0% found this document useful (0 votes)
5 views40 pages

Java Collections Framework Guide

This document serves as a comprehensive guide to the Java Collections Framework, detailing its core components such as List, Set, Queue/Deque, and Map, along with their common methods and examples using Integer and String. It includes specific implementations like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and more, providing code snippets for practical understanding. Additionally, it outlines 15 common algorithms in C++ and their Java equivalents, emphasizing the use of Java's built-in collection utilities.

Uploaded by

ashu430pm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views40 pages

Java Collections Framework Guide

This document serves as a comprehensive guide to the Java Collections Framework, detailing its core components such as List, Set, Queue/Deque, and Map, along with their common methods and examples using Integer and String. It includes specific implementations like ArrayList, LinkedList, HashSet, TreeSet, HashMap, and more, providing code snippets for practical understanding. Additionally, it outlines 15 common algorithms in C++ and their Java equivalents, emphasizing the use of Java's built-in collection utilities.

Uploaded by

ashu430pm
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java collection framework example

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.

✅ Java Collection Framework (For Integer & String)


Java Collections Framework provides ready-made data structures to store, manipulate & organize data efficiently.

It mainly has these parts:

List
Set
Queue / Deque

Map
Utility classes: Collections, Arrays

I will explain each with:


✔ Definition
✔ Common methods
✔ Example with Integer & String

🚀 1. LIST
List = Ordered collection, allows duplicates.

Common Methods:

add(E e)

add(int index, E element)

get(int index)

set(int index, E element)

remove(int index) / remove(Object o)


size()

contains(Object o)

isEmpty()

Iteration: for, for-each, Iterator

⭐ 1.1 ArrayList (Most used)


Dynamic array
Fast random access
Slow insertion in middle

✔ Example with Integer & String


java

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

[Link](nums); // [10, 15, 20, 30]


[Link]([Link](2)); // 20

[Link]([Link](15)); // remove element


[Link](1, 200); // update
[Link](nums);

// String List
List<String> names = new ArrayList<>();
[Link]("Ashutosh");
[Link]("Rahul");
[Link]("Riya");

[Link]([Link]("Rahul")); // true

for (String s : names)


[Link](s);
}
}

⭐ 1.2 LinkedList
Doubly linked list
Faster insertion/deletion in middle
Can be used as Queue

✔ Example:
java

List<String> list = new LinkedList<>();


[Link]("A");
[Link]("B");
[Link]("C");
[Link](1);
[Link](list); // [A, C]

🚀 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

Set<Integer> set = new HashSet<>();


[Link](10);
[Link](20);
[Link](10); // duplicate (ignored)
[Link](set);

⭐ 2.2 LinkedHashSet
Maintains insertion order.

java

Set<String> lhs = new LinkedHashSet<>();


[Link]("A");
[Link]("C");
[Link]("B");
[Link](lhs); // [A, C, B]

⭐ 2.3 TreeSet
Sorted set (natural order)
Internally uses Red-Black Tree

java

Set<Integer> ts = new TreeSet<>();


[Link](30);
[Link](10);
[Link](20);
[Link](ts); // [10, 20, 30]

🚀 3. MAP
Map = Key–Value pairs

Keys must be unique


Values can repeat

Common Methods

put(K key, V value)

get(Object key)

containsKey(Object key)

containsValue(Object value)

remove(Object key)

keySet()

values()

entrySet()

⭐ 3.1 HashMap (Most used)


Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/40
java

Map<Integer, String> map = new HashMap<>();


[Link](1, "Ashutosh");
[Link](2, "Rahul");
[Link](3, "Riya");

[Link]([Link](2)); // Rahul

// Loop through map


for ([Link]<Integer, String> e : [Link]()) {
[Link]([Link]() + " -> " + [Link]());
}

⭐ 3.2 LinkedHashMap
Maintains insertion order.

java

Map<String, Integer> lhm = new LinkedHashMap<>();


[Link]("A", 10);
[Link]("B", 20);
[Link]("C", 30);
[Link](lhm);

⭐ 3.3 TreeMap
Sorted map by keys.

java

Map<Integer, String> tm = new TreeMap<>();


[Link](20, "B");
[Link](10, "A");
[Link](30, "C");

[Link](tm); // {10=A, 20=B, 30=C}

🚀 4. QUEUE / DEQUE
⭐ 4.1 PriorityQueue
Min-heap
Elements sorted automatically

java

