JD

Java DSA Interview Questions

103+ SDET / LEAD SDET INTERVIEW-READY QUESTIONS ยท JAVA ยท 2026 EDITION

Next Gen QA IT Coaching Classes
๐Ÿ“ž 8700350994
Manual Testing Selenium Playwright API Testing

How to Use This Sheet for Your SDET / Lead SDET Interview

Priority order: Recent 2026 interview reports show SDET rounds lean heavily on Strings, Arrays, HashMap/HashSet, Two Pointer and Sliding Window โ€” spend most of your practice time here before moving to Trees, Graphs and hard DP.

PriorityTopicSDET Importance
๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅStringsVery High
๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅArraysVery High
๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅHashMap / HashSetVery High
๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅTwo PointerHigh
๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅSliding WindowHigh
๐Ÿ”ฅ๐Ÿ”ฅSortingHigh
๐Ÿ”ฅ๐Ÿ”ฅBinary SearchHigh
๐Ÿ”ฅ๐Ÿ”ฅLinked ListMedium-High
๐Ÿ”ฅStack / QueueMedium
๐Ÿ”ฅRecursionMedium
๐Ÿ”ฅTreesMedium
๐Ÿ”ฅGraph / DPLower priority for typical SDET
โญ The SDET Interview Trick โ€” Don't Just Write the Code
  1. Clarify โ€” e.g. "Should I return unique duplicates or every duplicate occurrence?"
  2. Explain the approach โ€” e.g. "I'll use a HashSet; if add() returns false, it's already been seen."
  3. Write the code
  4. Give the output
  5. Give time & space complexity
  6. Discuss edge cases โ€” empty input, single element, all duplicates, nulls. This is the step interviewers weigh most for an SDET, since it shows how you think about testability.
Strings (Q001โ€“Q025 ยท 25 Questions)
Q001 Reverse a String Easy
Reverse a string without using StringBuilder.reverse().
Input: SDET โ†’ Output: TEDS
public class Main {

    public static String reverse(String str) {
        char[] arr = str.toCharArray();
        int left = 0, right = arr.length - 1;
        while (left < right) {
            char t = arr[left];
            arr[left] = arr[right];
            arr[right] = t;
            left++;
            right--;
        }
        return new String(arr);
    }

    public static void main(String[] args) {
        String input = "SDET";
        System.out.println(reverse(input));
    }
}
Time: O(n) | Space: O(n)
Q002 Check Palindrome Easy
Check whether a string reads the same forwards and backwards.
Input: madam โ†’ Output: Palindrome
public class Main {

    public static boolean isPalindrome(String str) {
        int left = 0, right = str.length() - 1;
        while (left < right) {
            if (str.charAt(left) != str.charAt(right)) return false;
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        String str = "madam";
        System.out.println(isPalindrome(str) ? "Palindrome" : "Not Palindrome");
    }
}
Time: O(n) | Space: O(1)
Q003 Find Duplicate Characters in a String Easy
Print every character that appears more than once in a string.
Input: programming โ†’ Output: r g m
import java.util.*;

public class Main {

    public static void duplicateChars(String str) {
        Map<Character, Integer> map = new HashMap<>();
        for (char ch : str.toCharArray())
            map.put(ch, map.getOrDefault(ch, 0) + 1);

        for (Map.Entry<Character, Integer> entry : map.entrySet())
            if (entry.getValue() > 1) System.out.println(entry.getKey());
    }

    public static void main(String[] args) {
        duplicateChars("programming");
    }
}
Time: O(n) | Space: O(n)
Q004 Count Character Occurrences Easy
Find the frequency of every character in a string.
Input: automation โ†’ Output: a=2, u=1, t=2, o=2, m=1, i=1, n=1
import java.util.*;

public class Main {

    public static Map<Character, Integer> charFrequency(String str) {
        Map<Character, Integer> map = new HashMap<>();
        for (char ch : str.toCharArray())
            map.put(ch, map.getOrDefault(ch, 0) + 1);
        return map;
    }

    public static void main(String[] args) {
        Map<Character, Integer> result = charFrequency("automation");
        for (Map.Entry<Character, Integer> entry : result.entrySet())
            System.out.println(entry.getKey() + " = " + entry.getValue());
    }
}
Time: O(n) | Space: O(n)
Q005 Find First Non-Repeated Character Easy
Find the first character in a string that does not repeat.
Input: aabbcde โ†’ Output: c
import java.util.*;

public class Main {

    public static char firstNonRepeated(String str) {
        Map<Character, Integer> map = new LinkedHashMap<>();
        for (char ch : str.toCharArray())
            map.put(ch, map.getOrDefault(ch, 0) + 1);

        for (Map.Entry<Character, Integer> entry : map.entrySet())
            if (entry.getValue() == 1) return entry.getKey();

        return '-';
    }

    public static void main(String[] args) {
        System.out.println(firstNonRepeated("aabbcde"));
    }
}
Time: O(n) | Space: O(n)
Q006 Check Two Strings Are Anagrams Easy
Check whether two strings are anagrams of each other.
Input: listen, silent โ†’ Output: true
import java.util.*;

public class Main {

    public static boolean isAnagram(String s1, String s2) {
        if (s1.length() != s2.length()) return false;

        Map<Character, Integer> map = new HashMap<>();
        for (char ch : s1.toCharArray()) map.put(ch, map.getOrDefault(ch, 0) + 1);

        for (char ch : s2.toCharArray()) {
            if (!map.containsKey(ch)) return false;
            map.put(ch, map.get(ch) - 1);
        }

        for (int count : map.values())
            if (count != 0) return false;

        return true;
    }

    public static void main(String[] args) {
        System.out.println(isAnagram("listen", "silent"));
    }
}
Time: O(n) | Space: O(n)
Q007 String Compression Medium
Compress a string using run-length counts of repeated characters.
Input: aaaabbbbbcc โ†’ Output: a4b5c2
public class Main {

    public static String compress(String str) {
        StringBuilder sb = new StringBuilder();
        int count = 1;

        for (int i = 1; i <= str.length(); i++) {
            if (i < str.length() && str.charAt(i) == str.charAt(i - 1)) {
                count++;
            } else {
                sb.append(str.charAt(i - 1)).append(count);
                count = 1;
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(compress("aaaabbbbbcc"));
    }
}
Time: O(n) | Space: O(n)
Q008 Reverse Words in a Sentence Easy
Reverse the order of words in a sentence (letters inside each word stay the same).
Input: I am SDET โ†’ Output: SDET am I
public class Main {

    public static String reverseWords(String str) {
        String[] words = str.split(" ");
        StringBuilder sb = new StringBuilder();
        for (int i = words.length - 1; i >= 0; i--)
            sb.append(words[i]).append(" ");
        return sb.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println(reverseWords("I am SDET"));
    }
}
Time: O(n) | Space: O(n)
Q009 Reverse Each Word (Keep Word Order) Easy
Reverse each individual word but keep the word order unchanged.
Input: I love Java โ†’ Output: I evol avaJ
public class Main {

    public static String reverseEachWord(String str) {
        String[] words = str.split(" ");
        StringBuilder result = new StringBuilder();
        for (String w : words)
            result.append(new StringBuilder(w).reverse()).append(" ");
        return result.toString().trim();
    }

    public static void main(String[] args) {
        System.out.println(reverseEachWord("I love Java"));
    }
}
Time: O(n) | Space: O(n)
Q010 Find the Longest Word in a Sentence Easy
Return the longest word from a sentence.
Input: I am automation engineer โ†’ Output: automation
public class Main {

    public static String longestWord(String str) {
        String longest = "";
        for (String w : str.split(" "))
            if (w.length() > longest.length()) longest = w;
        return longest;
    }

    public static void main(String[] args) {
        System.out.println(longestWord("I am automation engineer"));
    }
}
Time: O(n) | Space: O(1)
Q011 Count Words in a String Easy
Count the number of words in a sentence.
Input: Java Selenium API Testing โ†’ Output: 4
public class Main {

    public static int wordCount(String str) {
        return str.trim().split("\\s+").length;
    }

    public static void main(String[] args) {
        System.out.println(wordCount("Java Selenium API Testing"));
    }
}
Time: O(n) | Space: O(n)
Q012 Remove Duplicate Characters from a String Easy
Remove duplicate characters while keeping the first occurrence order.
Input: programming โ†’ Output: progamin
import java.util.*;

public class Main {

    public static String removeDuplicateChars(String str) {
        Set<Character> seen = new LinkedHashSet<>();
        for (char ch : str.toCharArray()) seen.add(ch);

        StringBuilder sb = new StringBuilder();
        for (char ch : seen) sb.append(ch);
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(removeDuplicateChars("programming"));
    }
}
Time: O(n) | Space: O(n)
Q013 Check String Contains Only Digits Easy
Validate that a string is made up entirely of digits.
Input: 123456 โ†’ Output: true
public class Main {

    public static boolean onlyDigits(String str) {
        for (char ch : str.toCharArray())
            if (!Character.isDigit(ch)) return false;
        return true;
    }

    public static void main(String[] args) {
        System.out.println(onlyDigits("123456"));
    }
}
Time: O(n) | Space: O(1)
Q014 Remove Spaces from a String Easy
Remove all whitespace from a string.
Input: Java Automation Testing โ†’ Output: JavaAutomationTesting
public class Main {

    public static String removeSpaces(String str) {
        return str.replaceAll("\\s", "");
    }

    public static void main(String[] args) {
        System.out.println(removeSpaces("Java Automation Testing"));
    }
}
Time: O(n) | Space: O(n)
Q015 Count Vowels and Consonants Easy
Count vowels and consonants in a string.
Input: automation โ†’ Output: Vowels=6, Consonants=4
public class Main {

    public static void countVowelsConsonants(String str) {
        int vowels = 0, consonants = 0;
        for (char ch : str.toLowerCase().toCharArray()) {
            if (Character.isLetter(ch)) {
                if ("aeiou".indexOf(ch) != -1) vowels++;
                else consonants++;
            }
        }
        System.out.println("Vowels = " + vowels);
        System.out.println("Consonants = " + consonants);
    }

    public static void main(String[] args) {
        countVowelsConsonants("automation");
    }
}
Time: O(n) | Space: O(1)
Q016 Longest Palindromic Substring Medium
Find the longest substring that is itself a palindrome.
Input: babad โ†’ Output: bab (or aba)
public class Main {

    public static String longestPalindrome(String s) {
        if (s == null || s.length() < 1) return "";
        int start = 0, end = 0;

        for (int i = 0; i < s.length(); i++) {
            int len1 = expand(s, i, i);
            int len2 = expand(s, i, i + 1);
            int len = Math.max(len1, len2);
            if (len > end - start + 1) {
                start = i - (len - 1) / 2;
                end = i + len / 2;
            }
        }
        return s.substring(start, end + 1);
    }

    private static int expand(String s, int l, int r) {
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            l--;
            r++;
        }
        return r - l - 1;
    }

    public static void main(String[] args) {
        System.out.println(longestPalindrome("babad"));
    }
}
Time: O(n^2) | Space: O(1)
Q017 Check if a String is a Rotation of Another Easy
Check whether string B is a rotation of string A.
Input: A=waterbottle, B=erbottlewat โ†’ Output: true
public class Main {

