Skip to content
Veltoryx Technologies
JavaDSAInterviewsData StructuresAlgorithmsCheat Sheet·10 min read

Java DSA Interview – Complete Methods & Syntax Cheat Sheet

The ultimate quick-reference cheat sheet for Java DSA coding interviews — covering essential Java 8+ syntax, collection methods, and LeetCode problem-solving patterns.

V

Vivek Adarsh

Founder & Systems Architect, Veltoryx Technologies · Published November 24, 2026

For a Java DSA interview, you should be comfortable with three things:

  1. Java syntax: Writing code quickly without searching for methods.
  2. Collections API: Knowing which data structure and methods to use.
  3. Problem-solving patterns: Sliding Window, Two Pointers, Binary Search, BFS, DFS, DP, etc.

Since you're preparing for senior-level Java backend interviews, I'll focus on Java 8+ syntax, commonly used collection methods, and coding interview patterns.


1. String – Most frequently used

StringMethods.java
String s = "hello world";

// Length
s.length();

// Character access
s.charAt(0);

// Substring
s.substring(1);
s.substring(1, 4); // end index excluded

// Comparison
s.equals("hello");
s.equalsIgnoreCase("HELLO");
s.compareTo("world");

// Search
s.indexOf('l');
s.lastIndexOf('l');
s.contains("world");

// Modification (creates new String)
s.toLowerCase();
s.toUpperCase();
s.trim();
s.strip();              // Java 11
s.replace('l', 'x');
s.replace("hello", "hi");

// Split
String[] arr = s.split(" ");

// Convert
char[] chars = s.toCharArray();
String.valueOf(123);
Integer.parseInt("123");

// Check
s.isEmpty();
s.isBlank();            // Java 11

Important interview concepts:

  • String is immutable.
  • == compares references; equals() compares content.
  • substring(start, end) excludes the end index.
  • String concatenation inside loops can be inefficient.

2. StringBuilder

Use when repeatedly modifying strings.

StringBuilderMethods.java
StringBuilder sb = new StringBuilder();

sb.append("Hello");
sb.append(" World");

sb.insert(5, " Java");
sb.delete(0, 5);
sb.deleteCharAt(0);
sb.replace(0, 4, "Hi");
sb.reverse();

sb.charAt(0);
sb.setCharAt(0, 'A');

sb.length();
sb.toString();

Common interview use cases:

  • Reverse a string.
  • Palindrome.
  • Build output strings.
  • Remove characters.
  • Construct results efficiently.

3. Array

ArrayOperations.java
int[] arr = {10, 20, 30, 40};

arr.length;

// Access
arr[0];

// Update
arr[0] = 100;

// Sort
Arrays.sort(arr);

// Binary search (array must be sorted)
Arrays.binarySearch(arr, 30);

// Fill
Arrays.fill(arr, 0);

// Copy
int[] copy = Arrays.copyOf(arr, arr.length);

// Compare
Arrays.equals(arr, copy);

// Convert
String result = Arrays.toString(arr);

2D Array

MatrixTraversal.java
int[][] matrix = new int[3][3];

matrix.length;       // Rows
matrix[0].length;    // Columns

for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.println(matrix[i][j]);
    }
}

4. ArrayList

Very important

ArrayListMethods.java
List<Integer> list = new ArrayList<>();

// Add
list.add(10);
list.add(20);
list.add(1, 15);

// Get
list.get(0);

// Update
list.set(0, 100);

// Remove
list.remove(0);                  // By index
list.remove(Integer.valueOf(20)); // By value

// Search
list.contains(10);
list.indexOf(10);
list.lastIndexOf(10);

// Size
list.size();
list.isEmpty();

// Sort
Collections.sort(list);
list.sort(Collections.reverseOrder());

// Reverse
Collections.reverse(list);

// Min / Max
Collections.min(list);
Collections.max(list);

// Convert
int[] arr = list.stream().mapToInt(Integer::intValue).toArray();

// Iterate
for (int num : list) {
    System.out.println(num);
}

5. HashMap

Must know for interviews

Used for frequency counting, lookup, grouping, and prefix sums.

HashMapMethods.java
Map<Integer, Integer> map = new HashMap<>();

// Insert
map.put(1, 100);

// Get
map.get(1);
map.getOrDefault(2, 0);

// Insert only if absent
map.putIfAbsent(2, 200);

// Check
map.containsKey(1);
map.containsValue(100);

// Update
map.put(1, map.get(1) + 1);