PriorityQueue<Integer> pq = new PriorityQueue<>();


[Link](30);
[Link](10);
[Link](20);

[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

Deque<String> dq = new ArrayDeque<>();


[Link]("A");
[Link]("B");
[Link]("C");

[Link]([Link]()); // A

🚀 5. STACK (Legacy class)


Use Deque instead; but Stack still used in exams.

java

Stack<Integer> st = new Stack<>();


[Link](10);
[Link](20);
[Link](30);

[Link]([Link]()); // 30
[Link]([Link]()); // 30

🚀 6. COLLECTIONS UTILITY CLASS


Contains static methods like:

[Link](list)

[Link](list)

[Link](list)

[Link](list)

Example:

java

List<Integer> list = [Link](5, 1, 4, 3, 2);


[Link](list);
[Link](list); // [1, 2, 3, 4, 5]

📌 Summary Table
Interface/Class Ordered Allows Duplicate Sorted Example

ArrayList ✔ ✔ ❌ List of names


LinkedList ✔ ✔ ❌ Implement queue

HashSet ❌ ❌ ❌ Unique IDs


LinkedHashSet ✔ ❌ ❌ Unique + Maintain order

TreeSet ✔ ❌ ✔ Sorted unique values


HashMap ❌ Keys=Unique ❌ Key-Value store

LinkedHashMap ✔ Keys=Unique ❌ Ordered map


TreeMap ✔ Keys=Unique ✔ Sorted map

🚀 Want a PDF Notes Version of This?


I can generate a clean, exam-ready PDF for your revision if you want.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/40
Just say: "Yes, generate PDF".

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).

15 common algorithms (C++ style → Java Collections equivalents)


For every snippet assume:
import [Link].*; import [Link].*;
When I use List<Integer> / List<String> the examples are shown for both types when relevant.

1) sort (std::sort)
Java equivalent: [Link](list) or [Link](Comparator)
Complexity: O(n log n) (TimSort, stable)

java

List<Integer> li = new ArrayList<>([Link](5, 1, 4, 3, 2));


[Link](li); // ascending
// For descending:
[Link]([Link]());

List<String> ls = new ArrayList<>([Link]("z", "apple", "bob"));


[Link](ls); // lexicographic

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

// same as above; stability preserved when comparator considers equal elements

3) reverse (std::reverse)
Java equivalent: [Link](list)
Complexity: O(n)

java

List<Integer> li = new ArrayList<>([Link](1,2,3,4));


[Link](li); // [4,3,2,1]

List<String> ls = new ArrayList<>([Link]("a","b","c"));


[Link](ls);

4) shuffle (std::random_shuffle / std::shuffle)

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

List<Integer> li = new ArrayList<>([Link](1,2,3,4,5));


[Link](li, new Random(42)); // deterministic with seed

5) binary_search (std::binary_search)
Java equivalent: [Link](list, key) (list must be sorted)
Complexity: O(log n)

java

List<Integer> li = new ArrayList<>([Link](1,2,3,4,5));


int idx = [Link](li, 3); // returns index 2
// For Strings:
List<String> ls = new ArrayList<>([Link]("a","b","c"));
[Link](ls);
int i = [Link](ls, "b");

If not found: returns -(insertionPoint) - 1. You can compute insertion point: insertionPoint = -res - 1.

6) lower_bound / upper_bound (C++ style)


Java equivalent: [Link] plus maths to find insertion point; or use NavigableSet/TreeSet (ceiling/higher)
for set behavior.
Complexity: O(log n)

java

// lower_bound equivalent (first >= key)


List<Integer> li = new ArrayList<>([Link](1,3,3,5,7));
[Link](li);
int res = [Link](li, 3);
int lower;
if (res >= 0) {
// binarySearch returns any matching index; scan left to find first occurrence
lower = res;
while (lower > 0 && [Link](lower-1).equals(3)) lower--;
} else {
lower = -res - 1; // insertion point
}

// upper_bound equivalent (first > key)


int upper;
if (res >= 0) {
upper = res;
while (upper < [Link]() && [Link](upper).equals(3)) upper++;
} else {
upper = -res - 1;
}

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

List<Integer> li = new ArrayList<>([Link](2,4,6,8));


int index = [Link](6); // 2
boolean exists = [Link](5); // false

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

List<Integer> li = new ArrayList<>([Link](1,2,2,3,2));


int freq = [Link](li, 2); // 3

// predicate counting with streams:


