Chaturmind
LearnDSASystem DesignInterview PrepDevOpsEngineering GrowthBlog
Start learning
Chaturmind

Structured learning paths for engineers who want to go deep. Written by practitioners.

Learn

  • Java
  • DSA
  • System Design
  • Spring Boot
  • AI / ML
  • DevOps
  • Engineering Growth
  • Java Interview Prep

Company

  • Blog
  • Contact

Legal

  • Privacy Policy
  • Terms of Service

© 2026 Chaturmind. All rights reserved.

Built for engineers who want to go deep.


← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
Chaturmind
← Java Interview Prep: 2–5 Years

Revise the Fresher Tier

  • Revise: Core Java Fundamentals (Fresher Tier)
  • Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)
  • Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)
  • Revise: Hibernate, SQL, Microservices, Maven & Git (Fresher Tier)

Intermediate Core Java

  • Intermediate OOP & Language Features — Interview Questions
  • Enums, Generics, Pass-by-Value & Imports — Interview Questions
  • Collections Internals & Scenarios — Interview Questions
  • JVM, Memory & Class Loading — Interview Questions
  • Exception Design & Serialization Edge Cases — Interview Questions

Java 8 Deep Dive & Stream Coding

  • Lambdas, Functional Interfaces & Method References — Interview Questions
  • Default Methods, Backward Compatibility & Optional — Interview Questions
  • Stream API Internals (Part 1) — Interview Questions
  • Stream API Internals (Part 2) — Interview Questions
  • Stream Coding Problems (Level 2, Part 1) — Interview Questions
  • Stream Coding Problems (Level 2, Part 2) — Interview Questions

Concurrency & Multithreading

  • Synchronization, Locks & Deadlocks — Interview Questions
  • Executors, ThreadLocal & Concurrent Collections — Interview Questions

Spring Framework In Depth

  • Bean Lifecycle, Contexts & Circular Dependencies — Interview Questions
  • Spring Bean Conflicts, AOP, Batch & Injection Styles — Interview Questions

Spring Boot In Depth & Scenarios

  • Spring Boot Internals & Auto-Configuration — Interview Questions
  • Spring Boot Configuration, Profiles & Secrets — Interview Questions
  • Spring Boot Data, Transactions & Caching — Interview Questions
  • Spring Boot Testing, Error Pages & Deployment — Interview Questions
  • Spring Boot Performance, Scaling & Resilience — Interview Questions
  • Spring Boot Async, Events & Messaging — Interview Questions
  • Spring Boot Security Scenarios — Interview Questions
  • Actuator, AOP, Spring Cloud & Distributed Tracing — Interview Questions
  • External APIs, Files, GraphQL & WebFlux — Interview Questions

Spring Security

  • Spring Security — OAuth2, CORS, CSRF & Access Rules — Interview Questions
  • Spring Security — Passwords, Filter Chain, Sessions & Debugging — Interview Questions

Apache Kafka

  • Kafka Architecture, Topics & ZooKeeper vs KRaft — Interview Questions
  • Kafka Producers, Consumers, Reliability & Streams — Interview Questions
  • Kafka Security, Connect & Core Scenarios — Interview Questions
  • Kafka Production Scenarios — Interview Questions

Git, Maven & Gradle (Level II)

  • Git Workflows, Rebase & Conflict Handling — Interview Questions
  • Git Recovery, Hooks, Tags & Collaboration — Interview Questions
  • Maven Builds, Multi-Module Projects & Dependency Resolution — Interview Questions
  • Maven Profiles, settings.xml, Plugins & Quality Gates — Interview Questions
  • Gradle Fundamentals, Migration & Dependencies — Interview Questions
  • Gradle Performance, Plugins, Testing & Publishing — Interview Questions

Deployment & CI/CD

  • Sessions, CI/CD Pipelines, Rollbacks & Secrets — Interview Questions
  • Migrations, Zero-Downtime Releases, Containers & Monitoring — Interview Questions

JUnit 5 & Mockito

  • JUnit 5 — Interview Questions
  • Mockito Basics — Interview Questions
  • Mockito Advanced & Tricky Questions — Interview Questions