    public static boolean isRotation(String a, String b) {
        if (a.length() != b.length()) return false;
        return (a + a).contains(b);
    }

    public static void main(String[] args) {
        System.out.println(isRotation("waterbottle", "erbottlewat"));
    }
}
Time: O(n) | Space: O(n)
Q018 String to Integer (atoi) Medium
Convert a string to an integer, handling optional sign and leading spaces, without using Integer.parseInt().
Input: " -42" โ†’ Output: -42
public class Main {

    public static int myAtoi(String s) {
        s = s.trim();
        if (s.isEmpty()) return 0;

        int i = 0, sign = 1;
        long result = 0;

        if (s.charAt(0) == '+' || s.charAt(0) == '-') {
            sign = s.charAt(0) == '-' ? -1 : 1;
            i++;
        }

        while (i < s.length() && Character.isDigit(s.charAt(i))) {
            result = result * 10 + (s.charAt(i) - '0');
            if (result * sign > Integer.MAX_VALUE) return Integer.MAX_VALUE;
            if (result * sign < Integer.MIN_VALUE) return Integer.MIN_VALUE;
            i++;
        }
        return (int) (result * sign);
    }

    public static void main(String[] args) {
        System.out.println(myAtoi("   -42"));
    }
}
Time: O(n) | Space: O(1)
Q019 Group Anagrams Medium
Group a list of strings so that all anagrams end up in the same group.
Input: [eat,tea,tan,ate,nat,bat] โ†’ Output: [[eat,tea,ate],[tan,nat],[bat]]
import java.util.*;

public class Main {

    public static List<List<String>> groupAnagrams(String[] strs) {
        Map<String, List<String>> map = new HashMap<>();

        for (String str : strs) {
            char[] chars = str.toCharArray();
            Arrays.sort(chars);
            String key = new String(chars);
            map.computeIfAbsent(key, k -> new ArrayList<>()).add(str);
        }
        return new ArrayList<>(map.values());
    }

    public static void main(String[] args) {
        String[] input = {"eat", "tea", "tan", "ate", "nat", "bat"};
        System.out.println(groupAnagrams(input));
    }
}
Time: O(n * k log k) | Space: O(n * k)
Q020 Find All Permutations of a String Medium
Print every permutation of a given string.
Input: abc โ†’ Output: abc, acb, bac, bca, cab, cba
public class Main {

    public static void permute(String str, String current) {
        if (str.isEmpty()) {
            System.out.println(current);
            return;
        }
        for (int i = 0; i < str.length(); i++) {
            String rest = str.substring(0, i) + str.substring(i + 1);
            permute(rest, current + str.charAt(i));
        }
    }

    public static void main(String[] args) {
        permute("abc", "");
    }
}
Time: O(n * n!) | Space: O(n)
Q021 Check Isomorphic Strings Easy
Check whether characters of string A can be mapped one-to-one to characters of string B.
Input: egg, add โ†’ Output: true
import java.util.*;

public class Main {

    public static boolean isIsomorphic(String s, String t) {
        if (s.length() != t.length()) return false;

        Map<Character, Character> map = new HashMap<>();
        Set<Character> mapped = new HashSet<>();

        for (int i = 0; i < s.length(); i++) {
            char a = s.charAt(i), b = t.charAt(i);
            if (map.containsKey(a)) {
                if (map.get(a) != b) return false;
            } else {
                if (mapped.contains(b)) return false;
                map.put(a, b);
                mapped.add(b);
            }
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(isIsomorphic("egg", "add"));
    }
}
Time: O(n) | Space: O(n)
Q022 Longest Common Prefix Easy
Find the longest common prefix string amongst an array of strings.
Input: [flower,flow,flight] โ†’ Output: fl
public class Main {

    public static String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) return "";
        String prefix = strs[0];

        for (int i = 1; i < strs.length; i++) {
            while (!strs[i].startsWith(prefix)) {
                prefix = prefix.substring(0, prefix.length() - 1);
                if (prefix.isEmpty()) return "";
            }
        }
        return prefix;
    }

    public static void main(String[] args) {
        String[] input = {"flower", "flow", "flight"};
        System.out.println(longestCommonPrefix(input));
    }
}
Time: O(n * m) | Space: O(1)
Q023 Remove Adjacent Duplicates Easy
Repeatedly remove adjacent duplicate characters using a stack.
Input: abbaca โ†’ Output: ca
import java.util.*;

public class Main {

    public static String removeDuplicates(String s) {
        Deque<Character> stack = new ArrayDeque<>();

        for (char ch : s.toCharArray()) {
            if (!stack.isEmpty() && stack.peek() == ch) stack.pop();
            else stack.push(ch);
        }

        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) sb.append(stack.removeLast());
        return sb.toString();
    }

    public static void main(String[] args) {
        System.out.println(removeDuplicates("abbaca"));
    }
}
Time: O(n) | Space: O(n)
Q024 Count Palindromic Substrings Medium
Count how many substrings of a string are palindromes.
Input: aaa โ†’ Output: 6 (a,a,a,aa,aa,aaa)
public class Main {

    public static int countSubstrings(String s) {
        int count = 0;
        for (int center = 0; center < s.length(); center++) {
            count += expandCount(s, center, center);
            count += expandCount(s, center, center + 1);
        }
        return count;
    }

    private static int expandCount(String s, int l, int r) {
        int count = 0;
        while (l >= 0 && r < s.length() && s.charAt(l) == s.charAt(r)) {
            count++;
            l--;
            r++;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(countSubstrings("aaa"));
    }
}
Time: O(n^2) | Space: O(1)
Q025 Minimum Window Substring Hard
Find the smallest substring of S that contains every character of T (with frequency).
Input: S=ADOBECODEBANC, T=ABC โ†’ Output: BANC
import java.util.*;

public class Main {

    public static String minWindow(String s, String t) {
        Map<Character, Integer> need = new HashMap<>();
        for (char c : t.toCharArray()) need.merge(c, 1, Integer::sum);

        int required = need.size(), formed = 0, left = 0;
        Map<Character, Integer> window = new HashMap<>();
        int[] best = {-1, 0, 0};

        for (int right = 0; right < s.length(); right++) {
            char c = s.charAt(right);
            window.merge(c, 1, Integer::sum);

            if (need.containsKey(c) && window.get(c).intValue() == need.get(c).intValue())
                formed++;

            while (formed == required) {
                if (best[0] == -1 || right - left + 1 < best[0]) {
                    best[0] = right - left + 1;
                    best[1] = left;
                    best[2] = right;
                }
                char lc = s.charAt(left);
                window.put(lc, window.get(lc) - 1);
                if (need.containsKey(lc) && window.get(lc) < need.get(lc)) formed--;
                left++;
            }
        }
        return best[0] == -1 ? "" : s.substring(best[1], best[2] + 1);
    }