long evenCount = [Link]().filter(x -> x % 2 == 0).count();

9) accumulate / reduce (std::accumulate)


Java equivalent: stream().reduce(...) or mapToInt(...).sum() for numbers
Complexity: O(n)

java

List<Integer> li = new ArrayList<>([Link](1,2,3,4));


int sum = [Link]().mapToInt(Integer::intValue).sum(); // 10

// general reduce:
int prod = [Link]().reduce(1, (a,b) -> a*b);

10) transform (std::transform) — map each element


Java equivalent: stream().map(...) or [Link](UnaryOperator)
Complexity: O(n)

java

List<Integer> li = new ArrayList<>([Link](1,2,3));


List<Integer> doubled = [Link]().map(x -> x*2).collect([Link]());
// or in-place:
[Link](x -> x * 2);

List<String> names = new ArrayList<>([Link]("ash", "bob"));


List<String> upper = [Link]().map(String::toUpperCase).collect([Link]());

11) copy (std::copy)


Java equivalent: [Link](dest, src) or [Link](src) (common)
Complexity: O(n)

java

List<Integer> src = new ArrayList<>([Link](1,2,3));


List<Integer> dest = new ArrayList<>([Link](new Integer[[Link]()])); // same size
[Link](dest, src); // copies into existing dest positions

// Simpler: addAll (dest can be empty)


List<Integer> dest2 = new ArrayList<>();
[Link](src);

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

List<Integer> li = new ArrayList<>([Link](1,2,3,4,5,6));


[Link](x -> x % 2 == 0); // removes even numbers; li now [1,3,5]

List<String> names = new ArrayList<>([Link]("a","", "b"));


[Link](String::isEmpty); // removes empty strings

13) unique (std::unique — remove consecutive duplicates) / remove


duplicates generally
Java equivalent:

To remove duplicates while preserving order: use LinkedHashSet or stream().distinct()


To emulate std::unique (only remove consecutive duplicates) use List scan or stream with state.

java

// Remove all duplicates, preserve insertion order:


List<Integer> li = new ArrayList<>([Link](1,2,2,3,1));
List<Integer> unique = [Link]().distinct().collect([Link]()); // [1,2,3]

// Emulate std::unique (remove only consecutive duplicates):


List<Integer> a = new ArrayList<>([Link](1,1,2,2,2,3,3,1));
List<Integer> out = new ArrayList<>();
Integer prev = null;
for (Integer x : a) {
if (![Link](prev, x)) {
[Link](x);
}
prev = x;
}
// out = [1,2,3,1]

14) rotate (std::rotate)


Java equivalent: [Link](list, distance)
Complexity: O(n)

java

List<Integer> li = new ArrayList<>([Link](1,2,3,4,5));


// rotate right by 2 -> [4,5,1,2,3]
[Link](li, 2);

15) partition / stable_partition (std::partition)


Java equivalent:

[Link] + collect removed, or


[Link](predicate) to get a Map<Boolean, List<T>> — non-destructive.
Complexity: O(n)

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/40
java

List<Integer> li = new ArrayList<>([Link](1,2,3,4,5,6));

// Non-destructive partition using streams:


Map<Boolean, List<Integer>> parts = [Link]()
.collect([Link](x -> x % 2 == 0));
List<Integer> evens = [Link](true);
List<Integer> odds = [Link](false);

// In-place partition (not stable): reorder manually


int i = 0, j = [Link]()-1;
while (i <= j) {
while (i <= j && [Link](i) % 2 != 0) i++;
while (i <= j && [Link](j) % 2 == 0) j--;
if (i < j) [Link](li, i++, j--);
}
// after this, odds at front, evens at back (unstable)

Note: If you want a stable partition keep two lists and combine: List<T> yes = ...; List<T> no = ...; [Link](no).

Quick reference table


C++ algorithm Java equivalent

sort / stable_sort [Link] / [Link](Comparator)


reverse [Link]
shuffle [Link]
binary_search [Link]

lower_bound/upper_bound [Link] + insertionPoint or TreeSet methods


find indexOf / contains / stream().findFirst()
count [Link] / stream().filter().count()
accumulate stream().reduce() / mapToInt().sum()

transform stream().map() or [Link]()


copy [Link] / addAll
remove_if [Link]
unique (distinct) stream().distinct() or LinkedHashSet

rotate [Link]
partition [Link]() or manual reorder
for_each [Link](Consumer) or stream().forEach()

Example full program (all algorithms in one file)


