103+ SDET / LEAD SDET INTERVIEW-READY QUESTIONS ยท JAVA ยท 2026 EDITION
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.
| Priority | Topic | SDET Importance |
|---|---|---|
| ๐ฅ๐ฅ๐ฅ | Strings | Very High |
| ๐ฅ๐ฅ๐ฅ | Arrays | Very High |
| ๐ฅ๐ฅ๐ฅ | HashMap / HashSet | Very High |
| ๐ฅ๐ฅ๐ฅ | Two Pointer | High |
| ๐ฅ๐ฅ๐ฅ | Sliding Window | High |
| ๐ฅ๐ฅ | Sorting | High |
| ๐ฅ๐ฅ | Binary Search | High |
| ๐ฅ๐ฅ | Linked List | Medium-High |
| ๐ฅ | Stack / Queue | Medium |
| ๐ฅ | Recursion | Medium |
| ๐ฅ | Trees | Medium |
| ๐ฅ | Graph / DP | Lower priority for typical SDET |
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));
}
}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");
}
}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");
}
}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());
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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"));
}
}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");
}
}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"));
}
}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"));
}
}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"));
}
}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));
}
}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", "");
}
}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"));
}
}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));
}
}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"));
}
}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"));
}
}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"));
}
}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);
}
}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));
}
}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));
}
}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));
}
}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));
}
}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)));
}
}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));
}
}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);
}
}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));
}
}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);
}
}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));
}
}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)));
}
}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);
}
}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);
}
}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));
}
}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);
}
}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));
}
}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)));
}
}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));
}
}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));
}
}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));
}
}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);
}
}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));
}
}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));
}
}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);
}
}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));
}
}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));
}
}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));
}
}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));
}
}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));
}
}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));
}
}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)));
}
}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);
}
}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));
}
}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));
}
}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);
}
}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));
}
}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));
}
}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)));
}
}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));
}
}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));
}
}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"));
}
}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));
}
}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));
}
}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));
}
}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("{[()]}"));
}
}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);
}
}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());
}
}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());
}
}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)));
}
}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());
}
}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));
}
}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)));
}
}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);
}
}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);
}
}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));
}
}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);
}
}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);
}
}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;
}
}
}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));
}
}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");
}
}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));
}
}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
}
}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));
}
}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);
}
}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));
}
}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));
}
}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);
}
}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);
}
}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);
}
}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));
}
}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));
}
}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));
}
}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));
}
}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);
}
}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));
}
}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");
}
}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);
}
}