    public static void main(String[] args) {
        System.out.println(minWindow("ADOBECODEBANC", "ABC"));
    }
}
Time: O(n) | Space: O(k)
Arrays (Q026โ€“Q051 ยท 26 Questions)
Q026 Find Duplicate Elements in an Array Easy
Print every element that occurs more than once, using a HashSet.
Input: [10,20,30,20,40,10,50] โ†’ Output: 20 10
import java.util.*;

public class Main {

    public static void findDuplicates(int[] arr) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr)
            if (!set.add(num)) System.out.println(num);
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 20, 40, 10, 50};
        findDuplicates(arr);
    }
}
Time: O(n) | Space: O(n)
Q027 Find the Second Largest Element Easy
Find the second largest element in an array without sorting.
Input: [10,50,20,80,30] โ†’ Output: 50
public class Main {

    public static int secondLargest(int[] arr) {
        int largest = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
        for (int num : arr) {
            if (num > largest) {
                second = largest;
                largest = num;
            } else if (num > second && num != largest) {
                second = num;
            }
        }
        return second;
    }

    public static void main(String[] args) {
        int[] arr = {10, 50, 20, 80, 30};
        System.out.println(secondLargest(arr));
    }
}
Time: O(n) | Space: O(1)
Q028 Find the Missing Number Easy
Given numbers from 1 to N with one missing, find the missing number.
Input: [1,2,3,5], N=5 โ†’ Output: 4
public class Main {

    public static int findMissing(int[] arr, int n) {
        int expected = n * (n + 1) / 2;
        int actual = 0;
        for (int num : arr) actual += num;
        return expected - actual;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 5};
        System.out.println(findMissing(arr, 5));
    }
}
Time: O(n) | Space: O(1)
Q029 Move All Zeros to the End Easy
Move all zeros to the end while keeping the relative order of non-zero elements.
Input: [0,1,0,3,12] โ†’ Output: [1,3,12,0,0]
import java.util.*;

public class Main {

    public static void moveZeros(int[] arr) {
        int index = 0;
        for (int num : arr) if (num != 0) arr[index++] = num;
        while (index < arr.length) arr[index++] = 0;
    }

    public static void main(String[] args) {
        int[] arr = {0, 1, 0, 3, 12};
        moveZeros(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n) | Space: O(1)
Q030 Reverse an Array Easy
Reverse the elements of an array in place.
Input: [1,2,3,4,5] โ†’ Output: [5,4,3,2,1]
import java.util.*;

public class Main {

    public static void reverseArray(int[] arr) {
        int left = 0, right = arr.length - 1;
        while (left < right) {
            int t = arr[left];
            arr[left] = arr[right];
            arr[right] = t;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        reverseArray(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n) | Space: O(1)
Q031 Merge Two Sorted Arrays Easy
Merge two sorted arrays into a single sorted array.
Input: A=[1,3,5], B=[2,4,6] โ†’ Output: [1,2,3,4,5,6]
import java.util.*;

public class Main {

    public static int[] merge(int[] a, int[] b) {
        int[] result = new int[a.length + b.length];
        int i = 0, j = 0, k = 0;

        while (i < a.length && j < b.length)
            result[k++] = (a[i] <= b[j]) ? a[i++] : b[j++];

        while (i < a.length) result[k++] = a[i++];
        while (j < b.length) result[k++] = b[j++];

        return result;
    }

    public static void main(String[] args) {
        int[] a = {1, 3, 5};
        int[] b = {2, 4, 6};
        System.out.println(Arrays.toString(merge(a, b)));
    }
}
Time: O(n+m) | Space: O(n+m)
Q032 Maximum Subarray Sum (Kadane's Algorithm) Medium
Find the maximum sum of a contiguous subarray.
Input: [-2,1,-3,4,-1,2,1,-5,4] โ†’ Output: 6
public class Main {

    public static int maxSubArray(int[] arr) {
        int current = arr[0], maximum = arr[0];
        for (int i = 1; i < arr.length; i++) {
            current = Math.max(arr[i], current + arr[i]);
            maximum = Math.max(maximum, current);
        }
        return maximum;
    }

    public static void main(String[] args) {
        int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray(arr));
    }
}
Time: O(n) | Space: O(1)
Q033 Find Intersection of Two Arrays Easy
Find the common elements between two arrays.
Input: A=[1,2,3,4], B=[3,4,5,6] โ†’ Output: 3 4
import java.util.*;

public class Main {

    public static void intersection(int[] a, int[] b) {
        Set<Integer> set = new HashSet<>();
        for (int num : a) set.add(num);
        for (int num : b) if (set.contains(num)) System.out.println(num);
    }

    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4};
        int[] b = {3, 4, 5, 6};
        intersection(a, b);
    }
}
Time: O(n+m) | Space: O(n)
Q034 Find Majority Element (Boyer-Moore Voting) Medium
Find the element that appears more than n/2 times in an array.
Input: [2,2,1,1,1,2,2] โ†’ Output: 2
public class Main {

    public static int majorityElement(int[] arr) {
        int candidate = 0, count = 0;
        for (int num : arr) {
            if (count == 0) candidate = num;
            count += (num == candidate) ? 1 : -1;
        }
        return candidate;
    }

    public static void main(String[] args) {
        int[] arr = {2, 2, 1, 1, 1, 2, 2};
        System.out.println(majorityElement(arr));
    }
}
Time: O(n) | Space: O(1)
Q035 Find the Largest and Smallest Element Easy
Find both the largest and smallest elements in a single pass.
Input: [10,5,30,2,50,8] โ†’ Output: Smallest=2, Largest=50
public class Main {

    public static void minMax(int[] arr) {
        int min = arr[0], max = arr[0];
        for (int num : arr) {
            if (num < min) min = num;
            if (num > max) max = num;
        }
        System.out.println("Smallest = " + min);
        System.out.println("Largest = " + max);
    }

    public static void main(String[] args) {
        int[] arr = {10, 5, 30, 2, 50, 8};
        minMax(arr);
    }
}
Time: O(n) | Space: O(1)
Q036 Find the Third Largest Element Easy
Find the third largest distinct element in an array.
Input: [10,50,20,80,30,70] โ†’ Output: 50
public class Main {

    public static int thirdLargest(int[] arr) {
        int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE, third = Integer.MIN_VALUE;
        for (int num : arr) {
            if (num > first) {
                third = second;
                second = first;
                first = num;
            } else if (num > second && num != first) {
                third = second;
                second = num;
            } else if (num > third && num != second && num != first) {
                third = num;
            }
        }
        return third;
    }

    public static void main(String[] args) {
        int[] arr = {10, 50, 20, 80, 30, 70};
        System.out.println(thirdLargest(arr));
    }
}
Time: O(n) | Space: O(1)
Q037 Remove Duplicates from a Sorted Array Easy
Remove duplicates in place from a sorted array and return the new length.
Input: [1,1,2,2,3,4,4,5] โ†’ Output: [1,2,3,4,5]
import java.util.*;

public class Main {

    public static int removeDuplicates(int[] arr) {
        int index = 1;
        for (int i = 1; i < arr.length; i++)
            if (arr[i] != arr[i - 1]) arr[index++] = arr[i];
        return index;
    }

    public static void main(String[] args) {
        int[] arr = {1, 1, 2, 2, 3, 4, 4, 5};
        int newLength = removeDuplicates(arr);
        System.out.println(Arrays.toString(Arrays.copyOf(arr, newLength)));
    }
}
Time: O(n) | Space: O(1)
Q038 Find a Pair with a Given Difference Medium
Find a pair of elements whose absolute difference equals a target value.
Input: [5,20,3,2,50,80], diff=78 โ†’ Output: 2, 80
import java.util.*;

public class Main {

    public static void pairWithDifference(int[] arr, int diff) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr) {
            if (set.contains(num - diff)) System.out.println((num - diff) + ", " + num);
            if (set.contains(num + diff)) System.out.println((num + diff) + ", " + num);
            set.add(num);
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 20, 3, 2, 50, 80};
        pairWithDifference(arr, 78);
    }
}
Time: O(n) | Space: O(n)
Q039 Find All Pairs Whose Sum Equals a Target Easy
Print all pairs from an array whose sum equals a given target.
Input: [1,5,7,-1,5], target=6 โ†’ Output: 1+5, 7+-1
import java.util.*;

public class Main {

    public static void pairsWithSum(int[] arr, int target) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr) {
            int required = target - num;
            if (set.contains(required)) System.out.println(required + " + " + num);
            set.add(num);
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 5, 7, -1, 5};
        pairsWithSum(arr, 6);
    }
}
Time: O(n) | Space: O(n)
Q040 Rotate an Array Right by K Positions Medium
Rotate the array to the right by K positions in place.
Input: [1,2,3,4,5], K=2 โ†’ Output: [4,5,1,2,3]
import java.util.*;