HomeLearnJava Interview PrepJava Interview Prep: 2–5 YearsRevise the Fresher Tier
✓ FreeIntermediate· 33 min read

Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)

Every fresher-level question on collections, multithreading basics, Java 8 streams and coding-round programs, in one-line form with links.

Published September 25, 2026


How to use this revision

This page condenses every question from the Fresher to 2 Years course in these areas into a single line: the question, linked to its full answer, and the one-sentence answer you should be able to give instantly. Read down the list and answer each question aloud before reading the line. Wherever you hesitate, follow the link and revise the full answer — interviewers at your level expect these basics to be fluent, and they often open with them before going deeper.

Collections Framework

Collections Framework Basics — Interview Questions — open the lesson

  • What is the Java Collections Framework? — A unified set of interfaces (Collection, List, Set, Queue, Deque, Map), implementations (ArrayList, HashSet, HashMap, ArrayDeque, …) and algorithms (sorting, searching and shuffling in Collections and Arrays) for storing and processing groups of objects.
  • What are the main interfaces of the Collections Framework? — - Collection (the root for groups of elements), with its sub-interfaces: - List: ordered, allows duplicates, index-based. - Set: no duplicates. - Queue/Deque: processing order.
  • How does an Iterator work? — An Iterator walks through a collection one element at a time with hasNext() and next(). It can also safely remove the current element with iterator.remove().
  • What methods do all Collection types share? — - add, addAll, remove, removeAll, retainAll, clear. - size, isEmpty, contains, containsAll. - iterator, toArray. - Since Java 8: stream(), removeIf() and forEach().
  • How does the Collections Framework handle concurrency? — The ordinary collections (ArrayList, HashMap) are not thread-safe. For concurrent use there are three options: - Synchronized wrappers: Collections.synchronizedList(...).
  • How do you choose the right collection for a problem? — Ask four questions: do I need key-value lookup? Uniqueness? Ordering (insertion or sorted)? Which operation dominates (random access, insert or remove, contains)?
  • What did Java 8 add to the Collections Framework? — Streams (collection.stream()), and lambda-friendly default methods: forEach, removeIf, replaceAll, sort on List, and the new Map methods (getOrDefault, putIfAbsent, computeIfAbsent, merge).
  • What's the difference between Iterator and ListIterator? — Iterator works on any Collection, moves forward only, and can remove. ListIterator works only on lists, moves in both directions (hasPrevious()/previous()), knows the current index (nextIndex()), and can also set (replace) and add elements during iteration.
  • Which algorithms do Arrays.sort() and Collections.sort() use? — - Arrays.sort() on primitive arrays uses Dual-Pivot Quicksort. It's fast, but not stable (stability doesn't matter for primitives). - On object arrays, Arrays.sort() uses TimSort, a stable hybrid of merge sort and insertion sort that exploits runs already in order. -…
  • How do you store elements in a set while preserving insertion order? — Use a LinkedHashSet. It's a HashSet whose entries are also linked together in a doubly linked list, so iteration follows insertion order, with O(1) operations like HashSet.
  • How do you store elements so they stay sorted? — Use a TreeSet (unique elements) or a TreeMap (keys). They keep elements in natural order (Comparable), or in the order of a Comparator you supply, with O(log n) operations and navigation methods such as first(), ceiling() and headSet().
  • When would you use ArrayList, LinkedList and HashSet? — - ArrayList: the default list. O(1) index access, and amortised O(1) appends. It's cache-friendly, because the elements sit in one contiguous array. - LinkedList: O(1) inserts and removals at the ends, or at a position you already hold an iterator to.
  • What is the internal implementation of ArrayList and LinkedList? — - ArrayList is backed by an Object[] array. - When the array is full, it grows by about 50% (a new array plus a copy), so appends cost amortised O(1). - get(i) is O(1).

