Some Handy Tricks Up Your Sleeves To Solve DSA Problems Quickly

Some Handy Tricks Up Your Sleeves To Solve DSA Problems Quickly

Working With Strings and StringBuilder

//Reverse a String
String reversed = new StringBuilder(str).reverse().toString();

//Check if String is palindrome

boolean isPalindrome = str.equals(new StringBuilder(str).reverse().toString());

//Count Occurrence of a character

long count = str.chars().filter(ch -> ch == <Character to Check>).count();

//split String into words

String[] words = str.split("\\s+");

//Remove Spaces and Special Characters

String cleaned = str.replaceAll("[^a-zA-Z0-9]", "");

//Delete Character in StringBuilder

sb.deleteCharAt(index);

//Sort characters in a string

char[] chars = str.toCharArray();
Arrays.sort(chars);
String sorted = new String(chars);

//substring 

String s = "hello world";
String sub = s.substring(0, 5); // Extracts "hello"
boolean contains = s.contains("world"); // true

// generate all substrings

String s = "abc";
for (int i = 0; i < s.length(); i++) {
    for (int j = i + 1; j <= s.length(); j++) {
        System.out.println(s.substring(i, j));
    }
}

//reverse substring
String s = "abcdef";
String reversed = new StringBuilder(s.substring(2, 5))
                                        .reverse().toString(); // "dcb"

// generate subsets of a string

String s = "abc";
int n = s.length();

for (int i = 0; i < (1 << n); i++) { // Loop from 0 to 2^n - 1
    StringBuilder subset = new StringBuilder();
    for (int j = 0; j < n; j++) {
        if ((i & (1 << j)) != 0) { // Check if the j-th bit is set
            subset.append(s.charAt(j));
        }
    }
    System.out.println(subset.toString());
}

Working With Characters

// Check if Character is Letter or Digit

if(Character.isLetter(ch)){/* your logic */}
if(Character.isDigit(ch)){/* your logic */}

//Convert char to int and int to char
int num = ch -'0'; //converts '2' to 2
char c = (char) (num + '0') //converts 2 to '2'

//Check if Character is a vowel
if("aeiouAEIOU".indexOf(ch) != -1) {/* character is a vowel */}

//Some other useful Character functions
Character.toLowerCase(ch)
Character.toUpperCase(ch)

// common ASCII values
'a' - 97
'A' - 65
'0' - 48

Working With Numbers

//GCD

public int gcd(int a , int b){
    return b == 0 ? a : (b, a % b);
}

// LCM


public int lcm(int a , int b){
    return (a * b) / gcd(a,b);
}

// Generate All Divisors
for (int j = 1; j * j <= n; j++) {
    if (n % j == 0) {
        System.out.println(j);
        if (j != n / j) {
            System.out.println(n / j);
        }
    }
}

// count digits in a number

int digits = (int) Math.log10(num) + 1;

//Reverse a Number

int reverse = 0;
while(num > 0){
    reversed = reversed * 10 + num % 10;
    num /= 10;
}

// If number is a power of 2

boolean isPowerOf2 = ( n & ( n -1 )) == 0;

// string to numbers

String str = "12345";

// Convert to integer for small numbers within INTEGER.MAX_VALUE
int number = Integer.parseInt(str);
System.out.println("Integer: " + number);

// Convert to long (if the number is larger) within Long.MAX_VALUE
long largeNumber = Long.parseLong(str);
System.out.println("Long: " + largeNumber);

// For very large numbers, use BigInteger for values beyond Long.MAX_VALUE
import java.math.BigInteger;
BigInteger bigNumber = new BigInteger(str);
System.out.println("BigInteger: " + bigNumber);

//Convert binary to decimal
int[] binaryArray = {1, 0, 0, 1};
public static int binaryToDecimal(int[] binaryArray) {
        int decimal = 0;
        for (int i = 0; i < binaryArray.length; i++) {
            decimal = decimal * 2 + binaryArray[i];
        }
        return decimal;
    }

// Convert decimal to other formats
 String binaryString = Integer.toBinaryString(decimal);
 String hexString = Integer.toHexString(decimal).toUpperCase();
 String octalString = Integer.toOctalString(decimal);

// working with binary string

String binary = "1011";
int num = Integer.parseInt(binary, 2); // Convert binary string to an integer
int result = num & 5; // Perform bitwise AND with another number
// Convert result back to binary
System.out.println(Integer.toBinaryString(result));

