Java Collections Framework Guide
Java Collections Framework Guide
Below is a complete, exam-ready and interview-ready guide to the Java Collections Framework for Integer and String,
with all major interfaces, classes, methods, and detailed examples.
List
Set
Queue / Deque
Map
Utility classes: Collections, Arrays
🚀 1. LIST
List = Ordered collection, allows duplicates.
Common Methods:
add(E e)
get(int index)
contains(Object o)
isEmpty()
import [Link].*;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/40
public class ArrayListExample {
public static void main(String[] args) {
// Integer List
List<Integer> nums = new ArrayList<>();
[Link](10);
[Link](20);
[Link](30);
[Link](1, 15); // insert at index
// String List
List<String> names = new ArrayList<>();
[Link]("Ashutosh");
[Link]("Rahul");
[Link]("Riya");
[Link]([Link]("Rahul")); // true
⭐ 1.2 LinkedList
Doubly linked list
Faster insertion/deletion in middle
Can be used as Queue
✔ Example:
java
🚀 2. SET
Set = Unordered, no duplicates.
Common Methods:
add(E e)
remove(Object o)
contains(Object o)
size()
isEmpty()
Iteration
⭐ 2.1 HashSet
No order
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/40
Fastest set implementation
java
⭐ 2.2 LinkedHashSet
Maintains insertion order.
java
⭐ 2.3 TreeSet
Sorted set (natural order)
Internally uses Red-Black Tree
java
🚀 3. MAP
Map = Key–Value pairs
Common Methods
get(Object key)
containsKey(Object key)
containsValue(Object value)
remove(Object key)
keySet()
values()
entrySet()
[Link]([Link](2)); // Rahul
⭐ 3.2 LinkedHashMap
Maintains insertion order.
java
⭐ 3.3 TreeMap
Sorted map by keys.
java
🚀 4. QUEUE / DEQUE
⭐ 4.1 PriorityQueue
Min-heap
Elements sorted automatically
java
[Link]([Link]()); // 10
[Link]([Link]()); // 20
⭐ 4.2 ArrayDeque
Faster than Stack & LinkedList for Deque operations
Double-ended queue
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/40
java
[Link]([Link]()); // A
java
[Link]([Link]()); // 30
[Link]([Link]()); // 30
[Link](list)
[Link](list)
[Link](list)
[Link](list)
Example:
java
📌 Summary Table
Interface/Class Ordered Allows Duplicate Sorted Example
Nice — you want the 15 most common algorithms you’d expect from C++’s <algorithm> but shown as they are used with
Java Collections (for Integer and String).
Below I’ll list each algorithm, its Java equivalent, time complexity, a short explanation, and a complete, runnable Java
example (small snippet) — so you can copy-paste and run. I’ll favour the standard [Link] APIs and Stream where
appropriate (these are the idiomatic Java equivalents).
1) sort (std::sort)
Java equivalent: [Link](list) or [Link](Comparator)
Complexity: O(n log n) (TimSort, stable)
java
Notes: [Link] delegates to [Link] which uses TimSort (stable). For custom ordering pass a Comparator.
2) stable_sort (std::stable_sort)
Java equivalent: same as sort — Java's [Link] / [Link] is stable (TimSort).
Complexity: O(n log n)
java
3) reverse (std::reverse)
Java equivalent: [Link](list)
Complexity: O(n)
java
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/40
Java equivalent: [Link](list) (optionally pass Random)
Complexity: O(n)
java
5) binary_search (std::binary_search)
Java equivalent: [Link](list, key) (list must be sorted)
Complexity: O(log n)
java
If not found: returns -(insertionPoint) - 1. You can compute insertion point: insertionPoint = -res - 1.
java
Note: For large lists you can write custom binary search to find exact lower/upper bound in O(log n) without linear scan.
7) find (std::find)
Java equivalent: [Link](element) or [Link](element) or stream().filter(...).findFirst()
Complexity: O(n)
java
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/40
// Using streams for predicate:
Optional<Integer> found = [Link]().filter(x -> x % 4 == 0).findFirst();
8) count (std::count)
Java equivalent: [Link](list, element) or stream().filter(...).count()
Complexity: O(n)
java
java
// general reduce:
int prod = [Link]().reduce(1, (a,b) -> a*b);
java
java
Note: [Link] requires destination to be at least as large as source (it overwrites positions).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/40
12) remove_if (std::remove_if + erase idiom)
Java equivalent: [Link](Predicate) (in-place), or stream().filter(...).collect(...) to create new list
Complexity: O(n)
java
java
java
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/40
java
Note: If you want a stable partition keep two lists and combine: List<T> yes = ...; List<T> no = ...; [Link](no).
rotate [Link]
partition [Link]() or manual reorder
for_each [Link](Consumer) or stream().forEach()
java
import [Link].*;
import [Link].*;
// sort
[Link](a);
[Link]("sorted: " + a);
// reverse
[Link](a);
[Link]("reversed: " + a);
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/40
// shuffle
[Link](a, new Random(1));
[Link]("shuffled: " + a);
// count
[Link]("frequency of 2: " + [Link](a, 2));
// accumulate
int sum = [Link]().mapToInt(Integer::intValue).sum();
[Link]("sum: " + sum);
// transform
List<Integer> doubled = [Link]().map(x -> x*2).collect([Link]());
[Link]("doubled: " + doubled);
// copy
List<Integer> dest = new ArrayList<>([Link]([Link](), 0));
[Link](dest, a);
[Link]("copied dest: " + dest);
// unique (distinct)
List<Integer> distinct = [Link]().distinct().collect([Link]());
[Link]("distinct: " + distinct);
// rotate
List<Integer> rot = new ArrayList<>([Link](1,2,3,4,5));
[Link](rot, 2);
[Link]("rotated by 2: " + rot);
// partition
List<Integer> list = new ArrayList<>([Link](1,2,3,4,5,6));
Map<Boolean, List<Integer>> parts = [Link]().collect([Link](x -> x%2==0));
[Link]("evens: " + [Link](true) + " odds: " + [Link](false));
}
}
Provide exact O(log n) implementations for lower_bound & upper_bound (custom binary search) in Java, or
Convert these to C++-style function signatures for a one-to-one mapping, or
Produce a printable PDF or cheat-sheet containing all snippets.
Prompts the user for a list of Integers and a list of Strings (space-separated).
Then runs the 15 algorithms (the Java equivalents from your earlier request) on both lists and prints clear outputs
for each step.
Includes generic lowerBound/upperBound implementations (O(log n)) and examples for both types.
Copy-paste the code into [Link] and run (javac [Link] && java
CollectionAlgorithmsDemo).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/40
java
import [Link].*;
import [Link].*;
import [Link].*;
/**
* CollectionAlgorithmsDemo
*
* Reads integer and string lists from user and demonstrates 15 common algorithms:
* - sort, stable sort, reverse, shuffle, binary_search, lower_bound, upper_bound,
* find, count, accumulate, transform, copy, remove_if, unique (distinct), rotate,
* partition
*
* Note: Inputs are space-separated. Press Enter on empty line to use defaults.
*/
public class CollectionAlgorithmsDemo {
[Link]("\nEnter strings (space-separated). Press Enter for default: zebra apple bob alpha
beta");
String strLine = [Link]().trim();
List<String> strs = [Link]()
? new ArrayList<>([Link]("zebra", "apple", "bob", "alpha", "beta"))
: [Link]([Link]("\\s+")).collect([Link]());
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/40
if (![Link]()) {
int search = [Link](0); // take smallest element
int lb = lowerBound(intsSort, search, [Link]());
int ub = upperBound(intsSort, search, [Link]());
[Link]("Ints: lowerBound(" + search + ") = " + lb + ", upperBound(" + search + ") = " +
ub);
}
if (![Link]()) {
String s = [Link](0);
int lb = lowerBound(strsSort, s, [Link]());
int ub = upperBound(strsSort, s, [Link]());
[Link]("Strs: lowerBound(\"" + s + "\") = " + lb + ", upperBound(\"" + s + "\") = " + ub);
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/40
[Link]("\n--- Done ---");
[Link]();
}
/**
* Generic lowerBound: first index i such that [Link](i) >= key according to comparator.
* If all elements < key, returns [Link]().
* Requires list sorted according to comparator.
*/
public static <T> int lowerBound(List<T> a, T key, Comparator<? super T> cmp) {
int lo = 0, hi = [Link]();
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if ([Link]([Link](mid), key) < 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
/**
* Generic upperBound: first index i such that [Link](i) > key according to comparator.
* If no element > key, returns [Link]().
* Requires list sorted according to comparator.
*/
public static <T> int upperBound(List<T> a, T key, Comparator<? super T> cmp) {
int lo = 0, hi = [Link]();
while (lo < hi) {
int mid = (lo + hi) >>> 1;
if ([Link]([Link](mid), key) <= 0) lo = mid + 1;
else hi = mid;
}
return lo;
}
/**
* Remove only consecutive duplicates (like std::unique).
*/
public static <T> List<T> removeConsecutiveDuplicates(List<T> a) {
if ([Link]()) return a;
List<T> out = new ArrayList<>();
T prev = null;
boolean first = true;
for (T x : a) {
if (first || ) {
[Link](x);
prev = x;
first = false;
}
}
return out;
}
}
lowerBound and upperBound are O(log n) and work on sorted lists. I implemented them generically so they work for
Integer, String, or any T with a Comparator.
[Link](dest, src) requires [Link]() >= [Link](); I used [Link] to pre-size a mutable list.
removeConsecutiveDuplicates emulates std::unique (it removes only consecutive duplicates).
partitionshown both as a non-destructive stream-based partition (stable) — for an in-place unstable partition you
can implement a two-pointer swap algorithm (I can add that if you want).
The program uses safe defaults if you press Enter at the input prompts.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/40
Here is the simplest and cleanest Java code to:
import [Link].*;
// Create ArrayList
ArrayList<Integer> list = new ArrayList<>();
// Print result
[Link]("After multiplying each element by 4:");
[Link](list);
[Link]();
}
}
📌 Example Input
yaml
📌 Output
pgsql
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 15/40
10 common basic DSA questions in Java (statement → approach →
complexity → runnable solution)
Below are 10 frequently asked basic DSA problems with a short explanation, time/space complexity, and a concise Java
implementation you can copy/paste and run. Each solution is self-contained (a single class with main demonstrating the
method). If you want them combined into one file or a printable PDF, tell me.
java
// [Link]
import [Link];
public class ReverseArray {
public static void reverse(int[] a) {
int i = 0, j = [Link] - 1;
while (i < j) {
int t = a[i]; a[i] = a[j]; a[j] = t;
i++; j--;
}
}
public static void main(String[] args) {
int[] a = {1,2,3,4,5};
[Link]("Before: " + [Link](a));
reverse(a);
[Link]("After : " + [Link](a));
}
}
java
// [Link]
import [Link].*;
public class TwoSum {
public static int[] twoSum(int[] a, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < [Link]; i++) {
int need = target - a[i];
if ([Link](need)) return new int[]{[Link](need), i};
[Link](a[i], i);
}
return new int[]{-1,-1};
}
public static void main(String[] args) {
int[] a = {2,7,11,15};
int t = 9;
int[] res = twoSum(a, t);
[Link]([Link](res)); // [0,1]
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/40
Problem: Find index of key in sorted array, or -1.
Approach: Classic iterative binary search.
Time: O(log n), Space: O(1)
java
// [Link]
import [Link].*;
public class BinarySearch {
public static int binarySearch(int[] a, int key) {
int lo = 0, hi = [Link] - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (a[mid] == key) return mid;
else if (a[mid] < key) lo = mid + 1;
else hi = mid - 1;
}
return -1;
}
public static void main(String[] args) {
int[] a = {1,3,5,7,9};
[Link](binarySearch(a, 7)); // 3
[Link](binarySearch(a, 2)); // -1
}
}
java
// [Link]
import [Link].*;
public class RemoveDuplicates {
public static int removeDuplicates(int[] a) {
if ([Link] == 0) return 0;
int write = 1;
for (int read = 1; read < [Link]; read++) {
if (a[read] != a[read - 1]) {
a[write++] = a[read];
}
}
return write;
}
public static void main(String[] args) {
int[] a = {1,1,2,2,3,3,3,4};
int len = removeDuplicates(a);
[Link]("New len: " + len);
[Link]("Array now: " + [Link]([Link](a, len)));
}
}
java
// [Link]
import [Link].*;
public class MergeSortedArrays {
public static int[] merge(int[] a, int[] b) {
int n = [Link], m = [Link];
int[] res = new int[n + m];
int i=0,j=0,k=0;
while(i<n && j<m) {
if(a[i] <= b[j]) res[k++] = a[i++];
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/40
else res[k++] = b[j++];
}
while(i<n) res[k++] = a[i++];
while(j<m) res[k++] = b[j++];
return res;
}
public static void main(String[] args) {
int[] a = {1,3,5};
int[] b = {2,4,6,8};
[Link]([Link](merge(a,b))); // [1,2,3,4,5,6,8]
}
}
java
// [Link]
public class Kadane {
public static int maxSubArray(int[] a) {
int best = Integer.MIN_VALUE, cur = 0;
for (int x : a) {
cur = [Link](x, cur + x);
best = [Link](best, cur);
}
return best;
}
public static void main(String[] args) {
int[] a = {-2,1,-3,4,-1,2,1,-5,4};
[Link](maxSubArray(a)); // 6 (subarray [4,-1,2,1])
}
}
java
// [Link]
public class ReverseLinkedList {
static class Node {
int val; Node next;
Node(int v){ val=v; }
}
public static Node reverse(Node head) {
Node prev = null, cur = head;
while (cur != null) {
Node nxt = [Link];
[Link] = prev;
prev = cur;
cur = nxt;
}
return prev;
}
// Helper to print and demo
public static void main(String[] args) {
Node head = new Node(1);
[Link] = new Node(2); [Link] = new Node(3);
Node r = reverse(head);
while (r != null) {
[Link]([Link] + ([Link] != null ? "->" : "\n"));
r = [Link];
}
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/40
8) Detect cycle in linked list (Floyd’s Tortoise & Hare)
Problem: Return true if singly linked list has a cycle.
Approach: Two pointers — slow moves 1, fast moves 2; if meet → cycle.
Time: O(n), Space: O(1)
java
// [Link]
public class DetectCycle {
static class Node { int val; Node next; Node(int v){val=v;} }
public static boolean hasCycle(Node head) {
if (head == null) return false;
Node slow = head, fast = [Link];
while (fast != null && [Link] != null) {
if (slow == fast) return true;
slow = [Link];
fast = [Link];
}
return false;
}
public static void main(String[] args) {
Node a = new Node(1), b = new Node(2), c = new Node(3);
[Link] = b; [Link] = c; [Link] = b; // cycle
[Link](hasCycle(a)); // true
Node x = new Node(10);
[Link](hasCycle(x)); // false
}
}
java
// [Link]
import [Link].*;
public class BFSTree {
static class Node { int val; Node left, right; Node(int v){val=v;} }
public static List<List<Integer>> bfsLevels(Node root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<Node> q = new LinkedList<>();
[Link](root);
while (![Link]()) {
int sz = [Link]();
List<Integer> level = new ArrayList<>();
for (int i=0;i<sz;i++) {
Node n = [Link]();
[Link]([Link]);
if ([Link] != null) [Link]([Link]);
if ([Link] != null) [Link]([Link]);
}
[Link](level);
}
return res;
}
public static void main(String[] args) {
Node root = new Node(1);
[Link] = new Node(2); [Link] = new Node(3);
[Link] = new Node(4); [Link] = new Node(5);
[Link](bfsLevels(root)); // [[1],[2,3],[4,5]]
}
}
java
// [Link]
public class CountSetBits {
public static int countSetBits(int n) {
int cnt = 0;
while (n != 0) {
n &= (n - 1);
cnt++;
}
return cnt;
}
public static void main(String[] args) {
[Link](countSetBits(0b1011)); // 3
[Link](countSetBits(0)); // 0
[Link](countSetBits(-1)); // 32 for 32-bit signed int
}
}
If you'd like:
All problems combined into a single menu-driven Java program that asks which problem to run and takes input — I
can produce that.
Extended explanations, unit tests, or step-by-step dry runs for specific examples.
Which would you like next?
Nice — below are 10 of the most common array problems you’ll see on HackerRank (and similar sites), each with:
You can copy-paste each class into HackerRank (or combine into one file and run the desired main by renaming class to Main
if needed). I kept I/O simple and robust.
css
n
a0 a1 a2 ... a(n-1)
java
// [Link]
import [Link].*;
public class ReverseArray {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = [Link]();
int i=0, j=n-1;
while(i<j){
int t = a[i]; a[i]=a[j]; a[j]=t;
i++; j--;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/40
}
StringJoiner sj = new StringJoiner(" ");
for(int x: a) [Link]([Link](x));
[Link]([Link]());
[Link]();
}
}
css
n target
a0 a1 ... a(n-1)
java
// [Link]
import [Link].*;
public class TwoSumIndices {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
int n = [Link]();
int target = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
Map<Integer,Integer> map = new HashMap<>();
int i1=-1, i2=-1;
for(int i=0;i<n;i++){
int need = target - a[i];
if([Link](need)){ i1 = [Link](need); i2 = i; break; }
[Link](a[i], i);
}
[Link](i1 + " " + i2);
[Link]();
}
}
css
n d
a0 a1 ... a(n-1)
java
// [Link]
import [Link].*;
public class LeftRotation {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link](); int d = [Link]();
d = (n==0) ? 0 : d % n;
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
int[] out = new int[n];
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/40
for(int i=0;i<n;i++){
out[i] = a[(i + d) % n == 0 ? d % n : (i + d) % n]; // simpler: out[i]=a[(i+d)%n] but we want left
rotate by d -> element at i goes to (i-d+n)%n; easier build directly:
}
// simpler correct rebuild:
for(int i=0;i<n;i++) out[i] = a[(i + d) % n];
StringJoiner sj = new StringJoiner(" ");
for(int x: out) [Link]([Link](x));
[Link]([Link]());
[Link]();
}
}
(Note: above builds array starting from index d — left rotation by d yields sequence a[d], a[d+1], ... a[n-1], a[0] ... a[d-1].)
css
n
a0 a1 ... a(n-1)
java
// [Link]
import [Link].*;
public class MoveZeros {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
int write=0;
for(int i=0;i<n;i++){
if(a[i]!=0) a[write++]=a[i];
}
while(write<n) a[write++]=0;
StringJoiner sj = new StringJoiner(" ");
for(int x: a) [Link]([Link](x));
[Link]([Link]());
[Link]();
}
}
less
Approach: Use Floyd's Tortoise & Hare on array seen as next indices (requires values range 1..n). O(n) time, O(1) space.
java
// [Link]
import [Link].*;
public class FindDuplicate {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int len = [Link](); // actual length (n+1)
int[] a = new int[len];
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/40
for(int i=0;i<len;i++) a[i]=[Link]();
// Floyd's cycle detection
int slow = a[0], fast = a[a[0]];
while(slow != fast){
slow = a[slow];
fast = a[a[fast]];
}
fast = 0;
while(slow != fast){
slow = a[slow];
fast = a[fast];
}
[Link](slow);
[Link]();
}
}
css
n m
a0 ... a(n-1)
b0 ... b(m-1)
java
// [Link]
import [Link].*;
public class MergeSorted {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link](), m = [Link]();
int[] a = new int[n], b = new int[m];
for(int i=0;i<n;i++) a[i]=[Link]();
for(int j=0;j<m;j++) b[j]=[Link]();
int i=0,j=0;
List<Integer> out = new ArrayList<>(n+m);
while(i<n && j<m){
if(a[i] <= b[j]) [Link](a[i++]);
else [Link](b[j++]);
}
while(i<n) [Link](a[i++]);
while(j<m) [Link](b[j++]);
StringJoiner sj = new StringJoiner(" ");
for(int x: out) [Link]([Link](x));
[Link]([Link]());
[Link]();
}
}
css
n
a0 a1 ... a(n-1)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/40
java
// [Link]
import [Link].*;
public class KadaneMaxSubarray {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
int maxSoFar = Integer.MIN_VALUE, cur = 0;
for(int x: a){
cur = [Link](x, cur + x);
maxSoFar = [Link](maxSoFar, cur);
}
[Link](maxSoFar);
[Link]();
}
}
css
n
a0 a1 ... a(n-1)
Approach: Use merge-sort based counting. O(n log n) time, O(n) extra.
java
// [Link]
import [Link].*;
public class InversionCount {
static long mergeCount(int[] a, int l, int r, int[] tmp){
if(r - l <= 1) return 0;
int m = (l + r) >>> 1;
long cnt = mergeCount(a, l, m, tmp) + mergeCount(a, m, r, tmp);
int i=l, j=m, k=l;
while(i<m || j<r){
if(j==r || (i<m && a[i] <= a[j])){
tmp[k++] = a[i++];
} else {
tmp[k++] = a[j++];
cnt += (m - i); // all remaining in left are inversions with a[j-1]
}
}
[Link](tmp, l, a, l, r-l);
return cnt;
}
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
long inv = mergeCount(a, 0, n, new int[n]);
[Link](inv);
[Link]();
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/40
css
n
a0 a1 ... a(n-1)
Approach: Boyer-Moore voting (O(n) time, O(1) space). If unsure of existence, one extra pass to verify.
java
// [Link]
import [Link].*;
public class MajorityElement {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i] = [Link]();
int candidate = 0, count = 0;
for(int x: a){
if(count==0){ candidate = x; count = 1; }
else if(candidate == x) count++;
else count--;
}
// Optional verify:
int freq = 0;
for(int x: a) if(x==candidate) freq++;
if(freq > n/2) [Link](candidate);
else [Link]("No majority element");
[Link]();
}
}
css
n
a0 a1 ... a(n-1)
Approach: Compute prefix products and suffix products. O(n) time, O(n) extra (can be O(1) extra if output array allowed).
Handles zeros correctly.
java
// [Link]
import [Link].*;
public class ProductExceptSelf {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]();
long[] a = new long[n];
for(int i=0;i<n;i++) a[i]=[Link]();
long[] left = new long[n];
long[] right = new long[n];
left[0] = 1;
for(int i=1;i<n;i++) left[i] = left[i-1] * a[i-1];
right[n-1] = 1;
for(int i=n-2;i>=0;i--) right[i] = right[i+1] * a[i+1];
StringJoiner sj = new StringJoiner(" ");
for(int i=0;i<n;i++){
[Link]([Link](left[i] * right[i]));
}
[Link]([Link]());
[Link]();
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/40
HackerRank often expects a class named Main. If you paste a solution class with a different name, rename the class to
Main.
Pay attention to constraints — if n can be large, use long for counts/products and avoid O(n²) solutions.
For multi-test-case problems, wrap scanner reads accordingly (some problems give t first).
Always close the Scanner or just let the program end (closing is optional).
Combine all 10 into one menu-driven Main where you choose which problem to run, or
Nice — here are 10 very common string DSA problems you’ll see in interviews / HackerRank, each with:
You can copy any class into HackerRank (rename to Main if required) or paste multiple into one file and run them
individually.
java
// [Link]
import [Link].*;
public class ReverseString {
public static String reverse(String s) {
char[] a = [Link]();
int i = 0, j = [Link] - 1;
while (i < j) {
char t = a[i]; a[i++] = a[j]; a[j--] = t;
}
return new String(a);
}
public static void main(String[] args) {
[Link](reverse("hello")); // "olleh"
}
}
java
// [Link]
public class IsPalindrome {
public static boolean isPalindrome(String s) {
int i = 0, j = [Link]() - 1;
while (i < j) {
if ([Link](i) != [Link](j)) return false;
i++; j--;
}
return true;
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/40
}
public static void main(String[] args) {
[Link](isPalindrome("level")); // true
[Link](isPalindrome("hello")); // false
}
}
java
// [Link]
public class ValidPalindrome {
public static boolean isValidPalindrome(String s) {
int i = 0, j = [Link]() - 1;
while (i < j) {
while (i < j && )) i++;
while (i < j && )) j--;
if ([Link]([Link](i)) != [Link]([Link](j))) return false;
i++; j--;
}
return true;
}
public static void main(String[] args) {
[Link](isValidPalindrome("A man, a plan, a canal: Panama")); // true
[Link](isValidPalindrome("race a car")); // false
}
}
java
// [Link]
import [Link].*;
public class AnagramCheck {
public static boolean isAnagram(String a, String b) {
if ([Link]() != [Link]()) return false;
int[] freq = new int[256];
for (int i=0;i<[Link]();i++){
freq[[Link](i)]++;
freq[[Link](i)]--;
}
for (int c: freq) if (c != 0) return false;
return true;
}
public static void main(String[] args) {
[Link](isAnagram("listen","silent")); // true
[Link](isAnagram("hello","bello")); // false
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/40
java
// [Link]
import [Link].*;
public class FirstNonRepeating {
public static int firstUniqueCharIndex(String s) {
int[] freq = new int[256];
for (char c: [Link]()) freq[c]++;
for (int i=0;i<[Link]();i++) if (freq[[Link](i)] == 1) return i;
return -1;
}
public static void main(String[] args) {
[Link](firstUniqueCharIndex("leetcode")); // 0 ('l')
[Link](firstUniqueCharIndex("loveleetcode")); // 2 ('v')
}
}
java
// [Link]
public class LongestCommonPrefix {
public static String longestCommonPrefix(String[] strs) {
if (strs == null || [Link] == 0) return "";
String pref = strs[0];
for (int i = 1; i < [Link]; i++) {
while (!strs[i].startsWith(pref)) {
pref = [Link](0, [Link]() - 1);
if ([Link]()) return "";
}
}
return pref;
}
public static void main(String[] args) {
[Link](longestCommonPrefix(new String[]{"flower","flow","flight"})); // "fl"
[Link](longestCommonPrefix(new String[]{"dog","racecar","car"})); // ""
}
}
java
// [Link]
public class LongestPalSubstr {
public static String longestPalindrome(String s) {
if (s == null || [Link]() < 1) return "";
int start = 0, end = 0;
for (int i = 0; i < [Link](); i++) {
int len1 = expand(s, i, i);
int len2 = expand(s, i, i+1);
int len = [Link](len1, len2);
if (len > end - start + 1) {
start = i - (len - 1) / 2;
end = i + len / 2;
}
}
return [Link](start, end + 1);
}
private static int expand(String s, int L, int R) {
while (L >= 0 && R < [Link]() && [Link](L) == [Link](R)) { L--; R++; }
return R - L - 1;
}
public static void main(String[] args) {
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/40
[Link](longestPalindrome("babad")); // "bab" or "aba"
[Link](longestPalindrome("cbbd")); // "bb"
}
}
java
// [Link]
import [Link].*;
public class LongestUniqueSubstring {
public static int lengthOfLongestSubstring(String s) {
int[] last = new int[256]; // store last index +1; 0 means not seen
int start = 0, maxLen = 0;
for (int i = 0; i < [Link](); i++) {
start = [Link](start, last[[Link](i)]);
maxLen = [Link](maxLen, i - start + 1);
last[[Link](i)] = i + 1;
}
return maxLen;
}
public static void main(String[] args) {
[Link](lengthOfLongestSubstring("abcabcbb")); // 3 ("abc")
[Link](lengthOfLongestSubstring("bbbbb")); // 1 ("b")
}
}
java
// [Link]
public class Atoi {
public static int myAtoi(String s) {
int i = 0, n = [Link]();
while (i < n && [Link]([Link](i))) i++;
int sign = 1;
if (i < n && ([Link](i) == '+' || [Link](i) == '-')) {
if ([Link](i) == '-') sign = -1;
i++;
}
long num = 0;
while (i < n && [Link]([Link](i))) {
num = num * 10 + ([Link](i) - '0');
if (sign * num <= Integer.MIN_VALUE) return Integer.MIN_VALUE;
if (sign * num >= Integer.MAX_VALUE) return Integer.MAX_VALUE;
i++;
}
return (int) (sign * num);
}
public static void main(String[] args) {
[Link](myAtoi(" -42")); // -42
[Link](myAtoi("4193 with text"));// 4193
[Link](myAtoi("91283472332")); // Integer.MAX_VALUE
}
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/40
Problem: Given an array of strings, group anagrams together.
Approach: Use a normalized key: sorted string or frequency signature. Use HashMap from key → list.
Time: O(N * L log L) if sorting each string (L length), or O(N * L) with frequency key. Space: O(NL).
java
// [Link]
import [Link].*;
public class GroupAnagrams {
public static List<List<String>> groupAnagrams(String[] strs) {
Map<String, List<String>> map = new HashMap<>();
for (String s : strs) {
char[] ch = [Link]();
[Link](ch);
String key = new String(ch);
[Link](key, k -> new ArrayList<>()).add(s);
}
return new ArrayList<>([Link]());
}
public static void main(String[] args) {
String[] in = {"eat","tea","tan","ate","nat","bat"};
[Link](groupAnagrams(in));
// e.g. [[eat, tea, ate], [tan, nat], [bat]]
}
}
Combine all 10 into a single menu-driven Main program that asks which problem to run and reads input (useful for
practicing), or
Provide HackerRank / stdin-structured versions for each problem (I/O exactly as those platforms expect), or
Replace any O(n²) solutions (e.g., palindromic substring) with more optimal ones (Manacher’s algorithm) and explain
it.
css
n k
a0 a1 ... a(n-1)
Approach: Reverse whole array, reverse first k, reverse rest (O(1) extra).
Time: O(n), Space: O(1)
java
import [Link].*;
public class RotateRight {
public static void main(String[] args){
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/40
Scanner sc = new Scanner([Link]);
int n = [Link](); int k = [Link]();
int[] a = new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
if(n>0){
k = ((k % n) + n) % n;
reverse(a, 0, n-1);
reverse(a, 0, k-1);
reverse(a, k, n-1);
}
print(a);
[Link]();
}
static void reverse(int[] a,int l,int r){ while(l<r){ int t=a[l]; a[l++]=a[r]; a[r--]=t; } }
static void print(int[] a){ StringJoiner sj=new StringJoiner(" "); for(int x:a) [Link]([Link](x));
[Link](sj); }
}
Statement: Find any subarray whose sum equals S (array of non-negative ints). Print start and end indices (0-based) or -1
-1 if none.
Input:
css
n S
a0 a1 ... a(n-1)
java
import [Link].*;
public class SubarrayWithSum {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](); long S=[Link]();
long[] a=new long[n];
for(int i=0;i<n;i++) a[i]=[Link]();
int l=0;
long sum=0;
for(int r=0;r<n;r++){
sum += a[r];
while(sum > S && l<=r){ sum -= a[l++]; }
if(sum == S){ [Link](l + " " + r); [Link](); return; }
}
[Link]("-1 -1");
[Link]();
}
}
Statement: Print all unique triplets [i,j,k] (values) such that a[i]+a[j]+a[k]==0. Output each triplet on a new line or
nothing if none.
Input:
css
n
a0 a1 ... a(n-1)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/40
java
import [Link].*;
public class ThreeSum {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link]();
int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
[Link](a);
List<List<Integer>> res=new ArrayList<>();
for(int i=0;i<n;i++){
if(i>0 && a[i]==a[i-1]) continue;
int l=i+1, r=n-1;
while(l<r){
long sum=(long)a[i]+a[l]+a[r];
if(sum==0){
[Link]([Link](a[i], a[l], a[r]));
int leftVal=a[l], rightVal=a[r];
while(l<r && a[l]==leftVal) l++;
while(l<r && a[r]==rightVal) r--;
} else if(sum<0) l++;
else r--;
}
}
for(List<Integer> t: res){
[Link]([Link](0)+" "+[Link](1)+" "+[Link](2));
}
[Link]();
}
}
css
n k
a0 a1 ... a(n-1)
java
import [Link].*;
public class KthLargest {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](), k=[Link]();
int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
PriorityQueue<Integer> pq=new PriorityQueue<>();
for(int x: a){
[Link](x);
if([Link]()>k) [Link]();
}
[Link]([Link]());
[Link]();
}
}
css
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/40
a0 a1 ... a(n-1)
java
import [Link].*;
public class Sort012 {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link]();
int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
int low=0, mid=0, high=n-1;
while(mid<=high){
if(a[mid]==0){ swap(a, low++, mid++); }
else if(a[mid]==1){ mid++; }
else { swap(a, mid, high--); }
}
StringJoiner sj=new StringJoiner(" ");
for(int x:a) [Link]([Link](x));
[Link](sj);
[Link]();
}
static void swap(int[] a,int i,int j){ int t=a[i]; a[i]=a[j]; a[j]=t; }
}
Statement: Array of size n contains numbers from 1..(n+1) with one missing. Find the missing.
Input:
less
java
import [Link].*;
public class FindMissing {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](); // size n, numbers in 1..n+1 with one missing
long xor = 0;
for(int i=1;i<=n+1;i++) xor ^= i;
for(int i=0;i<n;i++) xor ^= [Link]();
[Link](xor);
[Link]();
}
}
Statement: Find all elements that appear more than n/3 times. Print space-separated or None.
Input:
css
n
a0 a1 ... a(n-1)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 33/40
java
import [Link].*;
public class MajorityElementII {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](); int[] a=new int[n];
for(int i=0;i<n;i++) a[i]=[Link]();
Integer cand1=null, cand2=null; int cnt1=0, cnt2=0;
for(int x:a){
if(cand1!=null && cand1==x) cnt1++;
else if(cand2!=null && cand2==x) cnt2++;
else if(cnt1==0){ cand1 = x; cnt1 = 1; }
else if(cnt2==0){ cand2 = x; cnt2 = 1; }
else { cnt1--; cnt2--; }
}
List<Integer> res=new ArrayList<>();
int c1=0,c2=0;
for(int x:a){ if(cand1!=null && x==cand1) c1++; if(cand2!=null && x==cand2) c2++; }
if(cand1!=null && c1 > n/3) [Link](cand1);
if(cand2!=null &&  && c2 > n/3) [Link](cand2);
if([Link]()) [Link]("None");
else { StringJoiner sj=new StringJoiner(" "); for(int x:res) [Link]([Link](x));
[Link](sj); }
[Link]();
}
}
Statement: Given array (can contain negative), find maximum product of a contiguous subarray.
Input:
css
n
a0 a1 ... a(n-1)
Approach: Maintain maxProd and minProd at each position because negative flips sign.
Time: O(n), Space: O(1)
java
import [Link].*;
public class MaxProductSubarray {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](); long[] a=new long[n];
for(int i=0;i<n;i++) a[i]=[Link]();
long maxProd=a[0], minProd=a[0], ans=a[0];
for(int i=1;i<n;i++){
long x=a[i];
long t1 = [Link](x, [Link](maxProd * x, minProd * x));
long t2 = [Link](x, [Link](maxProd * x, minProd * x));
maxProd = t1; minProd = t2;
ans = [Link](ans, maxProd);
}
[Link](ans);
[Link]();
}
}
css
n
p0 p1 ... p(n-1)
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 34/40
Approach: Track min price so far and max profit.
Time: O(n), Space: O(1)
java
import [Link].*;
public class MaxProfit {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](); long[] p=new long[n];
for(int i=0;i<n;i++) p[i]=[Link]();
long minPrice = Long.MAX_VALUE, maxProfit=0;
for(long price: p){
if(price < minPrice) minPrice = price;
else maxProfit = [Link](maxProfit, price - minPrice);
}
[Link](maxProfit);
[Link]();
}
}
Statement: Find any index i such that sum of elements left of i equals sum to right of i. Print index or -1.
Input:
css
n
a0 a1 ... a(n-1)
java
import [Link].*;
public class EquilibriumIndex {
public static void main(String[] args){
Scanner sc=new Scanner([Link]);
int n=[Link](); long[] a=new long[n];
long total=0;
for(int i=0;i<n;i++){ a[i]=[Link](); total+=a[i]; }
long left=0;
for(int i=0;i<n;i++){
total -= a[i]; // now total is right sum
if(left == total){ [Link](i); [Link](); return; }
left += a[i];
}
[Link](-1);
[Link]();
}
}
Combine these into one menu-driven Main program so you can pick which problem to run at runtime; or
Provide HackerRank-style single-file versions (rename to Main and exact expected I/O) for any subset you care about;
or
Add sample inputs and outputs for each problem.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 35/40
If you paste into an online judge that requires class Main, rename the public class <Name> to public class Main.
vbnet
java
import [Link].*;
public class ReverseStringInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
char[] a = [Link]();
int i = 0, j = [Link] - 1;
while (i < j) {
char t = a[i]; a[i++] = a[j]; a[j--] = t;
}
[Link](new String(a));
[Link]();
}
}
arduino
java
import [Link].*;
public class ValidPalindromeInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
int i = 0, j = [Link]()-1;
boolean ok = true;
while (i < j) {
while (i < j && )) i++;
while (i < j && )) j--;
if ([Link]([Link](i)) != [Link]([Link](j))) { ok = false; break; }
i++; j--;
}
[Link](ok);
[Link]();
}
}
rust
two lines:
line1 -> s1
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/40
line2 -> s2
java
import [Link].*;
public class AnagramCheckInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s1 = [Link]() ? [Link]() : "";
String s2 = [Link]() ? [Link]() : "";
if ([Link]() != [Link]()) { [Link](false); [Link](); return; }
int[] freq = new int[256];
for (int i = 0; i < [Link](); i++) {
freq[[Link](i)]++;
freq[[Link](i)]--;
}
for (int f : freq) if (f != 0) { [Link](false); [Link](); return; }
[Link](true);
[Link]();
}
}
arduino
one line: s
Approach: count freq then scan to find first with freq 1. O(n).
java
import [Link].*;
public class FirstUniqueCharInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
int[] freq = new int[256];
for (char c : [Link]()) freq[c]++;
int idx = -1;
for (int i = 0; i < [Link](); i++) if (freq[[Link](i)] == 1) { idx = i; break; }
[Link](idx);
[Link]();
}
}
lua
java
import [Link].*;
public class LongestCommonPrefixInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
int n = [Link]() ? [Link]() : 0;
[Link](); // consume newline
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 37/40
if (n <= 0) { [Link](""); [Link](); return; }
String pref = [Link]();
for (int i = 1; i < n; i++) {
String s = [Link]();
while () {
if ([Link]()) break;
pref = [Link](0, [Link]() - 1);
}
}
[Link](pref);
[Link]();
}
}
arduino
one line: s
java
import [Link].*;
public class LongestPalSubstrInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
if ([Link]() < 1) { [Link](""); [Link](); return; }
int start = 0, end = 0;
for (int i = 0; i < [Link](); i++) {
int len1 = expand(s, i, i);
int len2 = expand(s, i, i+1);
int len = [Link](len1, len2);
if (len > end - start + 1) {
start = i - (len-1)/2;
end = i + len/2;
}
}
[Link]([Link](start, end+1));
[Link]();
}
private static int expand(String s, int L, int R) {
while (L >= 0 && R < [Link]() && [Link](L) == [Link](R)) { L--; R++; }
return R - L - 1;
}
}
arduino
one line: s
java
import [Link].*;
public class LongestUniqueSubstringInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
int[] last = new int[256]; [Link](last, -1);
int start = 0, maxLen = 0;
for (int i = 0; i < [Link](); i++) {
char c = [Link](i);
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 38/40
if (last[c] >= start) start = last[c] + 1;
last[c] = i;
maxLen = [Link](maxLen, i - start + 1);
}
[Link](maxLen);
[Link]();
}
}
arduino
one line: s
Approach: skip spaces, optional +/- sign, parse digits with overflow checks. O(n).
java
import [Link].*;
public class AtoiInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
[Link](myAtoi(s));
[Link]();
}
public static int myAtoi(String s) {
int i = 0, n = [Link]();
while (i < n && [Link]([Link](i))) i++;
int sign = 1;
if (i < n && ([Link](i) == '+' || [Link](i) == '-')) {
if ([Link](i) == '-') sign = -1;
i++;
}
long num = 0;
while (i < n && [Link]([Link](i))) {
num = num * 10 + ([Link](i) - '0');
if (sign * num <= Integer.MIN_VALUE) return Integer.MIN_VALUE;
if (sign * num >= Integer.MAX_VALUE) return Integer.MAX_VALUE;
i++;
}
return (int) (sign * num);
}
}
9) Find all occurrences of a pattern in text (KMP) — print starting indices (0-
based)
Input
rust
two lines:
line1 -> text
line2 -> pattern
java
import [Link].*;
public class KMPSearchInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String text = [Link]() ? [Link]() : "";
String pat = [Link]() ? [Link]() : "";
List<Integer> occ = kmp(text, pat);
if ([Link]()) [Link]();
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 39/40
else {
StringJoiner sj = new StringJoiner(" ");
for(int idx: occ) [Link]([Link](idx));
[Link]([Link]());
}
[Link]();
}
arduino
one line: s
Approach: boolean seen array for ASCII to keep first occurrence, build result. O(n).
java
import [Link].*;
public class RemoveDuplicatesStringInput {
public static void main(String[] args){
Scanner sc = new Scanner([Link]);
String s = [Link]() ? [Link]() : "";
boolean[] seen = new boolean[256];
StringBuilder sb = new StringBuilder();
for (char c : [Link]()) {
if (!seen[c]) { seen[c] = true; [Link](c); }
}
[Link]([Link]());
[Link]();
}
}
Combine all 10 into a single menu-driven program (pick problem number at runtime), or
Provide HackerRank-style permutations (rename classes to Main and adapt inputs), or
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 40/40