HashMap, HashSet & TreeMap Internals — Interview Questions — open the lesson

  • How does a HashSet guarantee no duplicates? — A HashSet is backed by a HashMap. Each element is stored as a key, with a shared dummy value. Map keys are unique, so add of an equal element just finds the existing key and returns false.
  • How do hashCode() and equals() work together in hash-based collections? — hashCode() decides which bucket an object belongs in. equals() decides whether two objects in that bucket are the same key.
  • Why must you override hashCode() when you override equals()? — If two objects are equal but have different hash codes, they land in different buckets. HashMap and HashSet then never compare them with equals, so lookups fail, and "duplicate" entries appear.
  • What happens if you don't? — Hash collections misbehave silently: contains returns false for an equal object, get returns null, and sets hold logical duplicates.
  • When is a TreeSet more appropriate than a HashSet? — When you need the elements sorted, or need range and nearest-value queries. Examples: displaying customer names alphabetically, finding the next free appointment slot after 3 pm, or getting the top-N scores.
  • How does HashMap work internally? — HashMap is an array of buckets (a Node<K,V>[] table). Here's what put(key, value) does: 1. It computes key.hashCode() and spreads it: h ^ (h >>> 16), which mixes the high bits into the low ones. 2.
  • What happens when two keys have the same hash code? — That's a hash collision. Both entries go into the same bucket, and HashMap tells them apart with equals().
  • How does HashMap handle collisions, and what changed in Java 8? — Before Java 8, each bucket was a linked list, so a badly colliding bucket made lookups O(n). Since Java 8, when a bucket holds more than 8 entries (and the table has at least 64 buckets), it's converted into a red-black tree, which makes the worst case O(log n).
  • Can you use your own class as a HashMap key? — Yes. Any object can be a key, but it must implement equals() and hashCode() consistently, and it should be immutable.
  • What is ConcurrentHashMap, and how does it improve multi-threaded performance? — It's a thread-safe Map that allows many threads to read and write at the same time without locking the whole map: - Reads are mostly lock-free, because they rely on volatile reads. - Writes use CAS (compare-and-swap) to put a node into an empty bin, or lock only the…
  • What's the time complexity of HashMap/HashSet versus TreeMap/TreeSet? — Compared side by side in the full answer (table) — know each row.
  • What data structures do HashMap, TreeMap, HashSet and TreeSet use internally? — - HashMap: an array of buckets. Each bucket is a linked list, or a red-black tree when it has many collisions. - TreeMap: a red-black tree, a self-balancing binary search tree ordered by key. - HashSet: wraps a HashMap. - TreeSet: wraps a TreeMap.
  • What's the difference between HashMap and TreeMap? — HashMap is unordered, with O(1) average operations, and allows one null key. TreeMap keeps keys sorted, has O(log n) operations, offers navigation (firstKey, floorKey, subMap), and doesn't allow null keys with natural ordering, because compareTo would throw an…
  • When would you prefer a TreeMap over a HashMap? — When you need keys in sorted order, or range queries. Examples: showing a price list sorted by product name, finding "the tax slab for this income" with floorEntry(income), or pulling all events between two timestamps with subMap(from, to).
  • Can any object be a key in a TreeMap? — Only if the keys can be compared: either they implement Comparable, or you pass a Comparator to the TreeMap constructor.

Multithreading Basics