Below is a condensed runnable demonstration that executes many of the algorithms on Integer lists. Paste into a file
[Link] and run.

java

import [Link].*;
import [Link].*;

public class AlgoExamples {


public static void main(String[] args) {
List<Integer> a = new ArrayList<>([Link](5,1,4,3,2,2,3));
[Link]("original: " + a);

// 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);

// binary search (needs sorted)


[Link](a);
[Link]("sorted again: " + a);
int pos = [Link](a, 3);
[Link]("binarySearch(3) => " + pos);

// lower/upper bound demo (simple linear extend from result)


int lb=0, ub=0;
if (pos >= 0) {
lb = pos; while (lb>0 && [Link](lb-1).equals(3)) lb--;
ub = pos; while (ub<[Link]() && [Link](ub).equals(3)) ub++;
} else {
lb = ub = -pos - 1;
}
[Link]("lowerBound(3)=" + lb + " upperBound(3)=" + ub);

// 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);

// remove_if (remove even numbers)


[Link](x -> x % 2 == 0);
[Link]("after removeIf even: " + 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));
}
}

If you'd like, I can now:

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.

Which follow-up would you prefer?

Great — here’s a single, runnable Java program that:

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 {

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);

[Link]("Enter integers (space-separated). Press Enter for default: 5 1 4 3 2 2 3");


String intLine = [Link]().trim();
List<Integer> ints = [Link]()
? new ArrayList<>([Link](5, 1, 4, 3, 2, 2, 3))
: [Link]([Link]("\\s+")).map(Integer::parseInt).collect([Link]());

[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]());

[Link]("\n--- Input Lists ---");


printlnList("Integers", ints);
printlnList("Strings", strs);

[Link]("\n--- 1) sort (stable) ---");


List<Integer> intsSort = new ArrayList<>(ints);
List<String> strsSort = new ArrayList<>(strs);
[Link](intsSort); // stable
[Link](strsSort); // stable
printlnList("Ints sorted", intsSort);
printlnList("Strs sorted", strsSort);

[Link]("\n--- 2) stable_sort (same as sort in Java - TimSort is stable) ---");


// Already stable; show sorting with comparator (stable)
[Link]([Link]());
[Link]([Link]());
printlnList("Ints stable-sorted", intsSort);
printlnList("Strs stable-sorted", strsSort);

[Link]("\n--- 3) reverse ---");


List<Integer> intsRev = new ArrayList<>(intsSort);
List<String> strsRev = new ArrayList<>(strsSort);
[Link](intsRev);
[Link](strsRev);
printlnList("Ints reversed", intsRev);
printlnList("Strs reversed", strsRev);

[Link]("\n--- 4) shuffle ---");


List<Integer> intsShuf = new ArrayList<>(ints);
List<String> strsShuf = new ArrayList<>(strs);
[Link](intsShuf, new Random()); // non-deterministic
[Link](strsShuf, new Random());
printlnList("Ints shuffled", intsShuf);
printlnList("Strs shuffled", strsShuf);

[Link]("\n--- 5) binary_search (requires sorted) ---");


[Link](intsSort);
[Link](strsSort);
[Link]("Sorted ints for binary_search: " + intsSort);
[Link]("Sorted strs for binary_search: " + strsSort);
Integer keyInt = [Link]() ? null : [Link]([Link]() / 2);
String keyStr = [Link]() ? null : [Link]([Link]() / 2);
if (keyInt != null) {
int res = [Link](intsSort, keyInt);
[Link]("binarySearch ints for key=" + keyInt + " -> index: " + res);
}
if (keyStr != null) {
int res = [Link](strsSort, keyStr);
[Link]("binarySearch strs for key=\"" + keyStr + "\" -> index: " + res);
}

[Link]("\n--- 6 & 7) lower_bound & upper_bound (O(log n)) ---");


// Demonstrate using generic lowerBound/upperBound

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);
}

[Link]("\n--- 8) find (indexOf / contains / stream findFirst) ---");


if (![Link]()) {
int f = [Link]([Link](0));
[Link]("indexOf first element in ints: " + f + " (value: " + [Link](0) + ")");
}
if (![Link]()) {
boolean has = [Link]([Link](0));
[Link]("contains \"" + [Link](0) + "\" -> " + has);
Optional<String> found = [Link]().filter(s -> [Link]() > 3).findFirst();
[Link]("stream findFirst string with length>3: " + [Link]("none"));
}