public class Main {

    public static void rotate(int[] arr, int k) {
        k %= arr.length;
        reverse(arr, 0, arr.length - 1);
        reverse(arr, 0, k - 1);
        reverse(arr, k, arr.length - 1);
    }

    private static void reverse(int[] arr, int left, int right) {
        while (left < right) {
            int t = arr[left];
            arr[left] = arr[right];
            arr[right] = t;
            left++;
            right--;
        }
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        rotate(arr, 2);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n) | Space: O(1)
Q041 Find Leaders in an Array Medium
An element is a leader if no element to its right is greater than it.
Input: [16,17,4,3,5,2] โ†’ Output: 17 5 2
public class Main {

    public static void arrayLeaders(int[] arr) {
        int max = arr[arr.length - 1];
        System.out.print(max + " ");
        for (int i = arr.length - 2; i >= 0; i--) {
            if (arr[i] > max) {
                max = arr[i];
                System.out.print(max + " ");
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {16, 17, 4, 3, 5, 2};
        arrayLeaders(arr);
    }
}
Time: O(n) | Space: O(1)
Q042 Find the Equilibrium Index Medium
Find an index where the sum of elements on the left equals the sum on the right.
Input: [-7,1,5,2,-4,3,0] โ†’ Output: 3
public class Main {

    public static int equilibriumIndex(int[] arr) {
        int total = 0;
        for (int num : arr) total += num;

        int leftSum = 0;
        for (int i = 0; i < arr.length; i++) {
            total -= arr[i];
            if (leftSum == total) return i;
            leftSum += arr[i];
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {-7, 1, 5, 2, -4, 3, 0};
        System.out.println(equilibriumIndex(arr));
    }
}
Time: O(n) | Space: O(1)
Q043 Product of Array Except Self Medium
Return an array where each element is the product of all other elements, without using division.
Input: [1,2,3,4] โ†’ Output: [24,12,8,6]
import java.util.*;

public class Main {

    public static int[] productExceptSelf(int[] nums) {
        int n = nums.length;
        int[] result = new int[n];
        result[0] = 1;

        for (int i = 1; i < n; i++) result[i] = result[i - 1] * nums[i - 1];

        int right = 1;
        for (int i = n - 1; i >= 0; i--) {
            result[i] *= right;
            right *= nums[i];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4};
        System.out.println(Arrays.toString(productExceptSelf(arr)));
    }
}
Time: O(n) | Space: O(1) extra (excluding output)
Q044 Find a Peak Element Medium
Find an element that is greater than both its neighbours (binary search approach).
Input: [1,2,3,1] โ†’ Output: index 2 (value 3)
public class Main {

    public static int findPeakElement(int[] nums) {
        int left = 0, right = nums.length - 1;
        while (left < right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] > nums[mid + 1]) right = mid;
            else left = mid + 1;
        }
        return left;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 1};
        System.out.println("Peak index = " + findPeakElement(arr));
    }
}
Time: O(log n) | Space: O(1)
Q045 Sort an Array of 0s, 1s and 2s (Dutch National Flag) Medium
Sort an array containing only 0s, 1s and 2s in a single pass.
Input: [0,1,2,0,1,2] โ†’ Output: [0,0,1,1,2,2]
import java.util.*;

public class Main {

    public static void sortColors(int[] arr) {
        int low = 0, mid = 0, high = arr.length - 1;
        while (mid <= high) {
            if (arr[mid] == 0) swap(arr, low++, mid++);
            else if (arr[mid] == 1) mid++;
            else swap(arr, mid, high--);
        }
    }

    private static void swap(int[] arr, int i, int j) {
        int t = arr[i];
        arr[i] = arr[j];
        arr[j] = t;
    }

    public static void main(String[] args) {
        int[] arr = {0, 1, 2, 0, 1, 2};
        sortColors(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n) | Space: O(1)
Q046 Merge Overlapping Intervals Medium
Merge all overlapping intervals into non-overlapping ones.
Input: [[1,3],[2,6],[8,10],[15,18]] โ†’ Output: [[1,6],[8,10],[15,18]]
import java.util.*;

public class Main {

    public static int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        List<int[]> result = new ArrayList<>();

        for (int[] interval : intervals) {
            if (result.isEmpty() || result.get(result.size() - 1)[1] < interval[0]) {
                result.add(interval);
            } else {
                result.get(result.size() - 1)[1] =
                    Math.max(result.get(result.size() - 1)[1], interval[1]);
            }
        }
        return result.toArray(new int[0][]);
    }

    public static void main(String[] args) {
        int[][] intervals = {{1, 3}, {2, 6}, {8, 10}, {15, 18}};
        for (int[] interval : merge(intervals))
            System.out.println(Arrays.toString(interval));
    }
}
Time: O(n log n) | Space: O(n)
Q047 Find the Missing and Repeating Number Medium
An array of 1..N has one number missing and one repeated โ€” find both.
Input: [1,2,2,4] โ†’ Output: Missing=3, Repeating=2
public class Main {

    public static void findMissingAndRepeating(int[] arr) {
        int n = arr.length;
        int[] freq = new int[n + 1];
        int repeating = -1;

        for (int num : arr) {
            freq[num]++;
            if (freq[num] > 1) repeating = num;
        }

        int missing = -1;
        for (int i = 1; i <= n; i++) if (freq[i] == 0) missing = i;

        System.out.println("Missing = " + missing);
        System.out.println("Repeating = " + repeating);
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 4};
        findMissingAndRepeating(arr);
    }
}
Time: O(n) | Space: O(n)
Q048 Best Time to Buy and Sell Stock Easy
Given daily prices, find the maximum profit from one buy and one sell.
Input: [7,1,5,3,6,4] โ†’ Output: 5
public class Main {

    public static int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE, maxProfit = 0;
        for (int price : prices) {
            minPrice = Math.min(minPrice, price);
            maxProfit = Math.max(maxProfit, price - minPrice);
        }
        return maxProfit;
    }

    public static void main(String[] args) {
        int[] prices = {7, 1, 5, 3, 6, 4};
        System.out.println(maxProfit(prices));
    }
}
Time: O(n) | Space: O(1)
Q049 Trapping Rain Water Hard
Given elevation heights, compute how much rainwater can be trapped between bars.
Input: [0,1,0,2,1,0,1,3,2,1,2,1] โ†’ Output: 6
public class Main {

    public static int trap(int[] height) {
        int left = 0, right = height.length - 1;
        int leftMax = 0, rightMax = 0, water = 0;

        while (left < right) {
            if (height[left] <= height[right]) {
                leftMax = Math.max(leftMax, height[left]);
                water += leftMax - height[left];
                left++;
            } else {
                rightMax = Math.max(rightMax, height[right]);
                water += rightMax - height[right];
                right--;
            }
        }
        return water;
    }

    public static void main(String[] args) {
        int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        System.out.println(trap(height));
    }
}
Time: O(n) | Space: O(1)
Q050 Subarray With a Given Sum (Positive Numbers) Medium
Find a contiguous subarray (of positive numbers) that sums to a target value.
Input: [1,4,20,3,10,5], target=33 โ†’ Output: indices 2 to 4
public class Main {

    public static void subarraySum(int[] arr, int target) {
        int start = 0, sum = 0;
        for (int end = 0; end < arr.length; end++) {
            sum += arr[end];
            while (sum > target && start < end) {
                sum -= arr[start];
                start++;
            }
            if (sum == target) {
                System.out.println("Indices " + start + " to " + end);
                return;
            }
        }
        System.out.println("No subarray found");
    }

    public static void main(String[] args) {
        int[] arr = {1, 4, 20, 3, 10, 5};
        subarraySum(arr, 33);
    }
}
Time: O(n) | Space: O(1)
Q051 Maximum Product Subarray Medium
Find the contiguous subarray that has the largest product.
Input: [2,3,-2,4] โ†’ Output: 6
public class Main {

    public static int maxProduct(int[] nums) {
        int maxProd = nums[0], minProd = nums[0], result = nums[0];

        for (int i = 1; i < nums.length; i++) {
            int num = nums[i];
            if (num < 0) {
                int t = maxProd;
                maxProd = minProd;
                minProd = t;
            }
            maxProd = Math.max(num, maxProd * num);
            minProd = Math.min(num, minProd * num);
            result = Math.max(result, maxProd);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {2, 3, -2, 4};
        System.out.println(maxProduct(arr));
    }
}
Time: O(n) | Space: O(1)
Sorting (Q052โ€“Q054 ยท 3 Questions)
Q052 Sort an Array Without Arrays.sort() (Bubble Sort) Easy
Sort an array manually using bubble sort, without built-in sort methods.
Input: [5,2,8,1,3] โ†’ Output: [1,2,3,5,8]
import java.util.*;

public class Main {

    public static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                    int t = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = t;
                }
            }
        }
    }

    public static void main(String[] args) {
        int[] arr = {5, 2, 8, 1, 3};
        bubbleSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n^2) | Space: O(1)