Threads, Synchronization & volatile Basics — Interview Questions — open the lesson

  • What is a thread? What is multithreading? — A thread is an independent path of execution inside a process: the smallest unit of work the operating system schedules.
  • How do you create a thread in Java? — You give a Thread a task and call start(). There are three ways to supply the task: 1. Implement Runnable (or use a lambda). 2.
  • What's the difference between the Thread class and the Runnable interface? — Runnable represents the task (what to run). Thread represents the worker that runs it. Implementing Runnable is preferred: your class stays free to extend another class, the task stays separate from the threading mechanism, and the same task can be run by a thread pool.
  • What is the lifecycle of a thread? — A thread moves through the Thread.State values: - NEW: created, but start() not called yet. - RUNNABLE: running, or ready to run. - BLOCKED: waiting to acquire a monitor lock. - WAITING: waiting indefinitely, for example in wait(), join() or LockSupport.park(). -…
  • Can you start a thread twice? — No. Calling start() a second time on the same Thread object throws an IllegalThreadStateException, even after it has finished.
  • What does the synchronized keyword do? — It ensures that only one thread at a time executes a block or method guarded by the same monitor lock. It also guarantees visibility: changes made before releasing the lock are seen by the next thread that acquires it.
  • What is volatile? — volatile guarantees visibility and ordering for a single variable. A write by one thread is immediately visible to other threads that read it, and the compiler and CPU can't reorder operations around it in ways that break that guarantee.
  • How do you make a method thread-safe? — The options, roughly from best to worst: 1. Avoid shared mutable state. Use local variables, immutable objects, or confine data to a single thread. 2.
  • Two threads must update the same data structure. How do you handle it? — Make the updates atomic with respect to each other. Either use a concurrent structure (ConcurrentHashMap.merge, ConcurrentLinkedQueue), or guard every access to the shared structure with the same lock.
  • What is thread synchronisation, and why is it important? — Synchronisation coordinates threads' access to shared state. It prevents race conditions (lost updates, inconsistent reads) and ensures visibility of changes between threads.
  • When would you use wait() and notify()? — For one thread to wait for a condition that another thread will make true. The classic example is producer-consumer: the consumer waits while the queue is empty, and the producer notifies it after adding an item.
  • What challenges come with multithreaded programs? — Race conditions, deadlocks (two threads each waiting for the other's lock), livelock and starvation, visibility bugs (stale values), contention (threads queuing for locks), and bugs that are hard to reproduce, because they depend on timing.
  • What is the Java Memory Model, and how does it relate to threads? — The JMM is the specification of when a write made by one thread becomes visible to another, and which reorderings are allowed.
  • What is the Exchanger class? — java.util.concurrent.Exchanger<V> is a synchronisation point where two threads swap objects. Each thread calls exchange(myObject), blocks until its partner arrives, and then receives the partner's object.
  • Can you build a server in Java without Spring or any framework? — Yes. The JDK includes everything you need: - java.net.ServerSocket for a raw TCP server. - com.sun.net.httpserver.HttpServer for a simple HTTP server. - Java 18's jwebserver tool for serving static files.

Java 8+ & Stream API

Java 8 to Java 21 Features — Interview Questions — open the lesson

  • What is a functional interface? — An interface with exactly one abstract method (a SAM, "single abstract method"). Its instances can be created with lambdas, method references or constructor references.
  • Can a functional interface extend another interface? What are the advantages of functional interfaces? — Yes, as long as the result still has exactly one abstract method in total. It can extend an interface that has only default or static methods, or one whose single abstract method is the same one it declares.
  • What were the major features of Java 8? — - Lambda expressions and method references. - Functional interfaces (java.util.function). - The Stream API. - Default and static methods in interfaces. - Optional. - The new Date-Time API (java.time). - Also: CompletableFuture, StringJoiner/String.join, collection…
  • Why were Optional, lambdas and the Stream API introduced? — - Lambdas: to pass behaviour as data concisely, instead of writing anonymous classes. That was essential for parallel and functional-style libraries. - Streams: to express bulk operations on collections declaratively (what, not how), with pipelines that can be lazy and easily…
  • What's the difference between filter and map in streams? — filter(predicate) keeps or drops elements, so the stream may get smaller but the element type stays the same.
  • What were the new features in Java 11 (LTS)? — - The standard HTTP Client (java.net.http, supporting HTTP/2 and async). - var in lambda parameters. - Running single-file programs directly (java Hello.java). - New String methods: isBlank(), strip(), stripLeading(), stripTrailing(), lines(), repeat(). -…
  • What were the new features in Java 17 (LTS)? — - Sealed classes became final in 17. - Features finalised between Java 12 and 16, which 17 is the first LTS to include: - records; - pattern matching for instanceof; - text blocks; - switch expressions. - Also: strong encapsulation of JDK internals, new random-number…
  • What were the new features in Java 21 (LTS)? — - Virtual threads (Project Loom). - Sequenced collections (getFirst(), getLast(), reversed()). - Record patterns. - Pattern matching for switch. - Generational ZGC.
  • Which is faster, a traditional for loop or a stream? — For simple operations on small or medium collections, a plain loop is usually a little faster. There's no pipeline set-up, no lambda calls, and no boxing.
  • When would you use a loop, and when a stream? — Use a stream for declarative data transformations (filter, map, group, aggregate), where readability matters. Use a loop when you need early exit with complex conditions, checked exceptions, index manipulation, updates to several variables, or maximum performance in a hot path.
  • What are intermediate and terminal operations? — Intermediate operations (filter, map, sorted, distinct, limit) return a new stream and are lazy: nothing runs until a terminal operation is called.
  • How did interfaces change from Java 7 to Java 8 (and 9)? — In Java 7, interfaces could have only abstract methods and constants. Java 8 added default methods (inherited, overridable implementations) and static methods.
  • What is String.join() used for? — It concatenates strings with a delimiter, without manual loops or trailing separators.

Stream API Coding Questions (Part 1) — Interview Questions — open the lesson

  • Filter the even numbers from a list. — List<Integer> evens = numbers.stream() .filter(n -> n % 2 == 0)
  • Find the maximum value. — Optional<Integer> max = numbers.stream().max(Comparator.naturalOrder());
  • Calculate the sum of the elements. — int sum = numbers.stream().mapToInt(Integer::intValue).sum();
  • Convert a list of names to uppercase. — List<String> upper = names.stream() .map(n -> n.toUpperCase(Locale.ROOT))
  • Sort a list in ascending (and descending) order. — List<Integer> asc = numbers.stream().sorted().toList();
  • Count the elements greater than 5. — long count = numbers.stream().filter(n -> n > 5).count();
  • Get the distinct elements. — List<Integer> unique = numbers.stream().distinct().toList();
  • Reduce a list to its sum using reduce. — int total = numbers.stream().reduce(0, Integer::sum);
  • Return any element from the list. — Optional<Integer> any = numbers.stream().findAny();
  • Extract the first names from a list of full names. — List<String> firstNames = names.stream() .map(String::strip)

Stream API Coding Questions (Part 2) — Interview Questions — open the lesson

  • Check whether all numbers are positive. — boolean allPositive = numbers.stream().allMatch(n -> n > 0);
  • Check that there are no negative numbers. — boolean noNegatives = numbers.stream().noneMatch(n -> n < 0);
  • Find the first element. — Optional<Integer> first = numbers.stream().findFirst();
  • Flatten a nested list. — List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3, 4, 5), List.of()); List<Integer> flat =…
  • Group users by age (and more). — Map<Integer, List<User>> byAge = users.stream() .collect(Collectors.groupingBy(User::age));
  • Print elements during processing without altering the stream. — List<Integer> result = numbers.stream() .filter(n -> n > 5)
  • Limit the output to the first three elements. — List<Integer> firstThree = numbers.stream().limit(3).toList();
  • Skip the first two elements. — List<Integer> rest = numbers.stream().skip(2).toList();
  • Convert a list to a Set to remove duplicates. — Set<Integer> unique = numbers.stream().collect(Collectors.toSet());
  • Get summary statistics (min, max, average, sum, count). — IntSummaryStatistics stats = numbers.stream().mapToInt(Integer::intValue).summaryStatistics(); stats.getMin();

