Morris Traversal
#94 — Binary Tree Inorder Traversal
#99 — Recover Binary Search Tree
Your pattern-wise interview practice workspace
Work through the patterns and variants in your DSA roadmap, including the added String interview essentials. Star problems you want to revise, keep personal notes, and practise directly from a compact list.
These are informational only and are not included in your tracked problem totals.
#94 — Binary Tree Inorder Traversal
#99 — Recover Binary Search Tree
#5 — Longest Palindromic Substring
#647 — Palindromic Substrings
#28 — Find the Index of the First Occurrence in a String
#459 — Repeated Substring Pattern
#1334 — Find the City With the Smallest Number of Neighbors at a Threshold Distance
#1462 — Course Schedule IV
Segment Tree: #307 — Range Sum Query - Mutable; #699 — Falling Squares
Fenwick Tree: #307 — Range Sum Query - Mutable; #315 — Count of Smaller Numbers After Self; #327 — Count of Range Sum
Lazy Propagation and Sparse Table: revisit as techniques; the guide does not assign separate problems to them.
Practise Java collection/API choices with existing problems: #215 — Kth Largest Element in an Array; #347 — Top K Frequent Elements; #295 — Find Median from Data Stream.
#25 — Reverse Nodes in k-Group
#23 — Merge k Sorted Lists
#239 — Sliding Window Maximum
#76 — Minimum Window Substring
#42 — Trapping Rain Water
#124 — Binary Tree Maximum Path Sum
#297 — Serialize and Deserialize Binary Tree
#295 — Find Median from Data Stream
#460 — LFU Cache
#127 — Word Ladder
#269 — Alien Dictionary
#1192 — Critical Connections
#212 — Word Search II
#312 — Burst Balloons
#123 — Best Time to Buy and Sell Stock III
#188 — Best Time to Buy and Sell Stock IV
#1235 — Maximum Profit in Job Scheduling
The Hard Stretch shortlist and the three additional problems are taken from the guide’s closing study notes.
Look up Java collections, common operations, and their time and space costs. Copy examples as you practise.
Embedded from your uploaded Java_Collections_Interview_Notes_Expanded.html. Scroll to browse the pages; zoom using the controls.
Input and output are fundamental Java skills. Learn Scanner, buffered input for larger inputs, precise output formatting, and common input pitfalls.
Scanner is the easiest Java 8 compatible tool for reading standard input. Most online judges already provide input through System.in.
Use one Scanner on standard input.
import java.util.*;
Scanner sc = new Scanner(System.in);next() reads one whitespace-delimited word; nextLine() reads the remaining current line.
| METHOD | READS | TYPICAL TIME | EXTRA SPACE |
|---|---|---|---|
nextInt() | Next integer token | O(d) | O(d) buffering* |
nextLong() | Next long token | O(d) | O(d) buffering* |
nextDouble() | Next decimal token | O(d) | O(d) buffering* |
next() | Next word | O(k) | O(k) |
nextLine() | Remaining current line | O(k) | O(k) |
hasNext() | Whether another token exists | Input-dependent | Input-dependent |
d = numeric token length and k = text length. Scanner uses buffering and regular-expression parsing, so these are rough token-size guides, not strict per-call Java API guarantees.
int n = sc.nextInt();
long big = sc.nextLong();
double val = sc.nextDouble();
String word = sc.next();
char letter = sc.next().charAt(0); // first char of next wordThese loops are worth memorizing for coding assessments.
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++) a[i] = sc.nextInt();
int r = sc.nextInt(), c = sc.nextInt();
int[][] matrix = new int[r][c];
for (int i = 0; i < r; i++)
for (int j = 0; j < c; j++)
matrix[i][j] = sc.nextInt();After nextInt(), calling nextLine() first consumes the remainder of that line. If the next full line is the intended input, often use one extra sc.nextLine() first.
BufferedReader reads lines more efficiently for large inputs. Use StringTokenizer to extract whitespace-separated tokens.
import java.io.*;
import java.util.*;
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());One StringTokenizer created from one line does not automatically read the next line. For multiple lines, refill the tokenizer when it has no more tokens.
class FastScanner {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
StringTokenizer st;
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
String line = br.readLine();
if (line == null) return null; // EOF
st = new StringTokenizer(line);
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
}Reading n total characters is O(n) input work; each tokenization/parsing step depends on token length. BufferedReader uses internal buffers plus space for the current line. Fast input can be beneficial for large competitive-programming test cases.
Most DSA questions require exact output with no extra labels. Learn print, println, printf, and StringBuilder buffering.
| METHOD | BEHAVIOR | TIME | EXTRA SPACE |
|---|---|---|---|
print(x) | Output without newline | O(k) | Output-dependent |
println(x) | Output then newline | O(k) | Output-dependent |
printf(...) | Formatted output | Formatting-dependent | Formatting-dependent |
StringBuilder.append(x) | Build output buffer | O(k) amort. | O(k)* |
k is the amount of text produced. Printing also involves stream buffering and I/O costs; the table describes output-size scaling rather than an exact implementation guarantee. Builder capacity can grow as text is appended.
System.out.print(10 + " "); // Same line
System.out.println(20); // New line
System.out.printf(java.util.Locale.US, "%.2f%n", 3.14159);
StringBuilder out = new StringBuilder();
for (int i = 0; i < 5; i++) out.append(i).append(" ");
System.out.println(out.toString().trim());These errors can fail an online judge even if your algorithm is correct.
| TRAP | WHAT TO DO |
|---|---|
nextInt() then nextLine() | Consume the remainder of the previous line first if appropriate |
| End of input | Use hasNext() or hasNextInt() when the input count is unknown |
| Integer parsing | Integer.parseInt(" 12 ") fails; trim first |
| Very large input | Prefer buffered input / tokenizer |
| Wrong output format | Do not print prompts like “Enter a number” on judges |
| File input | Use System.in, not input.txt, unless explicitly required |
Scanner sc = new Scanner(System.in);
int age = sc.nextInt();
sc.nextLine(); // finish the number line
String name = sc.nextLine(); // actual next full linewhile (sc.hasNextInt()) {
int x = sc.nextInt();
System.out.println(x * 2);
}Three groups only: Math API, number theory/modulo, and overflow-safe arithmetic.
Use max/min in scans and DP, abs for distances; pow and sqrt return double.
int mx = Math.max(a, b), mn = Math.min(a, b); // Computes both maximum and minimum in constant time
long gap = Math.abs((long) a - b); // Gets nonnegative distance using long arithmetic
double root = Math.sqrt(49); // Computes square root; result has type double
double power = Math.pow(2, 10); // Raises a value to a power; result has type double
int rounded = (int) Math.round(3.6); // Rounds to nearest whole number and converts to intUseful for grouping, rounding and logarithmic calculations.
double up = Math.ceil(4.2), down = Math.floor(4.9); // Rounds one value upward and the other downward
long nearest = Math.round(4.6); // Rounds a double to the nearest long
double naturalLog = Math.log(10); // Computes natural logarithm using Math.log
double logBase2 = Math.log(8) / Math.log(2); // Computes logarithm base 2 using change of base
// Prefer exact integer techniques when precision matters.Euclidean algorithm; avoid multiplication overflow when computing LCM.
static long gcd(long a, long b) { // Defines a reusable Euclidean GCD helper
a = Math.abs(a); b = Math.abs(b); // Normalizes both operands to nonnegative values
while (b != 0) { long t = a % b; a = b; b = t; } // Runs Euclidean algorithm until remainder is zero
return a; // Returns the greatest common divisor
} // Closes the current loop, conditional, method or class
// For nonnegative inputs: lcm(a,b) = (a / gcd(a,b)) * b;
// If either is 0, lcm is 0. Multiplication may overflow.Normalize negative remainders, prevent overflow in products.
final long MOD = 1_000_000_007L; // Declares a common prime modulus for DSA problems
long sum = ((a % MOD) + (b % MOD)) % MOD; // Adds two residues under the modulus
sum = (sum + MOD) % MOD; // Normalizes negative remainder into nonnegative range
long product = ((a % MOD) * (b % MOD)) % MOD; // Multiplies reduced residues; check long overflow bounds
// Product is safe here only when reduced operands fit long.Promote before multiplication; beware Integer.MIN_VALUE absolute value.
int lo = Integer.MIN_VALUE, hi = Integer.MAX_VALUE; // Stores the minimum and maximum signed 32-bit integers
long product = (long) a * b; // Promotes before multiplication to avoid int overflow
long sum = (long) a + b; // Promotes before addition to avoid int overflow
int mid = left + (right - left) / 2; // Computes a binary-search midpoint more safely
// Math.abs(Integer.MIN_VALUE) still overflows.
// Math.addExact(a,b) throws on int overflow.Arrays store a fixed number of elements of one type. Indexing is O(1); insertion at a position requires shifting elements yourself.
Indices start at 0; the array length stays fixed.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.Arrays;The array {10, 20, 30} has positions 0 → 10, 1 → 20 and 2 → 30. The last valid index is arr.length - 1.
Values inside braces initialize a new array. new int[4] creates four integers initialized to zero. You cannot change an array’s length after creation.
int[] arr = {10, 20, 30};
int[] zeros = new int[4]; // {0, 0, 0, 0}
String[] words = {"cat", "dog"};| SYNTAX | MEANING |
|---|---|
int[] | Type: an array of integers |
arr | Variable that refers to the array |
new int[5] | Allocate five integer positions, each initially 0 |
arr.length | A field (not a method) holding the number of elements |
int[] is the type; arr is the variable; new int[5] allocates five positions. Unlike strings and lists, use .length, not .length() or .size().
int[] arr = new int[5];
arr[0] = 12; // update first element
int first = arr[0]; // read first element
int n = arr.length; // length is a fieldJava 2D arrays are arrays of arrays. Rows can have different lengths, so use grid[i].length when traversing potentially jagged arrays.
int[][] grid = {{1, 2, 3}, {4, 5, 6}};
int cell = grid[1][2]; // 6
int rows = grid.length;
int cols = grid[0].length;An array does not have add(), remove() or contains() methods. For insertion/deletion you shift values or create a new array. Arrays.asList(int[]) does not create a List
int[] a; declares a variable without allocating an array. a = new int[3]; allocates three zeros. int[] a = {1,2,3}; allocates and initializes in one statement.These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
arr[i] | Get element at index | O(1) | O(1) |
arr[i] = x | Replace element | O(1) | O(1) |
arr.length | Get fixed array length | O(1) | O(1) |
Arrays.sort(arr) | Sort an int[] ascending | O(n log n) worst | O(log n) typical stack |
Arrays.binarySearch(arr,x) | Search sorted array | O(log n) | O(1) |
Arrays.fill(arr,x) | Replace all elements | O(n) | O(1) |
Arrays.copyOf(arr,m) | Copy into length m | O(m) | O(m) |
Arrays.equals(a,b) | Compare elements | O(n) | O(1) |
Arrays.toString(arr) | Readable string representation | O(n) | O(n) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
int[] arr = {7, 3, 9};
int first = arr[0]; // 7
arr[1] = 8; // {7, 8, 9}
boolean found = false;
for (int x : arr) {
if (x == 9) found = true;
}Arrays have direct read/update but no built-in contains(). A general unsorted search takes O(n).
int[] a = {9, 1, 6};
Arrays.sort(a); // {1, 6, 9}
int index = Arrays.binarySearch(a, 6); // 1
int[] b = Arrays.copyOf(a, a.length);
System.out.println(Arrays.toString(b));Binary search requires sorted input. Arrays.copyOf creates another array; b = a would share the same underlying array.
int[] a = {1, 2};
int[] b = {1, 2};
System.out.println(a == b); // false
System.out.println(Arrays.equals(a, b)); // trueUse Arrays.equals for element-by-element comparison. == compares array references.
grid[row][column]. Rows may have different lengths, so use grid[r].length.Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
int[] a = {2, 4, 6};
for (int i = 0; i < a.length; i++) {
a[i] *= 2;
}Use this when you need the index, want to modify the array, or plan to use two pointers.
int[] a = {2, 4, 6};
for (int x : a) {
System.out.println(x);
}Changing x does not change the array element. Use an indexed loop to modify the original.
int[] a = {1, 2, 3, 4};
for (int i = a.length - 1; i >= 0; i--) {
System.out.println(a[i]);
}
int left = 0, right = a.length - 1;
while (left < right) {
int temp = a[left];
a[left] = a[right];
a[right] = temp;
left++; right--;
}Two pointers are useful for reversing, partitioning and processing from both ends.
int[][] grid = {{1, 2}, {3, 4}};
for (int r = 0; r < grid.length; r++) {
for (int c = 0; c < grid[r].length; c++) {
System.out.println(grid[r][c]);
}
}Nested loops visit every cell. Time is O(total number of elements).
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
int[] a = {1, 2, 3};
List<Integer> list = new ArrayList<>();
for (int x : a) list.add(x);Primitive arrays cannot be converted into a List<Integer> using Arrays.asList(a); that produces a single-element list containing the entire int[].
List<Integer> list = Arrays.asList(1, 2, 3);
int[] a = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
a[i] = list.get(i);
}Use this when a function expects a primitive array. Both conversions take O(n) time and O(n) output space.
int[] a = {1, 2, 2, 3};
Set<Integer> seen = new HashSet<>();
for (int x : a) seen.add(x);A set is useful for fast membership tests and removing duplicates, but it does not preserve array order.
int[] a = {2, 4, 6};
long[] prefix = new long[a.length + 1];
for (int i = 0; i < a.length; i++) {
prefix[i + 1] = prefix[i] + a[i];
}
int left = 0, right = 2;
long sum = prefix[right + 1] - prefix[left]; // 12A prefix array is a derived representation, not another collection type. Building it takes O(n) time and space; each inclusive range-sum query takes O(1).
ArrayList is a dynamic array: fast indexed reads, but middle insertions and deletions shift elements.
ArrayList grows when elements are added; inserting in the middle shifts later elements.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;List<Integer> is the interface type and new ArrayList<>() creates the implementation. Generic collections require Integer rather than primitive int.
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);Wrapping Arrays.asList(...) in new ArrayList<>(...) makes a resizable copy. The list returned by Arrays.asList alone has fixed size.
List<Integer> nums = new ArrayList<>(
Arrays.asList(3, 5, 7)
);
nums.add(9);| SYNTAX | MEANING |
|---|---|
List<Integer> | A list of Integer objects |
new ArrayList<>() | Constructs a resizable list |
Arrays.asList(1, 2, 3) | Supplies initial elements; alone it is a fixed-size list |
list.size() | Number of elements; capacity is not size |
The constructor argument 100 reserves initial capacity; it does not create 100 elements. Use size(), not length.
ArrayList<Integer> list = new ArrayList<>(100);
System.out.println(list.size()); // 0
list.add(42);
System.out.println(list.size()); // 1Valid indices run from 0 to size() - 1. get() reads, while set() replaces an existing position.
List<String> names = new ArrayList<>(Arrays.asList("A", "B"));
String first = names.get(0); // "A"
names.set(1, "C"); // [A, C]With ArrayList
These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
add(x) | Append element | O(1) amortized | O(1) amortized growth |
add(i,x) | Insert and shift later elements | O(n) | O(1) excl. growth |
get(i) | Read by index | O(1) | O(1) |
set(i,x) | Replace at index | O(1) | O(1) |
remove(i) | Remove by index; shift elements | O(n) | O(1) |
remove(Integer.valueOf(x)) | Remove first equal value | O(n) | O(1) |
contains(x) | Linear membership test | O(n) | O(1) |
indexOf(x) | First matching index or -1 | O(n) | O(1) |
size(), isEmpty() | List size / empty status | O(1) | O(1) |
Collections.sort(list) | Sort natural order | O(n log n) | O(n) worst |
clear() | Remove all elements | O(n) | O(1) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
List<Integer> list = new ArrayList<>(Arrays.asList(10, 30));
list.add(40); // [10, 30, 40]
list.add(1, 20); // [10, 20, 30, 40]
int x = list.get(2); // 30
list.set(0, 5); // [5, 20, 30, 40]Unlike set(index,value), add(index,value) inserts and shifts elements.
ArrayList<Integer> list = new ArrayList<>(
Arrays.asList(10, 20, 30)
);
list.remove(1); // removes 20 (index 1)
list.remove(Integer.valueOf(30)); // removes value 30This is an important overload distinction when elements are integers: remove(1) means index 1, not the value 1.
List<Integer> list = new ArrayList<>(Arrays.asList(7, 2, 5));
boolean found = list.contains(5);
int pos = list.indexOf(2);
Collections.sort(list); // [2, 5, 7]
boolean empty = list.isEmpty();ArrayList contains() is O(n); switch to a HashSet when repeated membership tests dominate.
add(index, value) (inserts) from set(index, value) (replaces).Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));
for (int i = 0; i < list.size(); i++) {
list.set(i, list.get(i) * 2);
}Choose this for indexed access or in-place replacement.
List<Integer> list = Arrays.asList(10, 20, 30);
for (int value : list) {
System.out.println(value);
}Choose this to read every value. Do not change the list’s structure with add() or remove() inside the loop.
List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4));
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) it.remove();
}Iterator removal avoids concurrent modification errors during traversal. You can also use list.removeIf(x -> x % 2 == 0).
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
int[] a = {1, 2, 3};
List<Integer> list = new ArrayList<>();
for (int x : a) list.add(x);
int[] back = new int[list.size()];
for (int i = 0; i < list.size(); i++) back[i] = list.get(i);Because int is primitive, conversions to/from Integer need boxing/unboxing. O(n) time and O(n) output space.
List<Integer> list = Arrays.asList(3, 3, 1, 2);
Set<Integer> unique = new HashSet<>(list);
List<Integer> result = new ArrayList<>(unique);Useful for deduplication or returning collection results. A HashSet does not preserve insertion order; use LinkedHashSet if order matters.
List<Integer> list = Arrays.asList(5, 6);
Integer[] arr = list.toArray(new Integer[0]);This produces Integer[], not primitive int[].
Learn immutable vs mutable text, essential methods and complexities, traversal and DSA-relevant conversions. No separate practice or readiness sections.
String represents immutable text; StringBuilder is a mutable buffer for efficient repeated editing; char is one UTF-16 code unit.
A String uses double quotes, a char uses single quotes.
String s = "banana";
char ch = 'b';
String empty = "";Choose it when you need repeated appends, reversals, or character updates.
StringBuilder sb = new StringBuilder();
StringBuilder fromText = new StringBuilder("hello");
sb.append("Java");
String result = sb.toString();String methods generally return a new String rather than modifying the original.
String s = "cat";
s.toUpperCase(); // Returned value ignored; s is still "cat"
s = s.toUpperCase(); // s is now "CAT"Use s.equals(t) for content comparison, not s == t. StringBuilder is better for repeated character additions inside loops.
Focus on methods that appear repeatedly in array/string DSA. n is string length; m is pattern/replacement length where relevant.
| METHOD | PURPOSE | TIME | EXTRA SPACE |
|---|---|---|---|
s.length() | Number of UTF-16 code units | O(1) | O(1) |
s.charAt(i) | Read character at index | O(1) | O(1) |
s.equals(t) | Compare content | O(n) worst | O(1) |
s.substring(a,b) | Copy range [a,b) | O(b-a) | O(b-a) |
s.indexOf(x) | Find substring / character | O(nm) worst* | O(1) typical |
s.toCharArray() | Convert into char array | O(n) | O(n) |
s.toLowerCase() | Lowercase text | O(n) | O(n) |
s.toUpperCase() | Uppercase text | O(n) | O(n) |
s.split(regex) | Split by regular expression | Varies | O(result) |
s.trim() | Trim edge whitespace | O(n) | O(n) worst |
sb.append(x) | Append to builder | O(k) amort. | O(k)* |
sb.setCharAt(i,c) | Change builder character | O(1) | O(1) |
sb.reverse() | Reverse builder | O(n) | O(1) |
sb.toString() | Make immutable String | O(n) | O(n) |
sb.deleteCharAt(i) | Delete and shift left | O(n) | O(1) |
*Substring search performance depends on the implementation and pattern; O(nm) is a conservative general bound. append copies the appended content and can resize the builder; adding one character is amortized O(1). Creating new Strings or arrays uses space proportional to produced content.
String s = "banana";
System.out.println(s.length()); // 6
System.out.println(s.charAt(1)); // a
System.out.println(s.substring(1, 4)); // ana
System.out.println(s.indexOf("na")); // 2
System.out.println(s.equals("banana")); // true
StringBuilder sb = new StringBuilder("cat");
sb.append("s"); // "cats"
sb.setCharAt(0, 'b'); // "bats"
sb.reverse(); // "stab"Character.isDigit(c), Character.isLetter(c), Character.isWhitespace(c), Character.toLowerCase(c) and Character.toUpperCase(c) are useful for parsing. They take O(1) time and extra space for a char input.
A String can be traversed by index or as a character array. Choose indexing when you need positions, two pointers, or neighboring characters.
String s = "hello";
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
System.out.println(i + ": " + c);
}for (char c : s.toCharArray()) {
System.out.println(c);
}Index traversal: O(n) time, O(1) extra space. toCharArray() traversal: O(n) time and O(n) additional space for the copied array. A Java char is not always an entire Unicode character; advanced Unicode problems may require code points.
These transformations show up in string reversal, token processing, parsing, and problems requiring a particular return type.
String s = "abc";
char[] chars = s.toCharArray(); // String → char[]
String restored = new String(chars); // char[] → String
StringBuilder sb = new StringBuilder(s); // String → builder
String back = sb.toString(); // builder → Stringint x = Integer.parseInt("123"); // String → int
long y = Long.parseLong("123456"); // String → long
String n = String.valueOf(123); // int → String
String[] parts = "red blue".split(" "); // String → tokens
String joined = String.join("-", parts); // tokens → StringText conversions that copy n characters use O(n) time and O(n) extra space. Parsing a number from n characters takes O(n) time and O(1) working space for fixed-width numeric primitives. Avoid conversions when direct indexed access is sufficient.
Learn the structure, essential methods and traversal first. Conversions are included only where they help with real DSA tasks. Each operation shows its time and extra-space cost.
What are you creating? A collection that connects a student name (key) to marks (value).
Java must know which collection class you want to use.
import java.util.HashMap;The first type is the key type; the second type is the value type.
HashMap<String, Integer> marks = new HashMap<>();| PART | MEANING |
|---|---|
HashMap | The collection class |
String | Key type (student name) |
Integer | Value type (marks) |
marks | Your variable name |
new HashMap<>() | Creates an empty map |
put(key, value) stores a pair. Using the same key again updates its value.
marks.put("Alice", 85);
marks.put("Bob", 92);
marks.put("Alice", 90); // Updates Alice, no duplicate keyChoose the key and value types based on what the problem needs.
HashMap<Integer, Integer> freq = new HashMap<>(); // Number → count
HashMap<Character, Integer> chars = new HashMap<>(); // Character → count
HashMap<Integer, String> names = new HashMap<>(); // ID → nameUse wrapper types like Integer and Character, not primitives like int and char. You may also write Map<String, Integer> marks = new HashMap<>();.
Learn these methods first. CRUD means create, read, update and delete. You do not need a separate CRUD API.
| METHOD | WHAT IT DOES | AVERAGE TIME | EXTRA SPACE |
|---|---|---|---|
put(k,v) | Insert or update a pair | O(1) | O(1)* |
get(k) | Get value; null if absent | O(1) | O(1) |
getOrDefault(k,d) | Return value or fallback | O(1) | O(1) |
containsKey(k) | Check whether key exists | O(1) | O(1) |
remove(k) | Remove a key-value pair | O(1) | O(1) |
size() | Count entries | O(1) | O(1) |
isEmpty() | Check empty map | O(1) | O(1) |
containsValue(v) | Check if any value matches | O(n) | O(1) |
clear() | Remove all entries | O(n + capacity) | O(1) |
keySet() | Get a live view of keys | O(1) | O(1) |
values() | Get a live view of values | O(1) | O(1) |
entrySet() | Get a live view of entries | O(1) | O(1) |
O(1) times are averages for hash-based lookup, insertion and deletion. Extra space means additional working memory per method, excluding the map itself. put() can allocate entries or resize the table, so its allocation is not always O(1) on an individual call. A HashMap storing n entries uses O(n) total space, assuming capacity is proportional to n. Iterating the entire map takes O(n + capacity) time and O(1) extra space with a for-each loop.
HashMap<String, Integer> marks = new HashMap<>();
marks.put("Alice", 85); // CREATE
marks.put("Alice", 90); // UPDATE
int score = marks.get("Alice"); // READ: 90
int other = marks.getOrDefault("Z", 0); // 0 if missing
boolean found = marks.containsKey("Bob"); // false
marks.remove("Alice"); // DELETEgetOrDefault() is especially important for frequency counting. get() may return null; avoid unboxing a missing Integer into int.
A HashMap does not support map.get(0) as an index lookup. Pick a traversal based on what you need:
| NEED | USE | FULL TRAVERSAL TIME |
|---|---|---|
| Only keys | keySet() | O(n + capacity) |
| Only values | values() | O(n + capacity) |
| Both key and value | entrySet() | O(n + capacity) |
for (String key : marks.keySet()) {
System.out.println(key);
}
for (int value : marks.values()) {
System.out.println(value);
}
for (Map.Entry<String, Integer> e : marks.entrySet()) {
System.out.println(e.getKey() + " = " + e.getValue());
}Use entrySet() when you need both the key and value, such as finding the key with the highest value. Iterating through all entries takes O(n) in the usual capacity-proportional case.
Only DSA-useful conversions: extract keys or values when a problem expects a List, or transform an array into a frequency map for fast lookup. The latter is a data transformation, not a Java type cast.
HashMap<Integer, Integer> freq = new HashMap<>();
freq.put(2, 3);
freq.put(5, 1);
ArrayList<Integer> keys = new ArrayList<>(freq.keySet());
ArrayList<Integer> values = new ArrayList<>(freq.values());int[] nums = {1, 2, 2, 3};
HashMap<Integer, Integer> freq = new HashMap<>();
for (int num : nums) {
freq.put(num, freq.getOrDefault(num, 0) + 1);
}
// Counts: 1→1, 2→2, 3→1Constructing a new list from keys or values takes O(n) time and O(n) extra space. HashMap iteration order is not guaranteed.
This comparison file redesigns only HashSet, String/StringBuilder/char and Input & Output. The earlier focused HashMap preview remains in place. All other sections retain their original content.
Understand uniqueness, initialize a set, learn the essential operations with time and extra-space costs, then iterate and convert only when needed.
Display order is illustrative: HashSet does not guarantee order.
A HashSet stores unique elements. Use it when you care whether something has been seen, not how often it occurs.
Import the collection (or use import java.util.*;).
import java.util.HashSet;Integer specifies the element type. Java collections use wrapper types, not primitives.
HashSet<Integer> seen = new HashSet<>();
HashSet<String> words = new HashSet<>();
HashSet<Character> letters = new HashSet<>();| PART | MEANING |
|---|---|
HashSet | Collection that stores unique elements |
Integer | Element type; use Integer, not int |
seen | Your variable name |
new HashSet<>() | Creates an empty set |
Arrays.asList() works here: the HashSet constructor accepts a collection and removes duplicates.
HashSet<Integer> nums =
new HashSet<>(Arrays.asList(10, 20, 20, 30));
// Contains 10, 20 and 30 (order unspecified).Set<Integer> nums = new HashSet<>(); is also valid (import java.util.Set). A set has no index, so nums.get(0) is invalid.
CRUD means create, read, update and delete. A set does not update an element by index: you typically remove the old value and add a replacement.
| METHOD | WHAT IT DOES | AVG TIME | EXTRA SPACE |
|---|---|---|---|
add(x) | Add if absent; returns false if duplicate | O(1) | O(1)* |
contains(x) | Check if element exists | O(1) | O(1) |
remove(x) | Delete if present; returns boolean | O(1) | O(1) |
size() | Count unique elements | O(1) | O(1) |
isEmpty() | Check whether set is empty | O(1) | O(1) |
clear() | Remove all elements | O(n + capacity) | O(1) |
addAll(c) | Add all elements from collection | O(m) avg. | O(m)* |
retainAll(c) | Keep only elements also in c | Varies | Varies |
These are typical average costs for simple keys such as Integer or String. Hash collisions and rehashing can cause slower individual operations. *Adding may allocate space; a set storing n unique elements needs O(n) total space. m is the input collection size. retainAll depends on the collection type and membership costs.
HashSet<Integer> seen = new HashSet<>();
seen.add(5); // true: new value
seen.add(5); // false: already present
boolean exists = seen.contains(5); // true
seen.remove(5); // true: removed
System.out.println(seen.size()); // 0if (!seen.add(num)) means “this value has already appeared.” It is useful for detecting duplicates in one pass.
HashSet has no numeric index and no guaranteed iteration order. The enhanced for loop is usually enough for DSA.
HashSet<Integer> seen = new HashSet<>(Arrays.asList(4, 7, 9));
for (int num : seen) {
System.out.println(num);
}Iterator<Integer> it = seen.iterator();
while (it.hasNext()) {
int num = it.next();
if (num == 7) it.remove(); // Safe removal while iterating
}Full traversal costs O(n + capacity) time and O(1) extra space with a for-each loop. Do not call seen.remove(num) during a for-each traversal; use the iterator’s remove() if needed.
Include conversions only when the target representation is useful: building a uniqueness set, or returning values as a list/array.
int[] nums = {1, 2, 2, 3};
HashSet<Integer> unique = new HashSet<>();
for (int x : nums) unique.add(x);
// 3 unique elements; O(n) average time, O(n) spaceHashSet<Integer> unique =
new HashSet<>(Arrays.asList(1, 2, 2, 3));
ArrayList<Integer> list = new ArrayList<>(unique);
Integer[] boxed = unique.toArray(new Integer[0]);
// List and array order are NOT guaranteed.Use an array/List → HashSet when duplicates or repeated membership checks matter. Use HashSet → List/array only if a problem’s output format requires it. Building or copying n values costs O(n) average time and O(n) extra space.
A stack works Last In, First Out (LIFO). Use ArrayDeque for stack operations in ordinary Java DSA code.
LIFO: after pushing 10, 20, 30, the next pop gives 30.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.ArrayDeque;
import java.util.Deque;If you push(10), then push(20), the top is 20. pop() returns 20 before 10.
Deque is the interface, ArrayDeque is the implementation. push() inserts at the front, which acts as the stack top.
Deque<Integer> stack = new ArrayDeque<>();
stack.push(10);
stack.push(20);
System.out.println(stack.peek()); // 20| SYNTAX | MEANING |
|---|---|
Deque<Integer> | The interface supporting stack-like operations |
new ArrayDeque<>() | Creates the concrete deque |
push(x) | Places x at the top |
pop() / peek() | Remove / read the top element |
Important: collection-constructor order is front-to-back, so 10 becomes the top. To make 30 top, push the items in sequence instead.
Deque<Integer> stack = new ArrayDeque<>(
Arrays.asList(10, 20, 30)
);
System.out.println(stack.peek()); // 10peek() is safe on an empty stack, but pop() throws. ArrayDeque does not allow null elements.
Deque<Integer> stack = new ArrayDeque<>();
System.out.println(stack.peek()); // null
// stack.pop(); // throws NoSuchElementExceptionpop() and peek() on an empty ArrayDeque throw NoSuchElementException; check isEmpty() first. Stack
These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
push(x) | Insert at top | O(1) amortized | O(1) amortized growth |
pop() | Remove and return top | O(1) | O(1) |
peek() | Read top, null if empty | O(1) | O(1) |
isEmpty() | Test if stack empty | O(1) | O(1) |
size() | Number of elements | O(1) | O(1) |
clear() | Remove all | O(n) | O(1) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
Deque<Integer> st = new ArrayDeque<>();
st.push(5); // top: 5
st.push(8); // top: 8
int top = st.peek(); // 8; stack unchanged
int out = st.pop(); // 8; top becomes 5The main difference: peek() inspects without removal; pop() removes.
String s = "(())";
Deque<Character> st = new ArrayDeque<>();
for (char ch : s.toCharArray()) {
if (ch == '(') st.push(ch);
else if (ch == ')') {
if (st.isEmpty()) { /* invalid closing bracket */ }
else st.pop();
}
}
boolean balanced = st.isEmpty();The stack matches each closing parenthesis with the latest opening parenthesis. The flag also detects an unmatched closing bracket.
Deque<Integer> preferred = new ArrayDeque<>();
Stack<Integer> legacy = new Stack<>();Both are supported, but ArrayDeque is generally preferred for LIFO operations. The older Stack extends Vector.
Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
Deque<Integer> st = new ArrayDeque<>();
st.push(10); st.push(20); st.push(30);
for (int x : st) System.out.println(x); // 30, 20, 10Iteration does not remove elements. For real stack processing, repeatedly pop().
Deque<Integer> st = new ArrayDeque<>();
st.push(10); st.push(20);
while (!st.isEmpty()) {
System.out.println(st.pop());
}Use this when you must process the most recent item first. Total O(n) time to remove n items.
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
Deque<Integer> st = new ArrayDeque<>();
st.push(10); st.push(20);
List<Integer> topFirst = new ArrayList<>(st); // [20, 10]
Deque<Integer> copied = new ArrayDeque<>(topFirst);The created list uses top-to-bottom iteration order. Converting back from this list preserves that front-to-back order. Each conversion takes O(n) time and space.
A queue works First In, First Out (FIFO), making it useful for level-order traversal and BFS.
FIFO: 10 enters first and is also removed first.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.ArrayDeque;
import java.util.Queue;After offer(10), offer(20) and offer(30), the front is 10. poll() returns 10, then 20.
Queue is the interface. ArrayDeque is a practical implementation for FIFO operations; unlike PriorityQueue, it follows insertion order.
Queue<Integer> q = new ArrayDeque<>();
q.offer(10);
q.offer(20);
System.out.println(q.peek()); // 10| SYNTAX | MEANING |
|---|---|
Queue<Integer> | The queue interface |
new ArrayDeque<>() | A common queue implementation |
offer(x) | Adds to the rear |
poll() / peek() | Remove / view the front |
A collection constructor preserves its iteration order as front-to-back queue order.
Queue<Integer> q = new ArrayDeque<>(
Arrays.asList(10, 20, 30)
);
System.out.println(q.poll()); // 10Use offer/poll/peek for straightforward queue algorithms. ArrayDeque does not accept null items.
Queue<Integer> q = new ArrayDeque<>();
System.out.println(q.poll()); // null
System.out.println(q.peek()); // null
// q.remove(); // throws if empty
// q.element(); // throws if emptypoll() and peek() return null for an empty queue; remove() and element() throw. ArrayDeque rejects null elements, so an empty result is unambiguous.
These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
offer(x) | Add to tail | O(1) amortized | O(1) amortized growth |
poll() | Remove front; null if empty | O(1) | O(1) |
peek() | Read front; null if empty | O(1) | O(1) |
add(x) | Add; throws if refused | O(1) amortized | O(1) amortized growth |
remove() | Remove front; throws if empty | O(1) | O(1) |
element() | Read front; throws if empty | O(1) | O(1) |
isEmpty(), size() | State and element count | O(1) | O(1) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
Queue<Integer> q = new ArrayDeque<>();
q.offer(5);
q.offer(9);
int first = q.peek(); // 5, unchanged
int taken = q.poll(); // 5, queue now contains 9FIFO processes the oldest element first. peek() is non-destructive; poll() removes.
Queue<Integer> q = new ArrayDeque<>();
q.offer(0); // starting node
while (!q.isEmpty()) {
int node = q.poll();
System.out.println(node);
// Add unvisited neighbors here with q.offer(neighbor)
}The queue handles processing order. Real graph BFS also needs an adjacency structure and visited tracking to avoid repeated nodes.
Queue<Integer> q = new ArrayDeque<>();
q.offer(10); q.offer(20);
int levelSize = q.size();
for (int i = 0; i < levelSize; i++) {
int node = q.poll();
System.out.println(node);
}Capture size() before processing a level. Newly enqueued items belong to the next level.
Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
Queue<Integer> q = new ArrayDeque<>(Arrays.asList(10, 20, 30));
for (int x : q) System.out.println(x);Enhanced for traverses head-to-tail without removing items.
Queue<Integer> q = new ArrayDeque<>(Arrays.asList(1, 2, 3));
while (!q.isEmpty()) {
int x = q.poll();
System.out.println(x);
}Use poll() inside a loop when you actually want to consume the queue.
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
List<Integer> list = Arrays.asList(10, 20, 30);
Queue<Integer> q = new ArrayDeque<>(list);
List<Integer> result = new ArrayList<>(q);Useful if an API expects a list rather than a queue. Both conversions take O(n) time and O(n) output space; order is preserved for ArrayDeque.
Deque means double-ended queue. It allows insertion, reading and removal at both ends.
Both ends are accessible. The front and back have separate operations.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.ArrayDeque;
import java.util.Deque;In a deque, first means front/left and last means back/right. Unlike ArrayList, you work with ends rather than numeric indices.
ArrayDeque dynamically grows and supports fast operations at either end. It does not accept null.
Deque<Integer> dq = new ArrayDeque<>();
dq.offerFirst(10); // [10]
dq.offerLast(20); // [10, 20]
dq.offerFirst(5); // [5, 10, 20]| SYNTAX | MEANING |
|---|---|
Deque<Integer> | Interface for both-ended operations |
new ArrayDeque<>() | Resizable deque implementation |
offerFirst / pollFirst | Insert / remove at the front |
offerLast / pollLast | Insert / remove at the back |
Input collection order becomes the deque’s front-to-back order.
Deque<Integer> dq = new ArrayDeque<>(
Arrays.asList(10, 20, 30)
);
System.out.println(dq.peekFirst()); // 10
System.out.println(dq.peekLast()); // 30The same implementation can play different roles. Stick to one naming style within an algorithm to avoid mixing end semantics.
Deque<Integer> d = new ArrayDeque<>();
d.push(1); // stack behavior
d.offerLast(2); // queue-tail behavior
int front = d.peekFirst();Do not assume get(0) or index-based operations exist. peekFirst() and peekLast() return null when the deque is empty.
These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
offerFirst(x) | Add at front | O(1) amortized | O(1) amortized growth |
offerLast(x) | Add at back | O(1) amortized | O(1) amortized growth |
pollFirst() | Remove front, null if empty | O(1) | O(1) |
pollLast() | Remove back, null if empty | O(1) | O(1) |
peekFirst() | Read front, null if empty | O(1) | O(1) |
peekLast() | Read back, null if empty | O(1) | O(1) |
push(x), pop() | Stack-style front operations | O(1) amortized / O(1) | O(1) amortized / O(1) |
size(), isEmpty() | Check count / emptiness | O(1) | O(1) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
Deque<Integer> dq = new ArrayDeque<>();
dq.offerLast(10); // [10]
dq.offerLast(20); // [10, 20]
dq.offerFirst(5); // [5, 10, 20]
int left = dq.pollFirst(); // 5
int right = dq.pollLast(); // 20pollFirst and pollLast remove the corresponding end. The peek variants do not remove.
int[] a = {4, 2, 5, 1};
Deque<Integer> dq = new ArrayDeque<>();
for (int i = 0; i < a.length; i++) {
while (!dq.isEmpty() && a[dq.peekLast()] <= a[i]) {
dq.pollLast();
}
dq.offerLast(i);
}This maintains decreasing values from front to back, so the front represents the largest retained element. A sliding-window maximum algorithm also removes expired indices from the front.
indices rather than values so you can discard indices that leave a sliding window.Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
Deque<Integer> dq = new ArrayDeque<>(Arrays.asList(1, 2, 3));
for (int x : dq) System.out.println(x); // 1, 2, 3
Iterator<Integer> rev = dq.descendingIterator();
while (rev.hasNext()) System.out.println(rev.next()); // 3, 2, 1Iteration does not remove elements. For algorithms that consume entries, use pollFirst() or pollLast().
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
Deque<Integer> dq = new ArrayDeque<>(Arrays.asList(2, 4, 6));
List<Integer> list = new ArrayList<>(dq); // [2, 4, 6]This preserves the front-to-back order and costs O(n) time and space. No conversion is needed merely to perform deque operations.
PriorityQueue stores elements in heap order. Only the next element to be removed is guaranteed to have top priority.
The heap does not keep all values sorted. Only the next poll() is guaranteed to be the minimum.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.PriorityQueue;
import java.util.Comparator;
import java.util.Arrays;A min-heap returns 1 before 5. A max-heap returns 5 before 1. Only the head is guaranteed to be highest priority; iteration is not sorted.
The default natural ordering puts the smallest number at the head.
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
minHeap.offer(8);
minHeap.offer(3);
minHeap.offer(5);
System.out.println(minHeap.peek()); // 3| SYNTAX | MEANING |
|---|---|
PriorityQueue<Integer> | The priority-queue type |
new PriorityQueue<>() | Default min-heap: smallest value first |
Comparator.reverseOrder() | Reverses ordering to produce a max-heap |
offer / peek / poll | Insert / read head / remove head |
Use a comparator to reverse priority. Avoid subtraction-based comparators such as (a,b) -> b-a, which can overflow.
PriorityQueue<Integer> maxHeap =
new PriorityQueue<>(Comparator.reverseOrder());
maxHeap.offer(8);
maxHeap.offer(3);
maxHeap.offer(5);
System.out.println(maxHeap.peek()); // 8Constructing from a collection heapifies it in O(n). The queue is not stored as a sorted list.
PriorityQueue<Integer> pq = new PriorityQueue<>(
Arrays.asList(7, 2, 9, 1)
);
System.out.println(pq.peek()); // 1A PriorityQueue is NOT a sorted list. for-each iteration and toArray() do not return sorted elements. Use a copy and poll repeatedly when priority order is required.
Comparator.reverseOrder() makes larger integers come out first. For pairs, compare the desired field using Integer.compare(a[0], b[0]). Equal priorities have no guaranteed stable order.These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
offer(x) | Insert item | O(log n) | O(1) amortized storage |
poll() | Remove min/max head | O(log n) | O(1) auxiliary |
peek() | Read head | O(1) | O(1) |
remove(x) | Find and remove given value | O(n) | O(1) auxiliary |
contains(x) | Check for given value | O(n) | O(1) |
size(), isEmpty() | Count / empty status | O(1) | O(1) |
new PriorityQueue<>(collection) | Heapify existing items | O(n) | O(n) output storage |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
PriorityQueue<Integer> pq = new PriorityQueue<>();
pq.offer(10);
pq.offer(4);
pq.offer(7);
int smallest = pq.peek(); // 4
int removed = pq.poll(); // 4; next head is 7Unlike HashSet, PriorityQueue allows duplicate values. peek() does not remove, while poll() removes.
PriorityQueue<Integer> pq =
new PriorityQueue<>(Comparator.reverseOrder());
pq.offer(10); pq.offer(4); pq.offer(7);
System.out.println(pq.poll()); // 10Use a max-heap when you repeatedly need the largest remaining value.
PriorityQueue<int[]> pq = new PriorityQueue<>(
(a, b) -> Integer.compare(a[1], b[1])
);
pq.offer(new int[]{5, 20});
pq.offer(new int[]{9, 10});
int[] best = pq.poll(); // {9, 10}Useful when each item contains an identifier and a priority (e.g. node and distance). Comparator compares the second field.
new PriorityQueue<>((a, b) -> Integer.compare(a[0], b[0])) for int[] entries sorted by the first element. Avoid subtraction-based comparators because they can overflow.Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
PriorityQueue<Integer> pq = new PriorityQueue<>(
Arrays.asList(8, 2, 5)
);
while (!pq.isEmpty()) {
System.out.println(pq.poll()); // 2, then 5, then 8
}Repeated polling produces priority order and consumes the heap. This takes O(n log n) overall.
PriorityQueue<Integer> pq = new PriorityQueue<>(Arrays.asList(4, 1, 3));
PriorityQueue<Integer> copy = new PriorityQueue<>(pq);
while (!copy.isEmpty()) System.out.println(copy.poll());Copy first if you need to keep the original. Iterating the original directly is not sorted.
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
List<Integer> nums = Arrays.asList(7, 1, 5);
PriorityQueue<Integer> pq = new PriorityQueue<>(nums);
List<Integer> sorted = new ArrayList<>();
while (!pq.isEmpty()) sorted.add(pq.poll());
// sorted is [1, 5, 7]Construction from a collection is O(n); repeatedly polling takes O(n log n). new ArrayList<>(pq) alone does NOT sort the values.
Java LinkedList is a doubly linked collection. Most coding-platform linked-list tasks instead supply a custom ListNode class.
A node points to the next node; Java LinkedList is doubly linked under the hood.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.LinkedList;
import java.util.Arrays;A singly linked chain looks like 10 → 20 → 30 → null. Each node contains a value and a reference to the next node. Unlike arrays, you cannot jump directly to index i.
java.util.LinkedList is a doubly linked list with built-in methods. It supports operations at either end.
LinkedList<Integer> list = new LinkedList<>();
list.addLast(10);
list.addLast(20);
list.addFirst(5); // [5, 10, 20]| SYNTAX | MEANING |
|---|---|
LinkedList<Integer> | Java collection of Integer values |
new LinkedList<>() | Creates an empty doubly linked list |
addFirst / addLast | Constant-time insertion at ends |
ListNode next | Link to the next node in a custom chain |
The constructor preserves the iteration order of the supplied collection.
LinkedList<Integer> list = new LinkedList<>(
Arrays.asList(10, 20, 30)
);Here head references the first node. head.next is a node reference, not an array index. Many linked-list DSA problems provide this class for you.
class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
ListNode head = new ListNode(10);
head.next = new ListNode(20);
head.next.next = new ListNode(30);LinkedList.get(i) is O(n), not O(1). In pointer problems, use the provided ListNode rather than assuming java.util.LinkedList is accepted.
These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
addFirst(x), addLast(x) | Insert at either end | O(1) | O(1) node |
getFirst(), getLast() | Read ends (throws if empty) | O(1) | O(1) |
removeFirst(), removeLast() | Delete at either end | O(1) | O(1) |
get(i), set(i,x) | Access/update indexed node | O(n) | O(1) |
add(i,x) | Insert at index | O(n) | O(1) node |
remove(i) | Remove node at index | O(n) | O(1) |
contains(x) | Find matching value | O(n) | O(1) |
size(), isEmpty() | Size and empty check | O(1) | O(1) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
LinkedList<Integer> list = new LinkedList<>();
list.addFirst(20);
list.addFirst(10);
list.addLast(30);
int first = list.getFirst(); // 10
list.set(1, 25); // [10, 25, 30]
list.removeLast(); // [10, 25]End operations are O(1), but get(i) and set(i,...) require traversal and are O(n).
class ListNode {
int val; ListNode next;
ListNode(int v) { val = v; }
}
ListNode head = new ListNode(20);
ListNode node = new ListNode(10);
node.next = head;
head = node; // 10 → 20For node problems, insertion changes links. A head insertion takes O(1) if you already have the head reference.
class ListNode {
int val; ListNode next;
ListNode(int v) { val = v; }
}
ListNode head = new ListNode(1);
head.next = new ListNode(2);
ListNode prev = null, curr = head;
while (curr != null) {
ListNode nextNode = curr.next;
curr.next = prev;
prev = curr;
curr = nextNode;
}
head = prev;This reverses links in-place using three references. It takes O(n) time and O(1) extra space.
node.next rewires the structure. Distinguish that from calling methods on the Java collection.Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
LinkedList<Integer> list = new LinkedList<>(
Arrays.asList(1, 2, 3)
);
for (int value : list) System.out.println(value);Library traversal takes O(n). Avoid calling get(i) repeatedly in a loop because that may take O(n²) overall.
class ListNode {
int val; ListNode next;
ListNode(int v) { val = v; }
}
ListNode head = new ListNode(1);
head.next = new ListNode(2);
for (ListNode cur = head; cur != null; cur = cur.next) {
System.out.println(cur.val);
}Walk from node to node using next. A null reference marks the end.
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
// slow is the middle (second middle when even length)This snippet assumes the head variable and ListNode class have already been defined. It is common in middle-node and cycle problems.
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
LinkedList<Integer> linked = new LinkedList<>(
Arrays.asList(3, 1, 2)
);
List<Integer> arrayList = new ArrayList<>(linked);
LinkedList<Integer> copy = new LinkedList<>(arrayList);Both conversions take O(n) time and O(n) output space. Changing collection types does not create or solve a custom node-chain problem.
List<Integer> values = new ArrayList<>();
for (ListNode cur = head; cur != null; cur = cur.next) {
values.add(cur.val);
}Assumes head is already a custom ListNode chain. Useful if a problem explicitly requests list/array output, but not needed for normal pointer operations.
TreeSet stores distinct sorted elements; TreeMap stores key-value pairs sorted by key. Ordered lookups are O(log n).
TreeSet iterates in sorted order; TreeMap sorts keys, not values.
Start with the data model, then learn the Java syntax. Each example is compatible with Java 8 compatible.
import java.util.TreeSet;
import java.util.TreeMap;
import java.util.Comparator;Choose TreeSet<Integer> for sorted unique numbers. Choose TreeMap<Integer,String> when each sorted key must map to a value.
Unlike HashSet, TreeSet maintains ascending natural order by default.
TreeSet<Integer> set = new TreeSet<>();
set.add(30);
set.add(10);
set.add(20);
set.add(20); // duplicate ignored
System.out.println(set); // [10, 20, 30]| SYNTAX | MEANING |
|---|---|
TreeSet<Integer> | Sorted unique elements |
TreeMap<Integer, String> | Sorted keys with associated values |
Comparator.reverseOrder() | Optional descending ordering |
floor / ceiling | Nearest item ≤ target / ≥ target |
Keys are sorted, while values can repeat. Inserting the same key again replaces its value.
TreeMap<Integer, String> map = new TreeMap<>();
map.put(30, "C");
map.put(10, "A");
map.put(20, "B");
System.out.println(map); // {10=A, 20=B, 30=C}Comparators specify key or element order. Values in TreeMap are not sorted independently.
TreeSet<Integer> descSet =
new TreeSet<>(Comparator.reverseOrder());
TreeMap<Integer, String> descMap =
new TreeMap<>(Comparator.reverseOrder());TreeSet and TreeMap are ordered, unlike HashSet and HashMap. first()/last() throw on empty sets/maps; floor()/ceiling() return null if no neighbor exists.
These are the operations worth knowing before using this structure in DSA. The time column describes the listed operation; space is additional space required by that operation, not the entire collection.
| Method / operation | Purpose | Time | Extra space |
|---|---|---|---|
TreeSet.add(x) | Insert distinct item | O(log n) | O(1) node |
TreeSet.contains(x) | Check membership | O(log n) | O(1) |
TreeSet.remove(x) | Remove item | O(log n) | O(1) |
TreeSet.first(), last() | Smallest / largest | O(log n) | O(1) |
TreeSet.floor(x), ceiling(x) | Nearest ≤ / ≥ | O(log n) | O(1) |
TreeSet.lower(x), higher(x) | Strictly < / > | O(log n) | O(1) |
TreeMap.put(k,v) | Insert or update key | O(log n) | O(1) node if new |
TreeMap.get(k), remove(k) | Read / delete key | O(log n) | O(1) |
TreeMap.firstKey(), lastKey() | Smallest / largest key | O(log n) | O(1) |
TreeMap.floorKey(k), ceilingKey(k) | Nearest key ≤ / ≥ | O(log n) | O(1) |
size(), isEmpty() | Count / empty state | O(1) | O(1) |
Complexity note: n is the number of elements. “Amortized” accounts for occasional resizing. Allocated collection nodes or output arrays are counted in the indicated space; operations can have different worst-case costs from their typical performance.
TreeSet<Integer> set = new TreeSet<>(
Arrays.asList(10, 20, 30, 40)
);
System.out.println(set.floor(25)); // 20
System.out.println(set.ceiling(25)); // 30
System.out.println(set.lower(20)); // 10
System.out.println(set.higher(20)); // 30floor and ceiling include equality. lower and higher are strictly smaller/larger. Missing neighbor returns null.
TreeMap<Integer, String> map = new TreeMap<>();
map.put(10, "A"); map.put(30, "C");
map.put(20, "B");
Integer key = map.floorKey(25); // 20
String value = map.get(key); // "B"Use TreeMap when sorted keys and associated values are both necessary.
TreeSet<Integer> set = new TreeSet<>();
System.out.println(set.floor(5)); // null
// set.first(); // throws NoSuchElementExceptionCheck isEmpty() before calling first()/last() on an empty collection. floor()/ceiling() can return null.
Choose traversal based on whether you need positions, element values, removal order or safe modification; the examples explain each choice.
TreeSet<Integer> set = new TreeSet<>(
Arrays.asList(5, 1, 3)
);
for (int x : set) System.out.println(x); // 1, 3, 5
for (int x : set.descendingSet()) System.out.println(x); // 5, 3, 1Iteration follows the sorted tree order, rather than insertion order.
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "C"); map.put(1, "A");
for (Map.Entry<Integer, String> e : map.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}entrySet() traverses keys in ascending order. Use descendingMap().entrySet() for reverse order.
Only conversions or representations that commonly solve a real problem are included; do not convert just because it is possible.
List<Integer> nums = Arrays.asList(5, 1, 5, 2);
TreeSet<Integer> sortedUnique = new TreeSet<>(nums);
List<Integer> result = new ArrayList<>(sortedUnique);
// result: [1, 2, 5]This is useful when you need both deduplication and sorted results. Construction takes O(n log n); the list conversion takes O(n).
Map<Integer, String> input = new HashMap<>();
input.put(3, "C"); input.put(1, "A");
TreeMap<Integer, String> ordered = new TreeMap<>(input);Converting a hash map to a tree map sorts the keys, not the values. It costs O(n log n).
Select an operation to see the example and complexity.
Collections works with collections; Arrays with arrays.
Collections.sort(list); // Sorts a List into natural ascending order
Collections.reverse(list); // Reverses the order of list elements
int best = Collections.max(list); // Finds the largest list element in linear time
list.sort(Comparator.reverseOrder()); // Sorts in place using a comparator to define orderingString and numeric conversions for coding rounds.
int n = Integer.parseInt("123"); // Parses a numeric string into an int
long l = Long.parseLong("12345678900"); // Parses a numeric string into a long
String text = String.valueOf(n); // Converts a value into its String representation
char[] chars = text.toCharArray(); // Converts String into editable character arraySpot these before submitting.
// arr.length vs list.size() vs s.length()
// Arrays.equals(a,b) for primitive array contents
// String.equals(t) instead of == for text
// List<Integer>.remove(1) removes index 1
// Avoid modifying a collection inside enhanced for
// Comparator: Integer.compare(a,b), not a-b
// StringBuilder != String: call toString() if needed