25 Java coding interview problems and their solutions

 This blog post presents 25 Java coding interview problems and their solutions, specifically designed for developers with 5+ years of experience. These questions cover data structures, algorithms, concurrency, design patterns, and practical Java skills that go beyond basic knowledge.


1. Reverse a Linked List

ListNode reverse(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode next = head.next;
        head.next = prev;
        prev = head;
        head = next;
    }
    return prev;
}

2. Detect Loop in a Linked List

boolean hasLoop(ListNode head) {
    ListNode slow = head, fast = head;
    while (fast != null && fast.next != null) {
        slow = slow.next;
        fast = fast.next.next;
        if (slow == fast) return true;
    }
    return false;
}

3. Find the Second Largest Number in an Array

int secondLargest(int[] arr) {
    int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
    for (int num : arr) {
        if (num > first) {
            second = first;
            first = num;
        } else if (num > second && num != first) {
            second = num;
        }
    }
    return second;
}

4. Count Occurrences of Each Character in a String

Map<Character, Long> countChars(String input) {
    return input.chars()
                .mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(c -> c, Collectors.counting()));
}

5. Check if Two Strings are Anagrams

boolean isAnagram(String s1, String s2) {
    char[] a1 = s1.toCharArray();
    char[] a2 = s2.toCharArray();
    Arrays.sort(a1);
    Arrays.sort(a2);
    return Arrays.equals(a1, a2);
}

6. Remove Duplicates from a List

List<Integer> removeDuplicates(List<Integer> list) {
    return new ArrayList<>(new HashSet<>(list));
}

7. Merge Two Sorted Arrays

int[] mergeSorted(int[] a, int[] b) {
    int[] res = new int[a.length + b.length];
    int i=0, j=0, k=0;
    while(i<a.length && j<b.length) {
        res[k++] = (a[i] < b[j]) ? a[i++] : b[j++];
    }
    while(i<a.length) res[k++] = a[i++];
    while(j<b.length) res[k++] = b[j++];
    return res;
}

8. FizzBuzz (Classic Interview Favorite)

void fizzBuzz(int n) {
    for (int i = 1; i <= n; i++) {
        if (i % 15 == 0) System.out.println("FizzBuzz");
        else if (i % 3 == 0) System.out.println("Fizz");
        else if (i % 5 == 0) System.out.println("Buzz");
        else System.out.println(i);
    }
}

9. Check for Palindrome

boolean isPalindrome(String s) {
    int l = 0, r = s.length() - 1;
    while (l < r) {
        if (s.charAt(l++) != s.charAt(r--)) return false;
    }
    return true;
}

10. Thread-Safe Singleton Design Pattern

class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized(Singleton.class) {
                if (instance == null)
                    instance = new Singleton();
            }
        }
        return instance;
    }
}

11. Producer-Consumer Using BlockingQueue

BlockingQueue<Integer> queue = new LinkedBlockingQueue<>();

Runnable producer = () -> {
    for (int i = 0; i < 10; i++) {
        queue.put(i);
    }
};

Runnable consumer = () -> {
    while (true) {
        int val = queue.take();
        System.out.println(val);
    }
};

12. Create a Deadlock (for Testing Purposes)

synchronized(lock1) {
    Thread.sleep(100);
    synchronized(lock2) {
        // Deadlock-prone work
    }
}

13. Use Optional to Avoid Null Checks

Optional.ofNullable(obj)
        .map(Object::toString)
        .orElse("default");

14. Find the Missing Number in an Array

int findMissing(int[] arr, int n) {
    int total = n * (n + 1) / 2;
    int sum = Arrays.stream(arr).sum();
    return total - sum;
}

15. Sort Map by Values

map.entrySet().stream()
   .sorted(Map.Entry.comparingByValue())
   .forEach(System.out::println);

16. Implement LRU Cache

Use LinkedHashMap with accessOrder=true.

17. Custom Sorting Using Comparator

list.sort((a, b) -> b.getAge() - a.getAge());

18. Count Word Frequency in a Sentence

Map<String, Long> freq = Arrays.stream(sentence.split(" "))
    .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

19. Convert List to Map

Map<Integer, String> map = list.stream()
    .collect(Collectors.toMap(User::getId, User::getName));

20. FlatMap vs Map Example

List<String> all = list.stream()
    .flatMap(str -> Arrays.stream(str.split(" ")))
    .collect(Collectors.toList());

21. Multi-threaded Counter with AtomicInteger

AtomicInteger count = new AtomicInteger(0);
Runnable task = () -> count.incrementAndGet();

22. Group by Field in List of Objects

Map<String, List<Employee>> grouped =
    employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));

23. Convert List to int[]

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

24. Read File into List of Strings

List<String> lines = Files.readAllLines(Paths.get("file.txt"));

25. Use ExecutorService to Run Threads

ExecutorService executor = Executors.newFixedThreadPool(3);
executor.submit(() -> System.out.println("Task"));
executor.shutdown();


Comments