// Frequency counting (very important)
map.put(num, map.getOrDefault(num, 0) + 1);

// Merge
map.merge(num, 1, Integer::sum);

// Remove
map.remove(1);

// Size
map.size();
map.isEmpty();

// Iterate keys
for (Integer key : map.keySet()) {
    System.out.println(key);
}

// Iterate values
for (Integer value : map.values()) {
    System.out.println(value);
}

// Iterate key-value pairs
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " " + entry.getValue());
}

Remember these three methods:

  • getOrDefault()
  • putIfAbsent()
  • merge()

6. HashSet

Used for unique elements, duplicate detection, and fast membership checks.

HashSetMethods.java
Set<Integer> set = new HashSet<>();

set.add(10);
set.add(20);
set.add(10); // Duplicate ignored

set.contains(10);
set.remove(10);
set.size();
set.isEmpty();
set.clear();

// Iterate
for (int num : set) {
    System.out.println(num);
}

Other useful sets:

SortedAndLinkedSets.java
Set<Integer> sortedSet = new TreeSet<>();
Set<Integer> linkedSet = new LinkedHashSet<>();
  • HashSet: Average $O(1)$ lookup.
  • TreeSet: $O(\log n)$, maintains sorted order.
  • LinkedHashSet: Maintains insertion order.

7. Queue

Used in BFS, level-order traversal, and scheduling problems.

QueueMethods.java
Queue<Integer> queue = new LinkedList<>();

// Insert
queue.offer(10);
queue.offer(20);

// Read first element
queue.peek();

// Remove first element
queue.poll();

// Size
queue.size();
queue.isEmpty();

// Iterate
for (int num : queue) {
    System.out.println(num);
}
MethodBehaviour
offer()Insert element
poll()Remove and return front; null if empty
peek()Read front without removing
add()Insert; may throw exception
remove()Remove front; throws if empty
element()Read front; throws if empty

8. Deque – Double Ended Queue

Useful for Sliding Window Maximum, palindrome checks and monotonic queue problems.

DequeMethods.java
Deque<Integer> deque = new ArrayDeque<>();

// Insert
deque.addFirst(10);
deque.addLast(20);

deque.offerFirst(5);
deque.offerLast(30);

// Read
deque.peekFirst();
deque.peekLast();

// Remove
deque.pollFirst();
deque.pollLast();

// Other
deque.size();
deque.isEmpty();
deque.clear();

Common pattern: Sliding Window Maximum

SlidingWindowMaximum.java
Deque<Integer> deque = new ArrayDeque<>();

for (int i = 0; i < nums.length; i++) {

    // Remove indexes outside window
    while (!deque.isEmpty() &&
           deque.peekFirst() <= i - k) {
        deque.pollFirst();
    }

    // Remove smaller elements
    while (!deque.isEmpty() &&
           nums[deque.peekLast()] <= nums[i]) {
        deque.pollLast();
    }

    deque.offerLast(i);

    if (i >= k - 1) {
        result[i - k + 1] = nums[deque.peekFirst()];
    }
}

9. Stack

Java's Stack class exists, but prefer Deque for modern interview solutions.

StackMethods.java
Deque<Integer> stack = new ArrayDeque<>();

// Push
stack.push(10);
stack.push(20);

// Read top
stack.peek();

// Remove top
stack.pop();

// Check
stack.isEmpty();
stack.size();
stack.clear();

Important methods:

MethodPurpose
push()Add to top
pop()Remove top
peek()Read top
isEmpty()Check empty

Common problems:

  • Valid Parentheses
  • Next Greater Element
  • Daily Temperatures
  • Largest Rectangle in Histogram
  • Monotonic Stack

10. PriorityQueue (Heap)

Very important

Used for Top K Elements, Kth Largest, scheduling, and merging sorted lists.

Min Heap – smallest element first

MinHeap.java
PriorityQueue<Integer> pq = new PriorityQueue<>();

pq.offer(30);
pq.offer(10);
pq.offer(20);

pq.peek(); // 10
pq.poll(); // 10

Max Heap – largest element first

MaxHeap.java
PriorityQueue<Integer> maxHeap =
    new PriorityQueue<>(Collections.reverseOrder());

maxHeap.offer(10);
maxHeap.offer(30);
maxHeap.offer(20);

maxHeap.peek(); // 30

Custom comparator

CustomComparatorPQ.java
PriorityQueue<int[]> pq = new PriorityQueue<>(
    (a, b) -> Integer.compare(a[1], b[1])
);

For a 2D array, this creates a min heap based on index 1.