Coding Round Programs

Classic Number & String Programs — Interview Questions — open the lesson

  • Reverse a string without using built-in reverse functions. — Use two pointers, one at each end, swapping characters as they move towards the middle. O(n) time, O(n) extra space for the character array (strings are immutable, so a copy is unavoidable).
  • Swap two numbers without a third variable. — Use arithmetic (a = a + b; b = a - b; a = a - b;) or XOR (a ^= b; b ^= a; a ^= b;).
  • Check whether a number is prime, efficiently. — Handle the small cases, rule out multiples of 2 and 3, then test only candidates of the form 6k ± 1 up to √n. That's O(√n) time.
  • Check whether a string or a number is a palindrome. — For strings, compare characters from both ends moving inwards: O(n) time, O(1) space. For numbers, reverse half the digits and compare, with no string conversion.
  • Print the Fibonacci series using recursion. — fib(n) = fib(n-1) + fib(n-2), with fib(0) = 0 and fib(1) = 1. The plain recursive version is O(2ⁿ), because it recomputes the same values again and again.
  • Check whether a number is an Armstrong number. — An Armstrong (narcissistic) number equals the sum of its digits, each raised to the power of the number of digits.
  • Repeatedly add the digits of a number until one digit remains. — Loop: sum the digits, and repeat while the sum is 10 or more. Or use the O(1) digital root formula: n == 0 ? 0 : 1 + (n - 1) % 9.
  • Check whether an integer is a power of two. — A power of two has exactly one bit set. n & (n - 1) clears the lowest set bit, so the result is 0 only for powers of two.

