LeetCode – Longest Substring Without Repeating Characters (Java)

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for “abcabcbb” is “abc”, which the length is 3. For “bbbbb” the longest substring is “b”, with the length of 1. Analysis The basic idea to solve this problem is using an extra data … Read more

LeetCode – Permutations II (Java)

Given a collection of numbers that might contain duplicates, return all possible unique permutations. For example, [1,1,2] have the following unique permutations: [1,1,2], [1,2,1], and [2,1,1]. Java Solution 1 Based on Permutation, we can add a set to track if an element is duplicate and no need to swap. public List<List<Integer>> permuteUnique(int[] nums) { List<List<Integer>> … Read more

LeetCode – Merge k Sorted Lists (Java)

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity. Analysis The simplest solution is using PriorityQueue. The elements of the priority queue are ordered according to their natural ordering, or by a comparator provided at the construction time (in this case). Java Solution public ListNode mergeKLists(ListNode[] lists) … Read more

LeetCode – Permutation Sequence (Java)

The set [1,2,3,…,n] contains a total of n! unique permutations. By listing and labeling all of the permutations in order, We get the following sequence (ie, for n = 3): “123” “132” “213” “231” “312” “321” Given n and k, return the kth permutation sequence. (Note: Given n will be between 1 and 9 inclusive.) … Read more

LeetCode – Minimum Depth of Binary Tree (Java)

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. Thoughts LinkedList is a queue in Java. The add() and remove() methods are used to manipulate the queue. Java Solution /** * Definition for binary … Read more

LeetCode – Maximum Subarray (Java)

Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [−2,1,−3,4,−1,2,1,−5,4], the contiguous subarray [4,−1,2,1] has the largest sum = 6. Java Solution – DP The easiest way to formulate the solution of this problem is using DP. Let f(n) be the maximum … Read more

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