Useful methods:

PriorityQueueMethods.java
pq.offer(value);
pq.add(value);
pq.poll();
pq.remove();
pq.peek();
pq.size();
pq.isEmpty();

11. LinkedList

LinkedListMethods.java
LinkedList<Integer> list = new LinkedList<>();

list.add(10);
list.addFirst(5);
list.addLast(20);

list.getFirst();
list.getLast();

list.removeFirst();
list.removeLast();

list.peekFirst();
list.peekLast();

list.pollFirst();
list.pollLast();

For custom linked-list interview questions:

ListNode.java
class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

Common syntax:

ReverseLinkedList.java
ListNode current = head;
ListNode previous = null;
ListNode next = null;

while (current != null) {
    next = current.next;
    current.next = previous;
    previous = current;
    current = next;
}

head = previous;

12. Sorting – Arrays and Collections

You should know both ascending and descending sorting.

Primitive array

SortPrimitiveArray.java
int[] arr = {5, 2, 8, 1};

Arrays.sort(arr);

Integer array descending

SortBoxedArrayDescending.java
Integer[] arr = {5, 2, 8, 1};

Arrays.sort(arr, Collections.reverseOrder());

List ascending / descending

SortList.java
Collections.sort(list);

Collections.sort(list, Collections.reverseOrder());

// Alternative
list.sort(Comparator.naturalOrder());
list.sort(Comparator.reverseOrder());

Sort 2D arrays

Sort2DArray.java
int[][] intervals = {
    {5, 8},
    {1, 3},
    {2, 6}
};

// Sort by starting value
Arrays.sort(intervals,
    (a, b) -> Integer.compare(a[0], b[0]));

Sort objects

Employee.java
class Employee {
    int age;
    String name;
}
SortObjects.java
employees.sort(
    Comparator.comparingInt(e -> e.age)
);

Descending:

SortObjectsDescending.java
employees.sort(
    Comparator.comparingInt((Employee e) -> e.age)
              .reversed()
);

Multiple conditions:

SortMultipleConditions.java
employees.sort(
    Comparator.comparingInt((Employee e) -> e.age)
              .thenComparing(e -> e.name)
);

13. Math Methods

Frequently used in mathematical DSA problems.

MathMethods.java
Math.max(a, b);
Math.min(a, b);

Math.abs(-10);

Math.pow(2, 3);

Math.sqrt(25);

Math.ceil(4.2);
Math.floor(4.8);
Math.round(4.5);

Math.log(10);
Math.log10(100);

Math.PI;

Important syntax:

MathFormulas.java
// Swap using temporary variable
int temp = a;
a = b;
b = temp;

// Avoid integer overflow in average
int mid = left + (right - left) / 2;

// Ceiling division for positive integers
int result = (n + k - 1) / k;

// GCD
static int gcd(int a, int b) {
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    return a;
}

// LCM
static long lcm(int a, int b) {
    return (long) a / gcd(a, b) * b;
}

14. Character Methods

Useful for string and character-frequency problems.

CharacterMethods.java
Character.isLetter(ch);
Character.isDigit(ch);
Character.isLetterOrDigit(ch);
Character.isUpperCase(ch);
Character.isLowerCase(ch);
Character.isWhitespace(ch);

Character.toLowerCase(ch);
Character.toUpperCase(ch);

ASCII conversion:

AsciiConversion.java
int value = ch - 'a'; // a = 0, b = 1...
int digit = ch - '0'; // '5' = 5

char ch = (char) ('a' + 2); // c

15. Java Streams – Java 8+

Not essential for every DSA solution, but useful to know.

StreamMethods.java
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5);

// Filter
nums.stream()
    .filter(n -> n % 2 == 0)
    .toList();

// Map
nums.stream()
    .map(n -> n * 2)
    .toList();

// Sum
int sum = nums.stream()
    .mapToInt(Integer::intValue)
    .sum();

// Max
int max = nums.stream()
    .mapToInt(Integer::intValue)
    .max()
    .orElse(0);

// Min
int min = nums.stream()
    .mapToInt(Integer::intValue)
    .min()
    .orElse(0);

// Count
long count = nums.stream()
    .filter(n -> n > 2)
    .count();

// Distinct
nums.stream().distinct().toList();

// Sort
nums.stream().sorted().toList();

// Descending
nums.stream()
    .sorted(Comparator.reverseOrder())
    .toList();

For coding interviews, prefer loops when they make the algorithm easier to explain and control.


16. Bit Manipulation