Q053 Selection Sort Easy
Sort an array by repeatedly selecting the minimum element from the unsorted part.
Input: [29,10,14,37,13] โ†’ Output: [10,13,14,29,37]
import java.util.*;

public class Main {

    public static void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            int minIdx = i;
            for (int j = i + 1; j < arr.length; j++)
                if (arr[j] < arr[minIdx]) minIdx = j;
            int t = arr[minIdx];
            arr[minIdx] = arr[i];
            arr[i] = t;
        }
    }

    public static void main(String[] args) {
        int[] arr = {29, 10, 14, 37, 13};
        selectionSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n^2) | Space: O(1)
Q054 Insertion Sort Easy
Sort an array by inserting each element into its correct position in the sorted part.
Input: [12,11,13,5,6] โ†’ Output: [5,6,11,12,13]
import java.util.*;

public class Main {

    public static void insertionSort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            int key = arr[i], j = i - 1;
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j];
                j--;
            }
            arr[j + 1] = key;
        }
    }

    public static void main(String[] args) {
        int[] arr = {12, 11, 13, 5, 6};
        insertionSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}
Time: O(n^2) | Space: O(1)
Binary Search (Q055โ€“Q056 ยท 2 Questions)
Q055 Binary Search Easy
Search for a target value in a sorted array.
Input: [10,20,30,40,50], target=30 โ†’ Output: index 2
public class Main {

    public static int search(int[] arr, int target) {
        int left = 0, right = arr.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) return mid;
            if (arr[mid] < target) left = mid + 1;
            else right = mid - 1;
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 20, 30, 40, 50};
        System.out.println(search(arr, 30));
    }
}
Time: O(log n) | Space: O(1)
Q056 Find First and Last Occurrence of an Element Medium
Find the first and last position of a target value in a sorted array.
Input: [1,2,2,2,3,4], target=2 โ†’ Output: First=1, Last=3
public class Main {

    public static int firstOccurrence(int[] arr, int target) {
        int left = 0, right = arr.length - 1, result = -1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                result = mid;
                right = mid - 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }

    public static int lastOccurrence(int[] arr, int target) {
        int left = 0, right = arr.length - 1, result = -1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (arr[mid] == target) {
                result = mid;
                left = mid + 1;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 2, 3, 4};
        System.out.println("First = " + firstOccurrence(arr, 2));
        System.out.println("Last = " + lastOccurrence(arr, 2));
    }
}
Time: O(log n) | Space: O(1)
HashMap / HashSet (Q057โ€“Q066 ยท 10 Questions)
Q057 Two Sum Easy
Find the indices of two numbers whose sum equals a target value.
Input: [2,7,11,15], target=9 โ†’ Output: [0,1]
import java.util.*;

public class Main {

    public static int[] twoSum(int[] arr, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < arr.length; i++) {
            int complement = target - arr[i];
            if (map.containsKey(complement)) return new int[]{map.get(complement), i};
            map.put(arr[i], i);
        }
        return new int[]{};
    }

    public static void main(String[] args) {
        int[] arr = {2, 7, 11, 15};
        System.out.println(Arrays.toString(twoSum(arr, 9)));
    }
}
Time: O(n) | Space: O(n)
Q058 Find Common Elements in Three Arrays Medium
Find elements that are common to all three arrays.
Input: A,B,C โ†’ Output: 20 80
import java.util.*;

public class Main {

    public static void commonInThree(int[] a, int[] b, int[] c) {
        Set<Integer> setA = new HashSet<>();
        for (int n : a) setA.add(n);

        Set<Integer> setAB = new HashSet<>();
        for (int n : b) if (setA.contains(n)) setAB.add(n);

        for (int n : c) if (setAB.contains(n)) System.out.println(n);
    }

    public static void main(String[] args) {
        int[] a = {1, 5, 10, 20, 40, 80};
        int[] b = {6, 7, 20, 80, 100};
        int[] c = {3, 4, 15, 20, 30, 70, 80, 120};
        commonInThree(a, b, c);
    }
}
Time: O(n+m+k) | Space: O(n)
Q059 Find Frequency of Numbers in an Array Easy
Build a map of number-to-frequency for an array.
Input: [1,2,2,3,3,3,4] โ†’ Output: {1=1, 2=2, 3=3, 4=1}
import java.util.*;

public class Main {

    public static Map<Integer, Integer> frequency(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : arr) map.put(num, map.getOrDefault(num, 0) + 1);
        return map;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 2, 3, 3, 3, 4};
        System.out.println(frequency(arr));
    }
}
Time: O(n) | Space: O(n)
Q060 Find the First Repeated Element Easy
Find the first element that repeats while scanning left to right.
Input: [10,5,3,4,3,5,6] โ†’ Output: 3
import java.util.*;

public class Main {

    public static int firstRepeated(int[] arr) {
        Set<Integer> set = new HashSet<>();
        for (int num : arr)
            if (!set.add(num)) return num;
        return -1;
    }

    public static void main(String[] args) {
        int[] arr = {10, 5, 3, 4, 3, 5, 6};
        System.out.println(firstRepeated(arr));
    }
}
Time: O(n) | Space: O(n)
Q061 Find Elements Appearing More Than Once Easy
Print all elements that occur more than once in an array.
Input: [1,2,3,2,4,5,1,6,2] โ†’ Output: 1 2
import java.util.*;

public class Main {

    public static void repeatedElements(int[] arr) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int num : arr) map.put(num, map.getOrDefault(num, 0) + 1);

        for (Map.Entry<Integer, Integer> entry : map.entrySet())
            if (entry.getValue() > 1) System.out.println(entry.getKey());
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 2, 4, 5, 1, 6, 2};
        repeatedElements(arr);
    }
}
Time: O(n) | Space: O(n)
Q062 Three Sum Medium
Find all unique triplets in an array that sum to zero.
Input: [-1,0,1,2,-1,-4] โ†’ Output: [-1,-1,2], [-1,0,1]
import java.util.*;

public class Main {

    public static List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();

        for (int i = 0; i < nums.length - 2; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            int left = i + 1, right = nums.length - 1;

            while (left < right) {
                int sum = nums[i] + nums[left] + nums[right];
                if (sum == 0) {
                    result.add(Arrays.asList(nums[i], nums[left], nums[right]));
                    while (left < right && nums[left] == nums[left + 1]) left++;
                    while (left < right && nums[right] == nums[right - 1]) right--;
                    left++;
                    right--;
                } else if (sum < 0) {
                    left++;
                } else {
                    right--;
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {-1, 0, 1, 2, -1, -4};
        System.out.println(threeSum(nums));
    }
}
Time: O(n^2) | Space: O(n)
Q063 Four Sum Medium
Find all unique quadruplets in an array that sum to a target value.
Input: [1,0,-1,0,-2,2], target=0 โ†’ Output: [-2,-1,1,2], [-2,0,0,2], [-1,0,0,1]
import java.util.*;

public class Main {

    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> result = new ArrayList<>();
        int n = nums.length;

        for (int i = 0; i < n - 3; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) continue;
            for (int j = i + 1; j < n - 2; j++) {
                if (j > i + 1 && nums[j] == nums[j - 1]) continue;
                int left = j + 1, right = n - 1;

                while (left < right) {
                    long sum = (long) nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum == target) {
                        result.add(Arrays.asList(nums[i], nums[j], nums[left], nums[right]));
                        while (left < right && nums[left] == nums[left + 1]) left++;
                        while (left < right && nums[right] == nums[right - 1]) right--;
                        left++;
                        right--;
                    } else if (sum < target) {
                        left++;
                    } else {
                        right--;
                    }
                }
            }
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 0, -1, 0, -2, 2};
        System.out.println(fourSum(nums, 0));
    }
}
Time: O(n^3) | Space: O(n)
Q064 Top K Frequent Elements Medium
Return the K most frequently occurring elements in an array.
Input: [1,1,1,2,2,3], k=2 โ†’ Output: [1,2]
import java.util.*;

public class Main {

    public static int[] topKFrequent(int[] nums, int k) {
        Map<Integer, Integer> freq = new HashMap<>();
        for (int num : nums) freq.put(num, freq.getOrDefault(num, 0) + 1);

        PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> freq.get(a) - freq.get(b));
        for (int key : freq.keySet()) {
            heap.offer(key);
            if (heap.size() > k) heap.poll();
        }

        int[] result = new int[k];
        for (int i = k - 1; i >= 0; i--) result[i] = heap.poll();
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 1, 2, 2, 3};
        System.out.println(Arrays.toString(topKFrequent(nums, 2)));
    }
}
Time: O(n log k) | Space: O(n)
Q065 Longest Consecutive Sequence Medium
Find the length of the longest run of consecutive integers in an unsorted array.
Input: [100,4,200,1,3,2] โ†’ Output: 4 ([1,2,3,4])
import java.util.*;

public class Main {

