Top 10 Programming Java Interview Questions and Answers

Top 10 Programming Java Interview Questions and Answers

Here are detailed, top 10 Programming Java Interview Questions and Answers challenging Java programming interview questions and answers that focus on practical, algorithmic, and data structure knowledge:

In case you need some brush up on some of the java top here is the link for Quick tutorial on Java


1. Reverse a Linked List

Question: Given a singly linked list, write a function to reverse it. You are provided with the ListNode class with integer values. Reverse the linked list in place and return the new head.

Answer:

class ListNode {
    int value;
    ListNode next;
    ListNode(int value) {
        this.value = value;
    }
}

public ListNode reverseList(ListNode head) {
    ListNode prev = null;
    while (head != null) {
        ListNode nextNode = head.next;
        head.next = prev;
        prev = head;
        head = nextNode;
    }
    return prev;
}

Explanation:

  • We initialize prev to null, which will eventually become the new head of the reversed list.
  • We iterate through each node, redirecting the next pointer of each node to point to prev.
  • After reversing all nodes, prev will point to the new head of the reversed list.

2. Find the Kth Largest Element in an Array

Question: Write a function to find the Kth largest element in an unsorted array of integers. You may assume K is always valid.

Answer:

import java.util.PriorityQueue;

public int findKthLargest(int[] nums, int k) {
    PriorityQueue<Integer> minHeap = new PriorityQueue<>();
    for (int num : nums) {
        minHeap.offer(num);
        if (minHeap.size() > k) {
            minHeap.poll();
        }
    }
    return minHeap.peek();
}

Explanation:

  • We use a min-heap (priority queue) to maintain the K largest elements.
  • We iterate through each number, adding it to the min-heap. If the heap size exceeds K, we remove the smallest element.
  • After processing all elements, the top of the min-heap contains the Kth largest element.

3. Check if a String is a Palindrome (Ignoring Case and Non-Alphanumeric Characters)

Question: Write a function that determines if a given string is a palindrome, ignoring case and non-alphanumeric characters.

Answer:

public boolean isPalindrome(String s) {
    int left = 0, right = s.length() - 1;
    while (left < right) {
        while (left < right && !Character.isLetterOrDigit(s.charAt(left))) left++;
        while (left < right && !Character.isLetterOrDigit(s.charAt(right))) right--;
        if (Character.toLowerCase(s.charAt(left)) != Character.toLowerCase(s.charAt(right))) {
            return false;
        }
        left++;
        right--;
    }
    return true;
}

Explanation:

  • We use two pointers, left and right, to traverse the string from both ends.
  • If either left or right points to a non-alphanumeric character, we skip it.
  • We compare the characters after converting to lowercase. If they differ, we return false; otherwise, we continue.
  • If the entire string is traversed without mismatches, it is a palindrome.

4. Merge Two Sorted Linked Lists

Question: Merge two sorted linked lists into one sorted list. You are given the heads of two linked lists l1 and l2. Return the merged linked list.

Answer:

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; }
}

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    ListNode dummy = new ListNode(0);
    ListNode current = dummy;
    while (l1 != null && l2 != null) {
        if (l1.val < l2.val) {
            current.next = l1;
            l1 = l1.next;
        } else {
            current.next = l2;
            l2 = l2.next;
        }
        current = current.next;
    }
    current.next = (l1 != null) ? l1 : l2;
    return dummy.next;
}

Explanation:

  • We create a dummy node to simplify the merging process.
  • We compare the current nodes of l1 and l2, adding the smaller one to our merged list.
  • Once one list is exhausted, we attach the remaining nodes of the other list to the merged list.

5. Top 10 Programming Java Interview Questions and Answers: Implement a Min Stack

Question: Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

Answer:

import java.util.Stack;

class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int x) {
        stack.push(x);
        if (minStack.isEmpty() || x <= minStack.peek()) {
            minStack.push(x);
        }
    }

    public void pop() {
        if (stack.pop().equals(minStack.peek())) {
            minStack.pop();
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        return minStack.peek();
    }
}

Explanation:

  • We use an additional minStack to keep track of the minimum values.
  • On each push, we update minStack if the new element is smaller or equal to the current minimum.
  • On pop, we update minStack if the popped element is the current minimum.

6. Find Longest Substring Without Repeating Characters

Question: Write a function to find the length of the longest substring without repeating characters.

Answer:

import java.util.HashMap;

public int lengthOfLongestSubstring(String s) {
    HashMap<Character, Integer> map = new HashMap<>();
    int maxLen = 0, left = 0;
    for (int right = 0; right < s.length(); right++) {
        char ch = s.charAt(right);
        if (map.containsKey(ch)) {
            left = Math.max(map.get(ch) + 1, left);
        }
        map.put(ch, right);
        maxLen = Math.max(maxLen, right - left + 1);
    }
    return maxLen;
}

Explanation:

  • We use a hashmap to store the last seen index of each character.
  • If a character is repeated, we move the left pointer to avoid including it in the current substring.
  • We calculate the length of the substring at each step and update maxLen if it’s the longest seen so far.

7. Detect a Cycle in a Linked List

Question: Given a linked list, determine if it contains a cycle. If it does, return true; otherwise, return false.

Answer:

public boolean hasCycle(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;
}

Explanation:

  • We use the “tortoise and hare” technique. fast moves two steps while slow moves one.
  • If there’s a cycle, fast and slow will eventually meet. If fast reaches the end, there’s no cycle.

8. Calculate the Edit Distance Between Two Strings

Question: Calculate the minimum edit distance (Levenshtein distance) between two strings s1 and s2.

Answer:

public int minDistance(String word1, String word2) {
    int m = word1.length(), n = word2.length();
    int[][] dp = new int[m + 1][n + 1];
    for (int i = 0; i <= m; i++) dp[i][0] = i;
    for (int j = 0; j <= n; j++) dp[0][j] = j;
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) {
                dp[i][j] = dp[i - 1][j - 1];
            } else {
                dp[i][j] = 1 + Math.min(dp[i - 1][j], Math.min(dp[i][j - 1], dp[i - 1][j - 1]));
            }
        }
    }
    return dp[m][n];
}

Explanation:

  • We use dynamic programming to fill a 2D array where dp[i][j] represents the edit distance between word1[0..i-1] and word2[0..j-1].
  • The final result is found in dp[m][n].

These questions demonstrate a deep understanding of Java concepts, algorithms, and data structure manipulations—perfect for challenging interviews.

External Resources

GeekforGeeks Java Interview Questions

Interview Bit Java interview Questions

Leave a Reply

Your email address will not be published. Required fields are marked *