Very common in medium and hard DSA questions.

BitOperations.java
// Check ith bit
(n & (1 << i)) != 0;

// Set ith bit
n = n | (1 << i);

// Clear ith bit
n = n & ~(1 << i);

// Toggle ith bit
n = n ^ (1 << i);

// Check odd/even
(n & 1) == 1;

// Multiply by 2
n << 1;

// Divide by 2 (non-negative numbers)
n >> 1;

// Remove lowest set bit
n = n & (n - 1);

// Check power of 2
n > 0 && (n & (n - 1)) == 0;

// XOR
a ^ b;

Remember:

OperatorMeaning
&AND
|OR
^XOR
~NOT
<<Left shift
>>Signed right shift
>>>Unsigned right shift

17. Two-Dimensional Arrays and Matrix

MatrixTraversalPatterns.java
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

int rows = matrix.length;
int cols = matrix[0].length;

// Traverse
for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        System.out.println(matrix[i][j]);
    }
}

// Directions: Up, Down, Left, Right
int[] dx = {-1, 1, 0, 0};
int[] dy = {0, 0, -1, 1};

// Boundary check
if (nr >= 0 && nr < rows &&
    nc >= 0 && nc < cols) {
    // Valid cell
}

18. Graph – BFS and DFS Syntax

Adjacency List

GraphAdjacencyList.java
int n = 5;

List<List<Integer>> graph = new ArrayList<>();

for (int i = 0; i < n; i++) {
    graph.add(new ArrayList<>());
}

// Undirected edge
graph.get(0).add(1);
graph.get(1).add(0);

BFS

GraphBfs.java
boolean[] visited = new boolean[n];
Queue<Integer> queue = new LinkedList<>();

queue.offer(0);
visited[0] = true;

while (!queue.isEmpty()) {

    int node = queue.poll();

    for (int neighbor : graph.get(node)) {

        if (!visited[neighbor]) {
            visited[neighbor] = true;
            queue.offer(neighbor);
        }
    }
}

DFS – Recursive

GraphDfsRecursive.java
void dfs(int node,
         List<List<Integer>> graph,
         boolean[] visited) {

    visited[node] = true;

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            dfs(neighbor, graph, visited);
        }
    }
}

DFS – Iterative

GraphDfsIterative.java
Deque<Integer> stack = new ArrayDeque<>();

stack.push(0);
visited[0] = true;

while (!stack.isEmpty()) {

    int node = stack.pop();

    for (int neighbor : graph.get(node)) {
        if (!visited[neighbor]) {
            visited[neighbor] = true;
            stack.push(neighbor);
        }
    }
}

19. Binary Search Syntax

You should be able to write binary search without relying on Arrays.binarySearch().

StandardBinarySearch.java
int left = 0;
int right = nums.length - 1;

while (left <= right) {

    int mid = left + (right - left) / 2;

    if (nums[mid] == target) {
        return mid;
    }
    else if (nums[mid] < target) {
        left = mid + 1;
    }
    else {
        right = mid - 1;
    }
}

return -1;

Lower Bound – first element greater than or equal to target

LowerBound.java
int left = 0;
int right = nums.length;

while (left < right) {

    int mid = left + (right - left) / 2;

    if (nums[mid] < target) {
        left = mid + 1;
    } else {
        right = mid;
    }
}

return left;

Upper Bound – first element strictly greater than target

UpperBound.java
int left = 0;
int right = nums.length;

while (left < right) {

    int mid = left + (right - left) / 2;

    if (nums[mid] <= target) {
        left = mid + 1;
    } else {
        right = mid;
    }
}

return left;

20. Recursion and Backtracking

Common syntax for permutations, subsets and combinations.

BacktrackingTemplate.java
void backtrack(int index,
               int[] nums,
               List<Integer> current,
               List<List<Integer>> result) {

    if (index == nums.length) {
        result.add(new ArrayList<>(current));
        return;
    }

    // Choose
    current.add(nums[index]);

    backtrack(index + 1, nums, current, result);

    // Undo choice
    current.remove(current.size() - 1);

    // Do not choose
    backtrack(index + 1, nums, current, result);
}

21. Dynamic Programming (DP)

Know these common Java array initialization patterns.

1D DP

OneDimentionalDP.java
int[] dp = new int[n];

Arrays.fill(dp, -1);

2D DP

TwoDimentionalDP.java
int[][] dp = new int[n][m];

for (int[] row : dp) {
    Arrays.fill(row, -1);
}

Memoization