    public static int longestConsecutive(int[] nums) {
        Set<Integer> set = new HashSet<>();
        for (int num : nums) set.add(num);

        int longest = 0;
        for (int num : set) {
            if (!set.contains(num - 1)) {
                int length = 1;
                while (set.contains(num + length)) length++;
                longest = Math.max(longest, length);
            }
        }
        return longest;
    }

    public static void main(String[] args) {
        int[] nums = {100, 4, 200, 1, 3, 2};
        System.out.println(longestConsecutive(nums));
    }
}
Time: O(n) | Space: O(n)
Q066 Subarray Sum Equals K Medium
Count the number of contiguous subarrays whose sum equals K.
Input: [1,1,1], k=2 โ†’ Output: 2
import java.util.*;

public class Main {

    public static int subarraySum(int[] nums, int k) {
        Map<Integer, Integer> prefixCount = new HashMap<>();
        prefixCount.put(0, 1);
        int sum = 0, count = 0;

        for (int num : nums) {
            sum += num;
            count += prefixCount.getOrDefault(sum - k, 0);
            prefixCount.put(sum, prefixCount.getOrDefault(sum, 0) + 1);
        }
        return count;
    }

    public static void main(String[] args) {
        int[] nums = {1, 1, 1};
        System.out.println(subarraySum(nums, 2));
    }
}
Time: O(n) | Space: O(n)
Two Pointer / Sliding Window (Q067โ€“Q070 ยท 4 Questions)
Q067 Longest Substring Without Repeating Characters Medium
Find the length of the longest substring without any repeating characters.
Input: abcabcbb โ†’ Output: 3 (abc)
import java.util.*;

public class Main {

    public static int lengthOfLongestSubstring(String s) {
        Set<Character> set = new HashSet<>();
        int left = 0, maxLength = 0;

        for (int right = 0; right < s.length(); right++) {
            while (set.contains(s.charAt(right))) {
                set.remove(s.charAt(left));
                left++;
            }
            set.add(s.charAt(right));
            maxLength = Math.max(maxLength, right - left + 1);
        }
        return maxLength;
    }

    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
    }
}
Time: O(n) | Space: O(n)
Q068 Maximum Sum of K Consecutive Elements Easy
Find the maximum sum of any K consecutive elements in an array.
Input: [2,1,5,1,3,2], k=3 โ†’ Output: 9
public class Main {

    public static int maxKSum(int[] arr, int k) {
        int windowSum = 0;
        for (int i = 0; i < k; i++) windowSum += arr[i];

        int maxSum = windowSum;
        for (int i = k; i < arr.length; i++) {
            windowSum += arr[i] - arr[i - k];
            maxSum = Math.max(maxSum, windowSum);
        }
        return maxSum;
    }

    public static void main(String[] args) {
        int[] arr = {2, 1, 5, 1, 3, 2};
        System.out.println(maxKSum(arr, 3));
    }
}
Time: O(n) | Space: O(1)
Q069 Smallest Subarray With a Given Sum Medium
Find the length of the smallest contiguous subarray whose sum is >= target.
Input: [2,1,5,2,3,2], target=7 โ†’ Output: 2 (5+2)
public class Main {

    public static int minSubArrayLen(int target, int[] arr) {
        int left = 0, sum = 0, minLength = Integer.MAX_VALUE;

        for (int right = 0; right < arr.length; right++) {
            sum += arr[right];
            while (sum >= target) {
                minLength = Math.min(minLength, right - left + 1);
                sum -= arr[left++];
            }
        }
        return minLength == Integer.MAX_VALUE ? 0 : minLength;
    }

    public static void main(String[] args) {
        int[] arr = {2, 1, 5, 2, 3, 2};
        System.out.println(minSubArrayLen(7, arr));
    }
}
Time: O(n) | Space: O(1)
Q070 Longest Substring With K Distinct Characters Medium
Find the length of the longest substring containing at most K distinct characters.
Input: araaci, k=2 โ†’ Output: 4 (araa)
import java.util.*;

public class Main {

    public static int longestKDistinct(String s, int k) {
        Map<Character, Integer> freq = new HashMap<>();
        int left = 0, maxLength = 0;

        for (int right = 0; right < s.length(); right++) {
            freq.merge(s.charAt(right), 1, Integer::sum);

            while (freq.size() > k) {
                char lc = s.charAt(left);
                freq.put(lc, freq.get(lc) - 1);
                if (freq.get(lc) == 0) freq.remove(lc);
                left++;
            }
            maxLength = Math.max(maxLength, right - left + 1);
        }
        return maxLength;
    }

    public static void main(String[] args) {
        System.out.println(longestKDistinct("araaci", 2));
    }
}
Time: O(n) | Space: O(k)
Stack / Queue (Q071โ€“Q078 ยท 8 Questions)
Q071 Check Balanced Parentheses (Valid Parentheses) Easy
Check whether brackets in a string are balanced and correctly nested.
Input: {[()]} โ†’ Output: Balanced
import java.util.*;

public class Main {

    public static boolean isBalanced(String str) {
        Deque<Character> stack = new ArrayDeque<>();

        for (char ch : str.toCharArray()) {
            if (ch == '(' || ch == '{' || ch == '[') {
                stack.push(ch);
            } else {
                if (stack.isEmpty()) return false;
                char top = stack.pop();
                if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '['))
                    return false;
            }
        }
        return stack.isEmpty();
    }

    public static void main(String[] args) {
        System.out.println(isBalanced("{[()]}"));
    }
}
Time: O(n) | Space: O(n)
Q072 Reverse a Stack (Without Extra Stack) Medium
Reverse the elements of a stack using recursion, without an auxiliary stack.
Input: [1,2,3,4] (top=4) โ†’ Output: [4,3,2,1] (top=1)
import java.util.*;

public class Main {

    public static void reverseStack(Deque<Integer> stack) {
        if (stack.isEmpty()) return;
        int top = stack.pop();
        reverseStack(stack);
        insertAtBottom(stack, top);
    }

    private static void insertAtBottom(Deque<Integer> stack, int value) {
        if (stack.isEmpty()) {
            stack.push(value);
            return;
        }
        int top = stack.pop();
        insertAtBottom(stack, value);
        stack.push(top);
    }

    public static void main(String[] args) {
        Deque<Integer> stack = new ArrayDeque<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        reverseStack(stack);
        System.out.println(stack);
    }
}
Time: O(n^2) | Space: O(n)
Q073 Implement a Stack Using a Queue Medium
Implement push, pop, peek and isEmpty for a Stack using only a Queue.
push(1); push(2); pop() โ†’ 2
import java.util.*;

public class Main {

    static class MyStack {
        Queue<Integer> queue = new LinkedList<>();

        public void push(int x) {
            queue.add(x);
            for (int i = 1; i < queue.size(); i++) queue.add(queue.poll());
        }

        public int pop() { return queue.poll(); }
        public int peek() { return queue.peek(); }
        public boolean isEmpty() { return queue.isEmpty(); }
    }

    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push(1);
        stack.push(2);
        System.out.println(stack.pop());
    }
}
push: O(n) | pop/peek: O(1)
Q074 Implement a Queue Using Two Stacks Medium
Implement enqueue, dequeue and peek for a Queue using two Stacks.
enqueue(1); enqueue(2); dequeue() โ†’ 1
import java.util.*;

public class Main {

    static class MyQueue {
        Deque<Integer> in = new ArrayDeque<>();
        Deque<Integer> out = new ArrayDeque<>();

        public void enqueue(int x) { in.push(x); }

        public int dequeue() {
            if (out.isEmpty())
                while (!in.isEmpty()) out.push(in.pop());
            return out.pop();
        }
    }

    public static void main(String[] args) {
        MyQueue queue = new MyQueue();
        queue.enqueue(1);
        queue.enqueue(2);
        System.out.println(queue.dequeue());
    }
}
Amortized: O(1) per operation
Q075 Next Greater Element Medium
For each element, find the next element to its right that is greater; use -1 if none exists.
Input: [4,5,2,10] โ†’ Output: [5,10,10,-1]
import java.util.*;

public class Main {

    public static int[] nextGreaterElement(int[] arr) {
        int n = arr.length;
        int[] result = new int[n];
        Deque<Integer> stack = new ArrayDeque<>();

        for (int i = n - 1; i >= 0; i--) {
            while (!stack.isEmpty() && stack.peek() <= arr[i]) stack.pop();
            result[i] = stack.isEmpty() ? -1 : stack.peek();
            stack.push(arr[i]);
        }
        return result;
    }

    public static void main(String[] args) {
        int[] arr = {4, 5, 2, 10};
        System.out.println(Arrays.toString(nextGreaterElement(arr)));
    }
}
Time: O(n) | Space: O(n)
Q076 Min Stack Medium
Design a stack that supports push, pop, top and retrieving the minimum element, all in O(1).
push(-2); push(0); push(-3); getMin() โ†’ -3
import java.util.*;

public class Main {

    static class MinStack {
        Deque<Integer> stack = new ArrayDeque<>();
        Deque<Integer> minStack = new ArrayDeque<>();

