Module: Java Interview Prep

Java Coding Questions

Java Core: Java Interview Prep -> Java Coding Questions

This section provides a collection of Java coding questions commonly asked in interviews, categorized by difficulty and topic. Solutions are provided after each question to allow for self-assessment.


Easy

1. FizzBuzz

  • Problem: Write a program that prints the numbers from 1 to n. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

  • Example: n = 15

    1
    2
    Fizz
    4
    Buzz
    Fizz
    7
    8
    Fizz
    Buzz
    11
    Fizz
    13
    14
    FizzBuzz
    
  • Solution:

    public class FizzBuzz {
        public static void main(String[] args) {
            int n = 15;
            for (int i = 1; i <= n; i++) {
                if (i % 3 == 0 && i % 5 == 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);
                }
            }
        }
    }
    

2. Check for Palindrome

  • Problem: Write a function to check if a given string is a palindrome (reads the same backward as forward). Ignore case and non-alphanumeric characters.

  • Example: "A man, a plan, a canal: Panama" is a palindrome.

  • Solution:

    public class Palindrome {
        public static boolean isPalindrome(String s) {
            String cleanString = s.replaceAll("[^a-zA-Z0-9]", "").toLowerCase();
            int left = 0;
            int right = cleanString.length() - 1;
    
            while (left < right) {
                if (cleanString.charAt(left) != cleanString.charAt(right)) {
                    return false;
                }
                left++;
                right--;
            }
            return true;
        }
    
        public static void main(String[] args) {
            String str = "A man, a plan, a canal: Panama";
            System.out.println(isPalindrome(str)); // Output: true
        }
    }
    

3. Find the Maximum Element in an Array

  • Problem: Write a function to find the maximum element in an integer array.

  • Example: [1, 5, 2, 8, 3] -> 8

  • Solution:

    public class MaxElement {
        public static int findMax(int[] arr) {
            if (arr == null || arr.length == 0) {
                throw new IllegalArgumentException("Array cannot be null or empty");
            }
            int max = arr[0];
            for (int i = 1; i < arr.length; i++) {
                if (arr[i] > max) {
                    max = arr[i];
                }
            }
            return max;
        }
    
        public static void main(String[] args) {
            int[] arr = {1, 5, 2, 8, 3};
            System.out.println(findMax(arr)); // Output: 8
        }
    }
    

Medium

4. Reverse a Linked List

  • Problem: Write a function to reverse a singly linked list.

  • Example: 1 -> 2 -> 3 -> 4 -> 5 becomes 5 -> 4 -> 3 -> 2 -> 1

  • Solution:

    class ListNode {
        int val;
        ListNode next;
        ListNode(int val) { this.val = val; }
    }
    
    public class ReverseLinkedList {
        public ListNode reverseList(ListNode head) {
            ListNode prev = null;
            ListNode current = head;
            ListNode next = null;
            while (current != null) {
                next = current.next;
                current.next = prev;
                prev = current;
                current = next;
            }
            return prev;
        }
    }
    

5. Implement Binary Search

  • Problem: Implement the binary search algorithm to find the index of a target value in a sorted array.

  • Example: [2, 5, 7, 8, 11, 12], target = 12 -> 5

  • Solution:

    public class BinarySearch {
        public static int binarySearch(int[] arr, int target) {
            int left = 0;
            int right = arr.length - 1;
    
            while (left <= right) {
                int mid = left + (right - left) / 2; // Prevent potential overflow
    
                if (arr[mid] == target) {
                    return mid;
                } else if (arr[mid] < target) {
                    left = mid + 1;
                } else {
                    right = mid - 1;
                }
            }
    
            return -1; // Target not found
        }
    
        public static void main(String[] args) {
            int[] arr = {2, 5, 7, 8, 11, 12};
            int target = 12;
            System.out.println(binarySearch(arr, target)); // Output: 5
        }
    }
    

6. First Non-Repeating Character in a String

  • Problem: Given a string, find the first non-repeating character in it and return its index. If it does not exist, return -1.

  • Example: leetcode -> 0 (l is the first non-repeating character)

  • Solution:

    import java.util.HashMap;
    
    public class FirstUniqueChar {
        public static int firstUniqChar(String s) {
            HashMap<Character, Integer> charCounts = new HashMap<>();
    
            // Count character frequencies
            for (int i = 0; i < s.length(); i++) {
                char c = s.charAt(i);
                charCounts.put(c, charCounts.getOrDefault(c, 0) + 1);
            }
    
            // Find the first character with a count of 1
            for (int i = 0; i < s.length(); i++) {
                if (charCounts.get(s.charAt(i)) == 1) {
                    return i;
                }
            }
    
            return -1;
        }
    
        public static void main(String[] args) {
            String s = "leetcode";
            System.out.println(firstUniqChar(s)); // Output: 0
        }
    }
    

Hard

7. Merge K Sorted Lists

  • Problem: You are given an array of k sorted linked lists. Merge them into one sorted linked list.
  • Solution: (Requires understanding of PriorityQueue and Linked List manipulation) - Implementation is more complex and often involves using a PriorityQueue to efficiently track the smallest elements across all lists.

8. Implement a LRU Cache

  • Problem: Design and implement a Least Recently Used (LRU) cache. It should support the following operations: get(key) and put(key, value).
  • Solution: (Requires understanding of HashMap and Doubly Linked List) - Implementation involves using a HashMap to store key-value pairs and a Doubly Linked List to maintain the order of access.

9. Word Break

  • Problem: Given a string s and a dictionary of strings wordDict, return true if s can be segmented into a space-separated sequence of one or more dictionary words.
  • Solution: (Requires understanding of Dynamic Programming) - Implementation involves building a boolean array dp where dp[i] is true if the substring s[0...i] can be segmented.

Note: These are just a few examples. Interviewers may ask variations of these questions or entirely different questions. Focus on understanding the underlying concepts and being able to explain your thought process. Practice coding regularly to improve your problem-solving skills. Consider using platforms like LeetCode, HackerRank, and Codewars for more practice problems.