LeetCode – Remove Duplicates from Sorted Array (Java)

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this in place with constant memory. For example, given input array A = [1,1,2], your function should return length = 2, and A … Read more

LeetCode – Remove Duplicates from Sorted Array II (Java)

Follow up for “Remove Duplicates“: What if duplicates are allowed at most twice? For example, given sorted array A = [1,1,1,2,2,3], your function should return length = 5, and A is now [1,1,2,2,3]. So this problem also requires in-place array manipulation. Java Solution 1 We can not change the given array’s size, so we only … Read more

LeetCode – Convert Sorted Array to Binary Search Tree (Java)

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. Java Solution A typical DFS problem using recursion. // Definition for binary tree class TreeNode { int val; TreeNode left; TreeNode right;   TreeNode(int x) { val = x; } }   public class Solution { public TreeNode … Read more

LeetCode – Convert Sorted List to Binary Search Tree (Java)

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. Thoughts If you are given an array, the problem is quite straightforward. But things get a little more complicated when you have a singly linked list instead of an array. Now you no longer have random … Read more

LeetCode – Subsets (Java)

Given a set of distinct integers, S, return all possible subsets. Note: 1) Elements in a subset must be in non-descending order. 2) The solution set must not contain duplicate subsets. For example, given S = [1,2,3], the method returns: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] Thoughts Given a set S … Read more

LeetCode – Valid Palindrome (Java)

Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. For example, “Red rum, sir, is murder” is a palindrome, while “Programcreek is awesome” is not. Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose … Read more

LeetCode – Longest Consecutive Sequence (Java)

Given an unsorted array of integers, find the length of the longest consecutive elements sequence. For example, given [100, 4, 200, 1, 3, 2], the longest consecutive elements sequence should be [1, 2, 3, 4]. Its length is 4. Your algorithm should run in O(n) complexity. Java Solution 1 Because it requires O(n) complexity, we … Read more