        public void push(int val) {
            stack.push(val);
            minStack.push(minStack.isEmpty() ? val : Math.min(val, minStack.peek()));
        }

        public void pop() { stack.pop(); minStack.pop(); }
        public int top() { return stack.peek(); }
        public int getMin() { return minStack.peek(); }
    }

    public static void main(String[] args) {
        MinStack minStack = new MinStack();
        minStack.push(-2);
        minStack.push(0);
        minStack.push(-3);
        System.out.println(minStack.getMin());
    }
}
Time: O(1) for all operations | Space: O(n)
Q077 Largest Rectangle in Histogram Hard
Given bar heights, find the area of the largest rectangle in the histogram.
Input: [2,1,5,6,2,3] โ†’ Output: 10
import java.util.*;

public class Main {

    public static int largestRectangleArea(int[] heights) {
        Deque<Integer> stack = new ArrayDeque<>();
        int maxArea = 0, n = heights.length;

        for (int i = 0; i <= n; i++) {
            int h = (i == n) ? 0 : heights[i];
            while (!stack.isEmpty() && heights[stack.peek()] >= h) {
                int height = heights[stack.pop()];
                int width = stack.isEmpty() ? i : i - stack.peek() - 1;
                maxArea = Math.max(maxArea, height * width);
            }
            stack.push(i);
        }
        return maxArea;
    }

    public static void main(String[] args) {
        int[] heights = {2, 1, 5, 6, 2, 3};
        System.out.println(largestRectangleArea(heights));
    }
}
Time: O(n) | Space: O(n)
Q078 Sliding Window Maximum Hard
Find the maximum element in every sliding window of size K.
Input: [1,3,-1,-3,5,3,6,7], k=3 โ†’ Output: [3,3,5,5,6,7]
import java.util.*;

public class Main {

    public static int[] maxSlidingWindow(int[] nums, int k) {
        Deque<Integer> deque = new ArrayDeque<>();
        int[] result = new int[nums.length - k + 1];

        for (int i = 0; i < nums.length; i++) {
            while (!deque.isEmpty() && deque.peekFirst() <= i - k) deque.pollFirst();
            while (!deque.isEmpty() && nums[deque.peekLast()] < nums[i]) deque.pollLast();
            deque.offerLast(i);
            if (i >= k - 1) result[i - k + 1] = nums[deque.peekFirst()];
        }
        return result;
    }

    public static void main(String[] args) {
        int[] nums = {1, 3, -1, -3, 5, 3, 6, 7};
        System.out.println(Arrays.toString(maxSlidingWindow(nums, 3)));
    }
}
Time: O(n) | Space: O(k)
Linked List (Q079โ€“Q088 ยท 10 Questions)
Q079 Reverse a Linked List Easy
Reverse a singly linked list in place.
Input: 1->2->3->4 โ†’ Output: 4->3->2->1
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node reverse(Node head) {
        Node previous = null, current = head;
        while (current != null) {
            Node next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }
        return previous;
    }

    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null) System.out.print(" -> ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);

        head = reverse(head);
        print(head);
    }
}
Time: O(n) | Space: O(1)
Q080 Find the Middle of a Linked List Easy
Find the middle node of a linked list using slow/fast pointers.
Input: 1->2->3->4->5 โ†’ Output: 3
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node findMiddle(Node head) {
        Node slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        System.out.println(findMiddle(head).data);
    }
}
Time: O(n) | Space: O(1)
Q081 Detect a Loop in a Linked List (Floyd's Cycle Detection) Medium
Detect whether a linked list has a cycle.
Input: 1->2->3->4->2 (cycle) โ†’ Output: true
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static boolean hasCycle(Node head) {
        Node slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = head; // creates a cycle

        System.out.println(hasCycle(head));
    }
}
Time: O(n) | Space: O(1)
Q082 Remove Duplicate Nodes from a Linked List Easy
Remove duplicate values from a sorted linked list.
Input: 1->2->2->3->3->4 โ†’ Output: 1->2->3->4
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node removeDuplicates(Node head) {
        Node current = head;
        while (current != null && current.next != null) {
            if (current.data == current.next.data)
                current.next = current.next.next;
            else
                current = current.next;
        }
        return head;
    }

    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data);
            if (head.next != null) System.out.print(" -> ");
            head = head.next;
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(2);
        head.next.next.next = new Node(3);
        head.next.next.next.next = new Node(3);
        head.next.next.next.next.next = new Node(4);

        head = removeDuplicates(head);
        print(head);
    }
}
Time: O(n) | Space: O(1)
Q083 Find the Nth Node From the End Medium
Find the Nth node from the end of a linked list using two pointers.
Input: 1->2->3->4->5, N=2 โ†’ Output: 4
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node nthFromEnd(Node head, int n) {
        Node fast = head, slow = head;
        for (int i = 0; i < n; i++) fast = fast.next;
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = new Node(5);

        System.out.println(nthFromEnd(head, 2).data);
    }
}
Time: O(n) | Space: O(1)
Q084 Remove a Cycle from a Linked List Medium
Detect a cycle and remove it so the list becomes a normal singly linked list.
Input: 1->2->3->4->2 (cycle) โ†’ Output: 1->2->3->4->null
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static void removeCycle(Node head) {
        Node slow = head, fast = head;
        boolean cycleFound = false;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) {
                cycleFound = true;
                break;
            }
        }
        if (!cycleFound) return;

        slow = head;
        if (slow == fast) {
            while (fast.next != slow) fast = fast.next;
        } else {
            while (slow.next != fast.next) {
                slow = slow.next;
                fast = fast.next;
            }
        }
        fast.next = null;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(4);
        head.next.next.next.next = head.next; // cycle back to node 2

        removeCycle(head);

        Node cur = head;
        while (cur != null) {
            System.out.print(cur.data + " ");
            cur = cur.next;
        }
    }
}
Time: O(n) | Space: O(1)
Q085 Merge Two Sorted Linked Lists Easy
Merge two sorted linked lists into one sorted linked list.
Input: 1->3->5, 2->4->6 โ†’ Output: 1->2->3->4->5->6
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node mergeTwoLists(Node l1, Node l2) {
        Node dummy = new Node(-1);
        Node tail = dummy;

        while (l1 != null && l2 != null) {
            if (l1.data <= l2.data) { tail.next = l1; l1 = l1.next; }
            else { tail.next = l2; l2 = l2.next; }
            tail = tail.next;
        }
        tail.next = (l1 != null) ? l1 : l2;
        return dummy.next;
    }

    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data + " ");
            head = head.next;
        }
    }

    public static void main(String[] args) {
        Node l1 = new Node(1);
        l1.next = new Node(3);
        l1.next.next = new Node(5);

        Node l2 = new Node(2);
        l2.next = new Node(4);
        l2.next.next = new Node(6);

        print(mergeTwoLists(l1, l2));
    }
}
Time: O(n+m) | Space: O(1)
Q086 Find the Intersection Point of Two Linked Lists Medium
Find the node at which two singly linked lists intersect.
Input: two lists merging at a common node โ†’ Output: the intersection node
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node getIntersectionNode(Node headA, Node headB) {
        Node a = headA, b = headB;
        while (a != b) {
            a = (a == null) ? headB : a.next;
            b = (b == null) ? headA : b.next;
        }
        return a;
    }

    public static void main(String[] args) {
        Node common = new Node(8);
        common.next = new Node(10);

        Node headA = new Node(3);
        headA.next = new Node(6);
        headA.next.next = common;

        Node headB = new Node(9);
        headB.next = common;

        Node result = getIntersectionNode(headA, headB);
        System.out.println(result != null ? result.data : "No Intersection");
    }
}
Time: O(n+m) | Space: O(1)
Q087 Check if a Linked List is a Palindrome Medium
Check whether a singly linked list reads the same forwards and backwards.
Input: 1->2->3->2->1 โ†’ Output: true
import java.util.*;

public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static boolean isPalindrome(Node head) {
        List<Integer> values = new ArrayList<>();
        for (Node cur = head; cur != null; cur = cur.next) values.add(cur.data);

        int left = 0, right = values.size() - 1;
        while (left < right) {
            if (!values.get(left).equals(values.get(right))) return false;
            left++;
            right--;
        }
        return true;
    }

    public static void main(String[] args) {
        Node head = new Node(1);
        head.next = new Node(2);
        head.next.next = new Node(3);
        head.next.next.next = new Node(2);
        head.next.next.next.next = new Node(1);

        System.out.println(isPalindrome(head));
    }
}
Time: O(n) | Space: O(n)
Q088 Add Two Numbers Represented by Linked Lists Medium
Add two numbers where each digit is stored as a node, in reverse order.
Input: 2->4->3 (342), 5->6->4 (465) โ†’ Output: 7->0->8 (807)
public class Main {

    static class Node {
        int data;
        Node next;
        Node(int data) { this.data = data; }
    }