Working With Bits

// Set Bit at given position
int setBit = n | ( 1 << position ); 

// unSet Bit at given Position

int unsetBit = n & ~( 1 << position );

// toggle Bit at given Position

int toggleBit = n ^ ( 1 << position );

// toggle All bits

int toggleAll = ~n // returns 2's complement

// toggle Bits to Specific Range

int mask = ( 1 << (bits to toggle) ) - 1;
int toggle = ~num & mask;

// count bits in a number

int count = Integer.bitCount(num);

// check if ith bit is set

boolean isSet = ( n & ( 1 << i) ) != 0;

Working With Arrays

// Sort an Array

Arrays.sort(arr);

// find Max and Min value in array

int max = Arrays.stream(arr).max().getAsInt();
int min = Arrays.stream(arr).min().getAsInt();

//Prefix Sum of an Array (running total of elements of Array)

int[] prefixSum = new int[arr.length];
prefixSum[0] = arr[0];
for(int i=1;i<arr.length;i++)
{
    prefixSum[i] = prefixSum[i-1] + arr[i];
}

// finding prefixSum for given rage after calculating prefixSum

int sum = prefixSum[end] - ( start > 0 ? prefixSum[start -1] : 0)

// check if array is sorted

boolean isSorted = IntStream.range(1, a.length).allMatch(i -> a[i] >= a[i-1])

// All subsets of a array

int[] arr = {1, 2, 3};
int n = arr.length;

for (int i = 0; i < (1 << n); i++) { // Loop from 0 to 2^n - 1
    List<Integer> subset = new ArrayList<>();
    for (int j = 0; j < n; j++) {
        if ((i & (1 << j)) != 0) { // Check if the j-th bit is set
            subset.add(arr[j]);
        }
    }
    System.out.println(subset);
}

//Generate All permutations

public static void generatePermutations(int[] arr,
                                        List<Integer> current, 
                                        boolean[] used)
 {
    if (current.size() == arr.length) {
        System.out.println(current);
        return;
    }
    for (int i = 0; i < arr.length; i++) {
        if (!used[i]) {
            used[i] = true;
            current.add(arr[i]);
            generatePermutations(arr, current, used);
            current.remove(current.size() - 1);
            used[i] = false;
        }
    }
}

Working With Matrix

//iterating through a matrix
for(int i = 0; i < matrix.length; i++) //rows
{
    for(int j = 0; j < matrix[0].length; j++) //column
    {
        System.out.println(matrix[i][j]);
    }
}

// traversing Matrix in 4 directions

int[] dx = {0, 0, -1, 1}; // row direction: left, right, stay, stay
int[] dy = {-1, 1, 0, 0}; // column direction: left, right, stay, stay

for(int k = 0; k < 4; k++)
{
    int newRow = row + dx[k];
    int newCol = col + dy[k];

    //check boundaries 
    if(newRow >= 0 && newRow < matrix.length 
            && newCol >= 0 && newCol < matrix[0].length)
        {
             System.out.println(matrix[newRow][newCol]);
        } 
}

Working With Deque

        // Deque as Stack
        Deque<Integer> s = new ArrayDeque<>();
        s.addLast(1); System.out.println(s);
        s.addLast(2); System.out.println(s);
        s.addLast(3); System.out.println(s);
        s.removeLast(); System.out.println(s);
        s.removeLast(); System.out.println(s);

        //output
        /*
        [1]
        [1, 2]
        [1, 2, 3]
        [1, 2]
        [1]
        */

        // Deque as Queue
        Deque<Integer> q = new ArrayDeque<>();
        q.addLast(1); System.out.println(q);
        q.addLast(2); System.out.println(q);
        q.addLast(3); System.out.println(q);
        q.removeFirst(); System.out.println(q);
        q.removeFirst(); System.out.println(q);

        //output
        /*
        [1]
        [1, 2]
        [1, 2, 3]
        [2, 3]
        [3]
        */        

        // Deque as LinkedList
        Deque<Integer> ll = new ArrayDeque<>();
        ll.addLast(1); System.out.println(ll);
        ll.addLast(2); System.out.println(ll);
        ll.addFirst(0); System.out.println(ll);
        ll.removeLast(); System.out.println(ll);
        ll.removeFirst(); System.out.println(ll);

        //output
        /*
        [1]
        [1, 2]
        [0, 1, 2]
        [0, 1]
        [1]
        */