String & Collection Programs — Interview Questions — open the lesson

  • Count the number of occurrences of each word in a string using a HashMap. — Normalise the text, split it on whitespace, and count with Map.merge (or getOrDefault). O(n) time.
  • Iterate over a HashMap using a while loop and an enhanced for loop. — Iterate over entrySet(), so you get the key and the value together without extra lookups. Use the enhanced for loop for reading.
  • Iterate over an ArrayList using a for loop, a while loop and an enhanced for loop. — List<Integer> list = List.of(10, 20, 30); for (int i = 0; i < list.size(); i++)…
  • Find the duplicate characters in a string. — Count each character in a map (or in an int[] for a small alphabet), then report the characters with a count above 1.
  • Find the second-highest number in an array. — Scan once, tracking the highest and the second highest. When a value beats highest, the old highest becomes second.
  • Remove all whitespace from a string without using replace(). — Build a new string with a StringBuilder, appending only the characters that aren't whitespace. O(n).
  • Accept comma-separated strings, sort them, and output them concatenated. — Split on commas, trim each part, drop the empty parts, sort, then join.

Array & String Problem Solving — Interview Questions — open the lesson

  • Two Sum: return the indices of the two numbers that add up to a target. — a hash map of "value → index" (a complement lookup). One pass, O(n) time, O(n) space.
  • A string is "good" if every character that appears has the same frequency. Check it. — a frequency count, then check that all the non-zero counts are equal. O(n) time, O(1) space (26 counters).
  • Remove all occurrences of a value in place, and return the new length. — two pointers, reading and writing. The reader scans every element, and the writer copies forward only the elements we keep.
  • After each query [val, index] (add val to nums[index]), return the sum of the even numbers. — maintain a running total incrementally instead of re-summing the array after every query. O(n + q) instead of O(n·q).
  • Find all the start indices of p's anagrams in s. — a fixed-size sliding window with character counts. Slide a window of length p.length() across s, updating the counts in O(1) per step.
  • Find the length of the longest substring without repeating characters. — a variable-size sliding window. Expand to the right. When a character repeats, move left past its previous occurrence.
  • Merge two sorted linked lists into one sorted list. — a dummy head, with two pointers. Always attach the smaller node, then append whatever is left over. O(m + n) time, O(1) extra space, because we relink the existing nodes.
  • Rotate an n×n matrix 90° clockwise in place. — transpose, then reverse each row. O(n²) time, O(1) extra space.
  • Move all zeros to the end while keeping the order of the non-zero elements. — two pointers again. Compact the non-zero elements forward, then fill the remainder with zeros. O(n) time, O(1) space.
  • Given n numbers in the range [1, n], find the numbers in that range that don't appear. — in-place marking. Use the sign of nums[v - 1] to record that value v was seen. O(n) time, O(1) extra space (not counting the output).

Follow-up questions this topic invites — and their answers

Q: How should I use this list in the last week before an interview? A: Do one pass per day. Cover the answer text, say your answer out loud, then check it. Mark every question you could not answer crisply, and spend your study time only on the marked ones by opening the linked full answer. By the third pass the marked list should be short.

Q: The interviewer asks one of these basics — should I give only the one-liner? A: Lead with the one-liner, then add one concrete detail or example from your own work. At this level the follow-up usually probes the mechanism behind the basic answer, so be ready to go one layer deeper using the key points in the full lesson.

Q: Some answers here were corrected compared with common prep sheets — why? A: Several widely shared answers are outdated or wrong (for example, Java version details, removed Spring APIs, or SQL queries that miss edge cases). The full lessons call these out under "Common trap" — reading those is the fastest way to stand out from candidates who memorised the same sheets.

Previous

Revise: Core Java Fundamentals (Fresher Tier)

Next

Revise: Spring Core, Spring Boot & Spring MVC (Fresher Tier)

AI Tutor

Lesson: Revise: Collections, Threads, Java 8 & Coding (Fresher Tier)

Quick actions

AI responses can be inaccurate. Verify critical information.