Leetcode Question Solution by ExpertFunda
LeetCode Solutions by ExpertFunda
Curated solutions with clean Java code, pattern explanations, and complexity analysis — built for FAANG interview success.
Two Sum
Given an array of integers nums and an integer target, return the indices of the two numbers that add up to target. Each input has exactly one solution and you may not use the same element twice.
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement)) {
return new int[]{map.get(complement), i};
}
map.put(nums[i], i);
}
throw new IllegalArgumentException("No solution");
}
Longest Substring Without Repeating Characters
Given a string s, find the length of the longest substring without repeating characters. Use a sliding window with a hash map to track the last seen index of each character.
public int lengthOfLongestSubstring(String s) {
Map<Character, Integer> map = new HashMap<>();
int left = 0, max = 0;
for (int right = 0; right < s.length(); right++) {
char c = s.charAt(right);
if (map.containsKey(c)) {
left = Math.max(map.get(c) + 1, left);
}
map.put(c, right);
max = Math.max(max, right - left + 1);
}
return max;
}
Merge Two Sorted Lists
Merge two sorted linked lists and return the merged list. Use a dummy head node and compare values iteratively, attaching the smaller node at each step.
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy = new ListNode(0);
ListNode cur = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
cur.next = l1;
l1 = l1.next;
} else {
cur.next = l2;
l2 = l2.next;
}
cur = cur.next;
}
cur.next = (l1 != null) ? l1 : l2;
return dummy.next;
}
Maximum Subarray
Find the contiguous subarray with the largest sum. Kadane’s algorithm keeps a running sum — reset to the current element whenever the running total drops below it.
public int maxSubArray(int[] nums) {
int cur = nums[0], max = nums[0];
for (int i = 1; i < nums.length; i++) {
cur = Math.max(nums[i], cur + nums[i]);
max = Math.max(max, cur);
}
return max;
}
Valid Parentheses
Given a string of brackets (, ), {, }, [, ] — determine if it is valid. Use a stack to track unmatched open brackets and a map for closing-to-opening pairs.
public boolean isValid(String s) {
Deque<Character> stack = new ArrayDeque<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
} else {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '['))
return false;
}
}
return stack.isEmpty();
}
Browse 500+ more curated solutions — use the sidebar to navigate by problem number, or explore by topic below.
View Full DSA Sheet →