    public static Node addTwoNumbers(Node l1, Node l2) {
        Node dummy = new Node(-1);
        Node current = dummy;
        int carry = 0;

        while (l1 != null || l2 != null || carry != 0) {
            int sum = carry;
            if (l1 != null) { sum += l1.data; l1 = l1.next; }
            if (l2 != null) { sum += l2.data; l2 = l2.next; }
            carry = sum / 10;
            current.next = new Node(sum % 10);
            current = current.next;
        }
        return dummy.next;
    }

    public static void print(Node head) {
        while (head != null) {
            System.out.print(head.data);
            head = head.next;
        }
    }

    public static void main(String[] args) {
        Node l1 = new Node(2);
        l1.next = new Node(4);
        l1.next.next = new Node(3); // represents 342

        Node l2 = new Node(5);
        l2.next = new Node(6);
        l2.next.next = new Node(4); // represents 465

        print(addTwoNumbers(l1, l2)); // 807
    }
}
Time: O(max(n,m)) | Space: O(max(n,m))
Recursion (Q089โ€“Q092 ยท 4 Questions)
Q089 Factorial of a Number Easy
Compute the factorial of a number using recursion.
Input: 5 โ†’ Output: 120
public class Main {

    static int factorial(int n) {
        if (n == 0 || n == 1) return 1;
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
        System.out.println(factorial(5));
    }
}
Time: O(n) | Space: O(n) (call stack)
Q090 Fibonacci Series Easy
Print the first N terms of the Fibonacci series (know recursive and iterative both).
Input: 7 โ†’ Output: 0 1 1 2 3 5 8
public class Main {

    static int fibonacci(int n) {
        if (n <= 1) return n;
        return fibonacci(n - 1) + fibonacci(n - 2);
    }

    static void fibonacciIterative(int n) {
        int a = 0, b = 1;
        for (int i = 0; i < n; i++) {
            System.out.print(a + " ");
            int next = a + b;
            a = b;
            b = next;
        }
    }

    public static void main(String[] args) {
        fibonacciIterative(7);
    }
}
Recursive: O(2^n) | Iterative: O(n)
Q091 Sum of Digits Easy
Find the sum of digits of a number using recursion.
Input: 12345 โ†’ Output: 15
public class Main {

    static int sum(int n) {
        if (n == 0) return 0;
        return n % 10 + sum(n / 10);
    }

    public static void main(String[] args) {
        System.out.println(sum(12345));
    }
}
Time: O(log n) | Space: O(log n)
Q092 Reverse a Number Easy
Reverse the digits of an integer.
Input: 12345 โ†’ Output: 54321
public class Main {

    static int reverseNumber(int n) {
        int reverse = 0;
        while (n != 0) {
            int digit = n % 10;
            reverse = reverse * 10 + digit;
            n /= 10;
        }
        return reverse;
    }

    public static void main(String[] args) {
        System.out.println(reverseNumber(12345));
    }
}
Time: O(log n) | Space: O(1)
Trees (Q093โ€“Q102 ยท 10 Questions)
Q093 Inorder Traversal (Left, Root, Right) Easy
Traverse a binary tree in inorder sequence.
Input: [1,null,2,3] โ†’ Output: [1,3,2]
import java.util.*;

public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static void inorder(TreeNode node, List<Integer> result) {
        if (node == null) return;
        inorder(node.left, result);
        result.add(node.val);
        inorder(node.right, result);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        List<Integer> result = new ArrayList<>();
        inorder(root, result);
        System.out.println(result);
    }
}
Time: O(n) | Space: O(h)
Q094 Preorder Traversal (Root, Left, Right) Easy
Traverse a binary tree in preorder sequence.
Input: [1,null,2,3] โ†’ Output: [1,2,3]
import java.util.*;

public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static void preorder(TreeNode node, List<Integer> result) {
        if (node == null) return;
        result.add(node.val);
        preorder(node.left, result);
        preorder(node.right, result);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        List<Integer> result = new ArrayList<>();
        preorder(root, result);
        System.out.println(result);
    }
}
Time: O(n) | Space: O(h)
Q095 Postorder Traversal (Left, Right, Root) Easy
Traverse a binary tree in postorder sequence.
Input: [1,null,2,3] โ†’ Output: [3,2,1]
import java.util.*;

public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static void postorder(TreeNode node, List<Integer> result) {
        if (node == null) return;
        postorder(node.left, result);
        postorder(node.right, result);
        result.add(node.val);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        List<Integer> result = new ArrayList<>();
        postorder(root, result);
        System.out.println(result);
    }
}
Time: O(n) | Space: O(h)
Q096 Level Order Traversal (BFS) Medium
Traverse a binary tree level by level using a queue.
Input: [3,9,20,null,null,15,7] โ†’ Output: [[3],[9,20],[15,7]]
import java.util.*;

public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) return result;

        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
            result.add(level);
        }
        return result;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        System.out.println(levelOrder(root));
    }
}
Time: O(n) | Space: O(n)
Q097 Maximum Depth of a Binary Tree Easy
Find the maximum depth (height) of a binary tree.
Input: [3,9,20,null,null,15,7] โ†’ Output: 3
public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static int maxDepth(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);

        System.out.println(maxDepth(root));
    }
}
Time: O(n) | Space: O(h)
Q098 Check if Two Trees Are Identical Easy
Check whether two binary trees are structurally identical with the same values.
Input: Tree A, Tree B โ†’ Output: true / false
public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null || p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    public static void main(String[] args) {
        TreeNode p = new TreeNode(1);
        p.left = new TreeNode(2);
        p.right = new TreeNode(3);

        TreeNode q = new TreeNode(1);
        q.left = new TreeNode(2);
        q.right = new TreeNode(3);

        System.out.println(isSameTree(p, q));
    }
}
Time: O(n) | Space: O(h)
Q099 Validate a Binary Search Tree Medium
Check whether a binary tree satisfies the binary search tree property.
Input: [2,1,3] โ†’ Output: true
public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static boolean isValidBST(TreeNode node, Long min, Long max) {
        if (node == null) return true;
        if ((min != null && node.val <= min) || (max != null && node.val >= max)) return false;
        return isValidBST(node.left, min, (long) node.val)
            && isValidBST(node.right, (long) node.val, max);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(2);
        root.left = new TreeNode(1);
        root.right = new TreeNode(3);

        System.out.println(isValidBST(root, null, null));
    }
}
Time: O(n) | Space: O(h)
Q100 Lowest Common Ancestor in a BST Medium
Find the lowest common ancestor of two nodes in a binary search tree.
Input: root, p=2, q=8 โ†’ Output: 6
public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode current = root;
        while (current != null) {
            if (p.val < current.val && q.val < current.val) current = current.left;
            else if (p.val > current.val && q.val > current.val) current = current.right;
            else return current;
        }
        return null;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(6);
        root.left = new TreeNode(2);
        root.right = new TreeNode(8);
        root.left.left = new TreeNode(0);
        root.left.right = new TreeNode(4);

        TreeNode p = root.left;
        TreeNode q = root.left.right;

        System.out.println(lowestCommonAncestor(root, p, q).val);
    }
}
Time: O(h) | Space: O(1)
Q101 Diameter of a Binary Tree Medium
Find the length of the longest path between any two nodes in a binary tree.
Input: [1,2,3,4,5] โ†’ Output: 3
public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    static int diameter = 0;

    public static int diameterOfBinaryTree(TreeNode root) {
        depth(root);
        return diameter;
    }

    private static int depth(TreeNode node) {
        if (node == null) return 0;
        int left = depth(node.left);
        int right = depth(node.right);
        diameter = Math.max(diameter, left + right);
        return 1 + Math.max(left, right);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        System.out.println(diameterOfBinaryTree(root));
    }
}
Time: O(n) | Space: O(h)
Q102 Search in a Binary Search Tree Easy
Search for a value in a binary search tree and return the subtree rooted at it.
Input: root, target=2 โ†’ Output: node with value 2
public class Main {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    public static TreeNode searchBST(TreeNode root, int val) {
        if (root == null || root.val == val) return root;
        return (val < root.val) ? searchBST(root.left, val) : searchBST(root.right, val);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(4);
        root.left = new TreeNode(2);
        root.right = new TreeNode(7);
        root.left.left = new TreeNode(1);
        root.left.right = new TreeNode(3);

        TreeNode result = searchBST(root, 2);
        System.out.println(result != null ? result.val : "Not Found");
    }
}
Time: O(h) | Space: O(h)
Warm-Up Basics (Q103โ€“Q103 ยท 1 Questions)
Q103 FizzBuzz Easy
Print numbers 1 to N; multiples of 3 print Fizz, multiples of 5 print Buzz, multiples of both print FizzBuzz.
Input: 1 to 15 โ†’ Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
public class Main {

    public static void fizzBuzz(int n) {
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) System.out.println("FizzBuzz");
            else if (i % 3 == 0) System.out.println("Fizz");
            else if (i % 5 == 0) System.out.println("Buzz");
            else System.out.println(i);
        }
    }

    public static void main(String[] args) {
        fizzBuzz(15);
    }
}
Time: O(n) | Space: O(1)