DpMemoization.java
int solve(int n, int[] dp) {

    if (n <= 1) {
        return n;
    }

    if (dp[n] != -1) {
        return dp[n];
    }

    return dp[n] = solve(n - 1, dp)
                 + solve(n - 2, dp);
}

Tabulation

DpTabulation.java
int[] dp = new int[n + 1];

dp[0] = 0;
dp[1] = 1;

for (int i = 2; i <= n; i++) {
    dp[i] = dp[i - 1] + dp[i - 2];
}

Other important DP operations:

DpInfInit.java
Arrays.fill(dp, Integer.MAX_VALUE);
Arrays.fill(dp, Integer.MIN_VALUE);

22. Useful Java Utility Methods

These methods frequently save time in interviews.

MethodPurpose
Arrays.sort(arr)Sort array
Arrays.fill(arr, x)Fill array
Arrays.copyOf(arr, n)Copy array
Arrays.equals(a, b)Compare arrays
Arrays.deepToString(arr)Print nested arrays
Collections.reverse(list)Reverse list
Collections.frequency(list, x)Count occurrences
Collections.swap(list, i, j)Swap elements
Collections.min(list)Minimum
Collections.max(list)Maximum
Collections.binarySearch(list, x)Binary search sorted list
Objects.equals(a, b)Null-safe equality
Integer.compare(a, b)Safe integer comparison
Long.compare(a, b)Safe long comparison

23. Common Java Syntax You Must Remember

These are small things that can cause unnecessary mistakes during interviews.

Array vs String vs Collection length

LengthSyntax.java
arr.length;
str.length();
list.size();
map.size();
set.size();

Loop syntax

LoopSyntax.java
// Normal loop
for (int i = 0; i < n; i++) {}

// Reverse loop
for (int i = n - 1; i >= 0; i--) {}

// Enhanced loop
for (int num : nums) {}

// While loop
while (left <= right) {}

Integer and Long

IntegerLongRanges.java
int max = Integer.MAX_VALUE;
int min = Integer.MIN_VALUE;

long maxLong = Long.MAX_VALUE;
long minLong = Long.MIN_VALUE;

When the sum can exceed the integer range:

SafeSumOverflow.java
long sum = 0;

for (int num : nums) {
    sum += num;
}

Conversions

TypeConversions.java
// String to Integer
int n = Integer.parseInt("123");

// Integer to String
String s = String.valueOf(123);

// String to Character array
char[] chars = s.toCharArray();

// Integer array to primitive array
int[] arr = list.stream()
                .mapToInt(Integer::intValue)
                .toArray();

// Primitive array to Integer array
Integer[] boxed = Arrays.stream(arr)
                        .boxed()
                        .toArray(Integer[]::new);

Ternary operator

TernaryOperator.java
int result = (a > b) ? a : b;

Swap

SwapElements.java
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

24. Which Data Structure Should You Use?

This is arguably more important than memorizing every method.

Problem requirementData structure
Fast key-value lookupHashMap
Find duplicatesHashSet
Frequency countingHashMap
Sorted unique valuesTreeSet
First In First OutQueue
Last In First OutStack / Deque
Sliding Window MaximumDeque
Kth Largest / SmallestPriorityQueue
Top K elementsPriorityQueue
Dynamic arrayArrayList
Fast insertion/removal at endsArrayDeque
Graph traversalAdjacency List
Prefix sum lookupHashMap
Range queriesSegment Tree / Fenwick Tree
Prefix-based string searchTrie

25. Time Complexity Cheat Sheet

Memorize these average/common complexities.

OperationTime complexity
Array access$O(1)$
Array search$O(n)$
Array sorting$O(n \log n)$
ArrayList get$O(1)$
ArrayList add at endAmortized $O(1)$
ArrayList insert at beginning$O(n)$
HashMap get / putAverage $O(1)$
HashSet containsAverage $O(1)$
TreeMap get / put$O(\log n)$
TreeSet add / contains$O(\log n)$
PriorityQueue offer / poll$O(\log n)$
PriorityQueue peek$O(1)$
Queue offer / poll$O(1)$ for ArrayDeque
Binary Search$O(\log n)$
BFS / DFS$O(V + E)$
Sliding WindowUsually $O(n)$
Merge Sort$O(n \log n)$
Interactive Engineering Platform

Explore Free Developer Tools & Interactive Tracks

Test data structures, format code, and master system design on the Veltoryx platform.

Written by Vivek Adarsh, Founder & Systems Architect, Veltoryx Technologies.

Related Engineering Articles