[Link]("\n--- 9) count (frequency) ---");


if (![Link]()) {
int v = [Link](0);
[Link]("frequency of " + v + " in ints: " + [Link](ints, v));
}
if (![Link]()) {
String w = [Link](0);
[Link]("frequency of \"" + w + "\" in strs: " + [Link](strs, w));
}

[Link]("\n--- 10) accumulate / reduce (sum for ints) ---");


int sum = [Link]().mapToInt(Integer::intValue).sum();
[Link]("sum of ints: " + sum);
String concat = [Link]().collect([Link](", "));
[Link]("concatenated strings (comma-separated): " + concat);

[Link]("\n--- 11) transform (map) ---");


List<Integer> doubled = [Link]().map(x -> x * 2).collect([Link]());
List<String> upper = [Link]().map(String::toUpperCase).collect([Link]());
printlnList("doubled ints", doubled);
printlnList("upper-case strs", upper);

[Link]("\n--- 12) copy ---");


// [Link] requires destination sized at least source
List<Integer> destInts = new ArrayList<>([Link]([Link](), 0));
[Link](destInts, ints);
printlnList("copied ints -> destInts", destInts);

List<String> destStrs = new ArrayList<>([Link]([Link](), ""));


[Link](destStrs, strs);
printlnList("copied strs -> destStrs", destStrs);

[Link]("\n--- 13) remove_if (remove predicate) ---");


List<Integer> removeIfInts = new ArrayList<>(ints);
[Link](x -> x % 2 == 0); // remove evens
printlnList("ints after removeIf (remove evens)", removeIfInts);

List<String> removeIfStrs = new ArrayList<>(strs);


[Link](String::isEmpty); // remove empty strings
printlnList("strs after removeIf (remove empty)", removeIfStrs);

[Link]("\n--- 14) unique / distinct ---");


List<Integer> distinctInts = [Link]().distinct().collect([Link]());
printlnList("distinct ints (preserve order)", distinctInts);
List<String> distinctStrs = [Link]().distinct().collect([Link]());
printlnList("distinct strs (preserve order)", distinctStrs);

[Link]("\n--- unique (consecutive duplicates removed like std::unique) ---");


List<Integer> consecUniqueInts = removeConsecutiveDuplicates(new ArrayList<>(ints));
printlnList("ints after removing consecutive duplicates", consecUniqueInts);

[Link]("\n--- 15) rotate ---");


List<Integer> rotInts = new ArrayList<>([Link](1, 2, 3, 4, 5));
[Link](rotInts, 2); // rotate right by 2
printlnList("rotated ints [1,2,3,4,5] by 2 ->", rotInts);

[Link]("\n--- partition (partitioningBy / in-place unstable partition demo) ---");


List<Integer> part = new ArrayList<>([Link](1, 2, 3, 4, 5, 6));
Map<Boolean, List<Integer>> parts = [Link]().collect([Link](x -> x % 2 == 0));
printlnList("evens (partition true)", [Link](true));
printlnList("odds (partition false)", [Link](false));

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/40
[Link]("\n--- Done ---");
[Link]();
}

// ---- Utility methods ----

private static <T> void printlnList(String title, List<T> list) {


[Link](title + ": " + list);
}

