Got it. Here are a few in-depth Java code-level questions to challenge a senior software engineer:
1. Implement a LRU Cache
Write a class that implements a Least Recently Used (LRU) cache:
import java.util.*;
class LRUCache<K, V> {
private final int capacity;
private final Map<K, V> map;
private final LinkedList<K> list;
public LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.list = new LinkedList<>();
}
public V get(K key) {
if (!map.containsKey(key)) {
return null;
}
list.remove(key);
list.addFirst(key);
return map.get(key);
}
public void put(K key, V value) {
if (map.containsKey(key)) {
list.remove(key);
} else if (map.size() == capacity) {
K last = list.removeLast();
map.remove(last);
}
list.addFirst(key);
map.put(key, value);
}
}
2. Find the Longest Substring Without Repeating Characters
Write a method to find the length of the longest substring without repeating characters in a given string.
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int maxLen = 0, start = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (map.containsKey(c)) {
start = Math.max(map.get(c) + 1, start);
}
map.put(c, i);
maxLen = Math.max(maxLen, i - start + 1);
}
return maxLen;
}
3. Detect a Cycle in a Linked List
Write a function to detect if a cycle exists in a linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
4. Implement a Thread-Safe Singleton Pattern
Write a thread-safe implementation of the Singleton pattern.
public class Singleton {
private static volatile Singleton instance = null;
private Singleton() {
// Private constructor to prevent instantiation
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