/**
* 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](prev, x)) {
[Link](x);
prev = x;
first = false;
}
}
return out;
}
}

Notes & tips

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.

If you want any of these:

Save output to file,


Add an interactive menu to choose which algorithm to run,
Or a version that reads input from a file — tell me which and I’ll update the program.

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/40
Here is the simplest and cleanest Java code to:

1. Take input from user


2. Store values in an ArrayList
3. Multiply each element by 4
4. Print the updated list

✅ Java Code (ArrayList Input + Multiply by 4)


java

import [Link].*;

public class MultiplyElements {


public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

// Create ArrayList
ArrayList<Integer> list = new ArrayList<>();

[Link]("Enter number of elements: ");


int n = [Link]();

[Link]("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
[Link]([Link]());
}

// Multiply each element by 4


for (int i = 0; i < [Link](); i++) {
[Link](i, [Link](i) * 4);
}

// Print result
[Link]("After multiplying each element by 4:");
[Link](list);

[Link]();
}
}

📌 Example Input
yaml

Enter number of elements: 5


Enter 5 integers:
1 2 3 4 5

📌 Output
pgsql

After multiplying each element by 4:


[4, 8, 12, 16, 20]

If you want, I can give:

A version using streams ([Link](x -> x*4))


A version for strings, doubles, or custom objects
Or a version that reads input until the user types "stop"

Just tell me!

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.

1) Reverse an array in-place


Problem: Reverse an integer array in-place.
Approach: Two pointers swap from ends toward center.
Time: O(n), Space: O(1)

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));
}
}

2) Two Sum (indices) — target sum


Problem: Given array a and target, return indices of two numbers adding to target (assume one solution).
Approach: HashMap for complement → O(n).
Time: O(n), Space: O(n)

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]
}
}

3) Binary Search (sorted array)

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
}
}

4) Remove duplicates from a sorted array (in-place)


Problem: Given sorted array, remove duplicates so each element appears once and return new length (modify in-place).
Approach: Two-pointer / slow-fast.
Time: O(n), Space: O(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)));
}
}

5) Merge two sorted arrays (into a new array)


Problem: Given two sorted arrays, merge into a single sorted array.
Approach: Two-pointer merge (like merge step in merge sort).
Time: O(n+m), Space: O(n+m)

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]
}
}

6) Kadane’s Algorithm — Maximum Subarray Sum


Problem: Given array, find contiguous subarray with max sum.
Approach: Kadane (running current sum and max).
Time: O(n), Space: O(1)

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])
}
}

7) Reverse a singly linked list (iterative)


Problem: Given head of singly linked list, reverse it and return new head.
Approach: Iterative three-pointer (prev, curr, next).
Time: O(n), Space: O(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
}
}

9) BFS traversal of a binary tree (level-order)


Problem: Print level-order traversal of a binary tree.
Approach: Use a Queue (FIFO).
Time: O(n), Space: O(width) worst-case O(n)

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]]
}
}

10) Count set bits in an integer (Brian Kernighan’s algorithm)


Problem: Count number of 1 bits in binary representation of n.
Approach: Repeatedly do n &= (n - 1) which removes lowest set bit — runs in #set-bits steps.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/40
Time: O(#ones) ≤ O(log n), Space: O(1)

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:

Problem statement (short)


Expected input format (HackerRank-style / STDIN)
Approach + time/space complexity
A complete, ready-to-run Java solution (one class with main that reads from stdin and prints output)

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.

1) Reverse an array (in-place)


Problem: Reverse the elements of an array.
Input format:

css

n
a0 a1 a2 ... a(n-1)

Output: Reversed array (space separated)


Approach: Two-pointer swap. O(n) time, O(1) extra space.

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]();
}
}

2) Two Sum (exist pair with target)


Problem: Given array and target, print indices (0-based) of any pair that sums to target or print -1 -1 if none.
Input:

css

n target
a0 a1 ... a(n-1)

Approach: HashMap for complement. O(n) time, O(n) space.

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]();
}
}

3) Left rotation by d (HackerRank classic)


Problem: Rotate array left by d positions.
Input:

css

n d
a0 a1 ... a(n-1)

Output: Rotated array


Approach: Compute new indices or use reversal technique. O(n) time, O(n) or O(1) extra (reversal). Here simple O(n) extra
for clarity.

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].)

4) Move zeros to end (stable)


Problem: Move all zeros to the end while preserving order of non-zero elements.
Input:

css

n
a0 a1 ... a(n-1)

Approach: Two-pointer write index. O(n) time, O(1) extra.

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]();
}
}

5) Find duplicate (one duplicate) — array of n+1 with values 1..n


Problem: There is one duplicate value. Find it (without modifying array) — use Floyd or HashSet.
Input:

less

n // length is n+1 actually, containing numbers 1..n


a0 a1 ... a(n)

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]();
}
}

6) Merge two sorted arrays (produce merged sorted array)


Problem: Given two sorted arrays, output merged sorted array.
Input:

css

n m
a0 ... a(n-1)
b0 ... b(m-1)

Approach: Two-pointer merge. O(n+m) time, O(n+m) space.

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]();
}
}

7) Maximum subarray sum (Kadane)


Problem: Largest sum of contiguous subarray.
Input:

css

n
a0 a1 ... a(n-1)

Approach: Kadane’s algorithm. O(n) time, O(1) space.

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]();
}
}

8) Count inversions (number of pairs i<j with a[i]>a[j])


Problem: Count inversions in array. Output the inversion count (use long).
Input:

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]();
}
}

9) Majority Element (element appearing > n/2 times)


Problem: Find element that appears more than n/2 times. Assume such element exists.
Input:

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]();
}
}

10) Product of array except self (without division)


Problem: For each index i, output product of all elements except a[i]. Use long if required.
Input:

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]();
}
}

Final tips for HackerRank

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).

Would you like me to:

Combine all 10 into one menu-driven Main where you choose which problem to run, or

Produce printable one-page cheat-sheet PDF with code snippets?


Which next?

Nice — here are 10 very common string DSA problems you’ll see in interviews / HackerRank, each with:

short problem statement

approach + time/space complexity


a concise, runnable Java solution (single class with main() demonstrating usage)

You can copy any class into HackerRank (rename to Main if required) or paste multiple into one file and run them
individually.

1) Reverse a string (in-place for char array)


Problem: Reverse the characters of a string.
Approach: Two-pointer swap.
Time: O(n), Space: O(1) for in-place (or O(n) to build new string).

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"
}
}

2) Check palindrome (case-sensitive)


Problem: Check whether a string reads the same forwards and backwards.
Approach: Two pointers comparing characters. (For ignoring spaces/punctuation, prefilter.)
Time: O(n), Space: O(1).

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
}
}

3) Valid palindrome (ignore non-alphanumeric, case-insensitive)


Problem: Determine if a string is palindrome considering only letters/digits and ignoring case.
Approach: Two-pointer with [Link] + toLowerCase.
Time: O(n), Space: O(1).

java

// [Link]
public class ValidPalindrome {
public static boolean isValidPalindrome(String s) {
int i = 0, j = [Link]() - 1;
while (i < j) {
while (i < j && ![Link]([Link](i))) i++;
while (i < j && ![Link]([Link](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
}
}

4) Check anagram (same characters, frequency)


Problem: Given two strings, check if they are anagrams (same character counts).
Approach: Frequency array / HashMap. For lowercase letters use int[26].
Time: O(n), Space: O(1) (alphabet-limited) or O(k).

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
}
}

5) First non-repeating character


Problem: Return the first character that appears only once in the string (or -1/index if none).
Approach: Two-pass: freq map then find first with freq 1.
Time: O(n), Space: O(1) (fixed alphabet) or O(k).

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')
}
}

6) Longest common prefix


Problem: Given an array of strings, find the longest common prefix.
Approach: Horizontal scanning or binary search. (Here: horizontal scanning)
Time: O(S) where S is sum of all characters, Space: O(1).

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"})); // ""
}
}

7) Longest palindromic substring (expand around center)


Problem: Return the longest palindromic substring.
Approach: For every center expand left/right (handles odd & even). O(n²) time, O(1) extra. (Manacher is O(n), but this is
simpler and common.)

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"
}
}

8) Longest substring without repeating characters


Problem: Length of the longest substring with all unique characters.
Approach: Sliding window with last-seen index (two pointers).
Time: O(n), Space: O(1) (fixed alphabet) or O(k).

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")
}
}

9) Implement atoi (string to integer) — handle signs, overflow


Problem: Convert string to 32-bit signed integer with rules: ignore leading spaces, optional +/- sign, read digits, clamp to
INT range.
Approach: Parse char-by-char, check overflow before multiply/add.
Time: O(n), Space: O(1).

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
}
}

10) Group anagrams

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]]
}
}

If you want, I can:

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.

Which of those would you like next?

Great — here are 10 more common array DSA problems in Java.


For each problem you get:

Short statement, approach, and complexities.


A complete, runnable Java class that reads input from stdin (using Scanner) and prints the answer.

Input format is shown before the code.


Tip: If you paste into an online judge that requires the class to be named Main, rename the public class <Name> to
public class Main.

Problem 1 — Rotate array right by k

Statement: Rotate array to the right by k positions.


Input:

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); }
}

Problem 2 — Subarray with given sum (non-negative numbers)

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)

Approach: Sliding window (two pointers).


Time: O(n), Space: O(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]();
}
}

Problem 3 — 3-Sum (all unique triplets summing to 0)

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)

Approach: Sort then two-pointer for each element, skip duplicates.


Time: O(n²), Space: O(log n) for sort

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]();
}
}

Problem 4 — Kth largest element

Statement: Find k-th largest element (1-based: k=1 => largest).


Input:

css

n k
a0 a1 ... a(n-1)

Approach: Use min-heap of size k.


Time: O(n log k), Space: O(k)

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]();
}
}

Problem 5 — Sort array of 0s,1s,2s (Dutch National Flag)

Statement: Sort an array containing only 0,1,2 in-place.


Input:

css

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 32/40
a0 a1 ... a(n-1)

Approach: Three pointers low, mid, high.


Time: O(n), Space: O(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; }
}

Problem 6 — Find missing number in 1..n (one missing)

Statement: Array of size n contains numbers from 1..(n+1) with one missing. Find the missing.
Input:

less

n // array length (n), actual full range is 1..n+1


a0 a1 ... a(n-1)

Approach: Use XOR or sum formula to find missing.


Time: O(n), Space: O(1)

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]();
}
}

Problem 7 — Majority element II (elements appearing > n/3)

Statement: Find all elements that appear more than n/3 times. Print space-separated or None.
Input:

css

n
a0 a1 ... a(n-1)

Approach: Extended Boyer-Moore: at most two candidates, then verify.


Time: O(n), Space: O(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 && ![Link](cand2,cand1) && c2 > n/3) [Link](cand2);
if([Link]()) [Link]("None");
else { StringJoiner sj=new StringJoiner(" "); for(int x:res) [Link]([Link](x));
[Link](sj); }
[Link]();
}
}

Problem 8 — Maximum product subarray

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]();
}
}

Problem 9 — Best time to buy and sell stock (one transaction)

Statement: Given prices array, maximize profit from one buy-sell.


Input:

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]();
}
}

Problem 10 — Equilibrium index (index where left sum == right sum)

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)

Approach: Compute total sum then iterate maintaining left sum.


Time: O(n), Space: O(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]();
}
}

If you want, I can now:

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.

Which would you like next?

Great — here are 10 more common string DSA problems in Java.


Each problem includes: short statement, input format, approach note, and a complete runnable Java class that reads
from stdin (using Scanner) and prints the answer.

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.

1) Reverse a string (print reversed)


Input

vbnet

a single line: the string s

Approach: reverse char array in-place. O(n) time, O(1) extra.

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]();
}
}

2) Check palindrome (ignore non-alphanumeric, case-insensitive)


Input

arduino

one line: the string s

Approach: two-pointer skipping non-alnum chars. O(n).

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 && ![Link]([Link](i))) i++;
while (i < j && ![Link]([Link](j))) j--;
if ([Link]([Link](i)) != [Link]([Link](j))) { ok = false; break; }
i++; j--;
}
[Link](ok);
[Link]();
}
}

3) Check anagram (two strings)


Input

rust

two lines:
line1 -> s1

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 36/40
line2 -> s2

Approach: frequency array (works for ASCII/Unicode if extended). O(n).

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]();
}
}

4) First non-repeating character (print index or -1)


Input

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]();
}
}

5) Longest common prefix (array of strings)


Input

lua

first line: n (number of strings)


next n lines: each string

Approach: horizontal scanning shrinking prefix. O(total chars).

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 (![Link](pref)) {
if ([Link]()) break;
pref = [Link](0, [Link]() - 1);
}
}
[Link](pref);
[Link]();
}
}

6) Longest palindromic substring (expand around centers)


Input

arduino

one line: s

Approach: expand around each center (odd/even). O(n²) worst-case.

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;
}
}

7) Longest substring without repeating characters (print length)


Input

arduino

one line: s

Approach: sliding window with last-seen indices. O(n).

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]();
}
}

8) Implement atoi (string to 32-bit signed integer)


Input

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

Approach: KMP prefix-function for O(n + m).

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]();
}

static List<Integer> kmp(String s, String p) {


List<Integer> res = new ArrayList<>();
if ([Link]() == 0) { for (int i=0;i<=[Link]();i++) [Link](i); return res; }
int[] lps = buildLPS(p);
int i=0, j=0;
while (i < [Link]()) {
if ([Link](i) == [Link](j)) { i++; j++; if (j==[Link]()){ [Link](i-j); j = lps[j-1]; } }
else if (j>0) j = lps[j-1];
else i++;
}
return res;
}

static int[] buildLPS(String p) {


int n = [Link]();
int[] lps = new int[n];
int len = 0, i = 1;
while (i < n) {
if ([Link](i) == [Link](len)) lps[i++] = ++len;
else if (len > 0) len = lps[len-1];
else lps[i++] = 0;
}
return lps;
}
}

10) Remove duplicate characters (preserve first occurrence order)


Input

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]();
}
}

If you want I can:

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

Add sample inputs/expected outputs for each problem.

Which would you like next?

Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 40/40

You might also like