# Title Difficulty Train of thought
1 Two Sum Easy return indices of the two numbers in an array such that they add up to target. Can we use additional space somehow? Like maybe a hash map to speed up the search?
2 Add Two Numbers Medium two non-empty linked lists stored in reverse order representing two non-negative integers.
3 Longest Substring Without Repeating Characters Medium The reason is that if $s[j]$ have a duplicate in the range $[i, j)$ with index $j’$, we don’t need to increase $i$ little by little. We can skip all the elements in the range $[i, j’]$ and let $i$ to be $j’ + 1$ directly.
4 Median of Two Sorted Arrays Hard
5 Longest Palindromic Substring Medium This yields a straight forward DP solution, which we first initialize the one and two letters palindromes, and work our way up finding all three letters palindromes, and so on.
10 Regular Expression Matching Hard
11 Container With Most Water Medium
15 3Sum Medium
17 Letter Combinations of a Phone Number Medium
19 Remove Nth Node From End of List Medium
20 Valid Parentheses Easy
21 Merge Two Sorted Lists Easy
22 Generate Parentheses Medium
23 Merge k Sorted Lists Hard
32 Longest Valid Parentheses Hard
33 Search in Rotated Sorted Array Medium
34 Find First and Last Position of Element in Sorted Array Medium
39 Combination Sum Medium
41 First Missing Positive Hard
42 Trapping Rain Water Hard
45 Jump Game II Hard
46 Permutations Medium
48 Rotate Image Medium
49 Group Anagrams Medium
53 Maximum Subarray Easy
55 Jump Game Medium
56 Merge Intervals Medium
62 Unique Paths Medium
64 Minimum Path Sum Medium
70 Climbing Stairs Easy
72 Edit Distance Hard
75 Sort Colors Medium
76 Minimum Window Substring Hard
78 Subsets Medium
79 Word Search Medium
84 Largest Rectangle in Histogram Hard
85 Maximal Rectangle Hard
94 Binary Tree Inorder Traversal Medium
96 Unique Binary Search Trees Medium
98 Validate Binary Search Tree Medium
101 Symmetric Tree Easy
102 Binary Tree Level Order Traversal Medium
104 Maximum Depth of Binary Tree Easy
105 Construct Binary Tree from Preorder and Inorder Traversal Medium
114 Flatten Binary Tree to Linked List Medium
121 Best Time to Buy and Sell Stock Easy
124 Binary Tree Maximum Path Sum Hard
128 Longest Consecutive Sequence Hard
136 Single Number Easy
138 Copy List with Random Pointer Medium
139 Word Break Medium
141 Linked List Cycle Easy
142 Linked List Cycle II Medium
146 LRU Cache Medium
148 Sort List Medium
152 Maximum Product Subarray Medium
155 Min Stack Easy
160 Intersection of Two Linked Lists Easy
169 Majority Element Easy
198 House Robber Medium
199 Binary Tree Right Side View Medium
200 Number of Islands Medium
206 Reverse Linked List Easy
207 Course Schedule Medium
208 Implement Trie (Prefix Tree) Medium
215 Kth Largest Element in an Array Medium
221 Maximal Square Medium
226 Invert Binary Tree Easy
230 Kth Smallest Element in a BST Medium
234 Palindrome Linked List Easy
236 Lowest Common Ancestor of a Binary Tree Medium
238 Product of Array Except Self Medium
239 Sliding Window Maximum Hard
240 Search a 2D Matrix II Medium
253 Meeting Rooms II Medium
279 Perfect Squares Medium
283 Move Zeroes Easy
287 Find the Duplicate Number Medium
295 Find Median from Data Stream Hard
297 Serialize and Deserialize Binary Tree Hard
300 Longest Increasing Subsequence Medium
322 Coin Change Medium
337 House Robber III Medium
338 Counting Bits Medium
347 Top K Frequent Elements Medium
394 Decode String Medium
406 Queue Reconstruction by Height Medium
416 Partition Equal Subset Sum Medium
437 Path Sum III Medium
438 Find All Anagrams in a String Medium
448 Find All Numbers Disappeared in an Array Easy
494 Target Sum Medium
543 Diameter of Binary Tree Easy
560 Subarray Sum Equals K Medium
581 Shortest Unsorted Continuous Subarray Medium
617 Merge Two Binary Trees Easy
621 Task Scheduler Medium
647 Palindromic Substrings Medium
739 Daily Temperatures Medium
763 Partition Labels Medium

1 Two Sum

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        d = {}
        for i, n in enumerate(nums):
            complement = target - n
            if complement in d:
                return [d[complement], i]
            d[n] = i

2 Add Two Numbers

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy_head = ListNode(0)
        curr = dummy_head
        carry = 0
        while (l1 or l2 or carry):
            if l1:
                carry += l1.val
                l1 = l1.next
            if l2:
                carry += l2.val
                l2 = l2.next
            carry, out = divmod(carry, 10)
            
            curr.next = ListNode(out)
            curr = curr.next

        return dummy_head.next

3 Longest Substring Without Repeating Characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        n = len(s)
        ans = 0
        # mp stores the current index of a character
        mp = {}

        i = 0
        # try to extend the range [i, j]
        for j in range(n):
            if s[j] in mp:
                i = max(mp[s[j]], i)

            ans = max(ans, j - i + 1)
            mp[s[j]] = j + 1

        return ans

4 Median of Two Sorted Arrays

5 Longest Palindromic Substring

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public String longestPalindrome(String s) {
    if (s == null || s.length() < 1) return "";
    int start = 0, end = 0;
    for (int i = 0; i < s.length(); i++) {
        int len1 = expandAroundCenter(s, i, i);
        int len2 = expandAroundCenter(s, i, i + 1);
        int len = Math.max(len1, len2);
        if (len > end - start) {
            start = i - (len - 1) / 2;
            end = i + len / 2;
        }
    }
    return s.substring(start, end + 1);
}

private int expandAroundCenter(String s, int left, int right) {
    int L = left, R = right;
    while (L >= 0 && R < s.length() && s.charAt(L) == s.charAt(R)) {
        L--;
        R++;
    }
    return R - L - 1;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16

class Solution(object):
    def longestPalindrome(self, s):
        """
        :type s: str
        :rtype: str
        """
        res = ""
        for i in range(len(s)):
            res = max(self.helper(s,i,i), self.helper(s,i,i+1), res, key=len)
        return res
       
    def helper(self,s,l,r):
        while 0<=l and r < len(s) and s[l]==s[r]:
                l-=1; r+=1
        return s[l+1:r]

10 Regular Expression Matching

11 Container With Most Water

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
    def maxArea(self, height):
        max_area, beg, end = 0, 0, len(height) - 1
        while beg < end:
            max_area = max(max_area, min(height[beg], height[end]) * (end - beg))
            if height[beg] < height[end]:
                beg += 1
            else:
                end -= 1
        return max_area

15 3Sum

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
def threeSum(self, nums):
    res = []
    nums.sort()
    for i in xrange(len(nums)-2):
        if i > 0 and nums[i] == nums[i-1]:
            continue
        l, r = i+1, len(nums)-1
        while l < r:
            s = nums[i] + nums[l] + nums[r]
            if s < 0:
                l +=1 
            elif s > 0:
                r -= 1
            else:
                res.append((nums[i], nums[l], nums[r]))
                while l < r and nums[l] == nums[l+1]:
                    l += 1
                while l < r and nums[r] == nums[r-1]:
                    r -= 1
                l += 1; r -= 1
    return res
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        N, result = len(nums), []
        for i in range(N):
            if i > 0 and nums[i] == nums[i-1]:
                continue
            target = nums[i]*-1
            s,e = i+1, N-1
            while s<e:
                if nums[s]+nums[e] == target:
                    result.append([nums[i], nums[s], nums[e]])
                    s = s+1
                    while s<e and nums[s] == nums[s-1]:
                        s = s+1
                elif nums[s] + nums[e] < target:
                    s = s+1
                else:
                    e = e-1
        return result

17 Letter Combinations of a Phone Number

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution:
    def letterCombinations(self, digits):
        """
        :type digits: str
        :rtype: List[str]
        """
        phone = {'2': ['a', 'b', 'c'],
                 '3': ['d', 'e', 'f'],
                 '4': ['g', 'h', 'i'],
                 '5': ['j', 'k', 'l'],
                 '6': ['m', 'n', 'o'],
                 '7': ['p', 'q', 'r', 's'],
                 '8': ['t', 'u', 'v'],
                 '9': ['w', 'x', 'y', 'z']}
                
        def backtrack(combination, next_digits):
            # if there is no more digits to check
            if len(next_digits) == 0:
                # the combination is done
                output.append(combination)
            # if there are still digits to check
            else:
                # iterate over all letters which map 
                # the next available digit
                for letter in phone[next_digits[0]]:
                    # append the current letter to the combination
                    # and proceed to the next digits
                    backtrack(combination + letter, next_digits[1:])
                    
        output = []
        if digits:
            backtrack("", digits)
        return output

19 Remove Nth Node From End of List

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
def removeNthFromEnd(self, head, n):
    dummy = ListNode(0)
    dummy.next = head
    fast = slow = dummy
    for _ in xrange(n):
        fast = fast.next
    while fast and fast.next:
        fast = fast.next
        slow = slow.next
    slow.next = slow.next.next
    return dummy.next

20 Valid Parentheses

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution(object):
    def isValid(self, s):
        """
        :type s: str
        :rtype: bool
        """

        # The stack to keep track of opening brackets.
        stack = []

        # Hash map for keeping track of mappings. This keeps the code very clean.
        # Also makes adding more types of parenthesis easier
        mapping = {")": "(", "}": "{", "]": "["}

        # For every bracket in the expression.
        for char in s:

            # If the character is an closing bracket
            if char in mapping:

                # Pop the topmost element from the stack, if it is non empty
                # Otherwise assign a dummy value of '#' to the top_element variable
                top_element = stack.pop() if stack else '#'

                # The mapping for the opening bracket in our hash and the top
                # element of the stack don't match, return False
                if mapping[char] != top_element:
                    return False
            else:
                # We have an opening bracket, simply push it onto the stack.
                stack.append(char)

        # In the end, if the stack is empty, then we have a valid expression.
        # The stack won't be empty for cases like ((()
        return not stack

21 Merge Two Sorted Lists

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# iteratively
def mergeTwoLists1(self, l1, l2):
    dummy = cur = ListNode(0)
    while l1 and l2:
        if l1.val < l2.val:
            cur.next = l1
            l1 = l1.next
        else:
            cur.next = l2
            l2 = l2.next
        cur = cur.next
    cur.next = l1 or l2
    return dummy.next
    
# recursively    
def mergeTwoLists2(self, l1, l2):
    if not l1 or not l2:
        return l1 or l2
    if l1.val < l2.val:
        l1.next = self.mergeTwoLists(l1.next, l2)
        return l1
    else:
        l2.next = self.mergeTwoLists(l1, l2.next)
        return l2

22 Generate Parentheses

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution(object):
    def generateParenthesis(self, N):
        ans = []
        def backtrack(S = '', left = 0, right = 0):
            if len(S) == 2 * N:
                ans.append(S)
                return
            if left < N:
                backtrack(S+'(', left+1, right)
            if right < left:
                backtrack(S+')', left, right+1)

        backtrack()
        return ans

23 Merge k Sorted Lists

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution(object):
    def mergeKLists(self, lists):
        if not lists:
            return None
        if len(lists) == 1:
            return lists[0]
        mid = len(lists) // 2
        l, r = self.mergeKLists(lists[:mid]), self.mergeKLists(lists[mid:])
        return self.merge(l, r)
    
    def merge(self, l, r):
        dummy = p = ListNode()
        while l and r:
            if l.val < r.val:
                p.next = l
                l = l.next
            else:
                p.next = r
                r = r.next
            p = p.next
        p.next = l or r
        return dummy.next

32 Longest Valid Parentheses

33 Search in Rotated Sorted Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
    # @param {integer[]} numss
    # @param {integer} target
    # @return {integer}
    def search(self, nums, target):
        if not nums:
            return -1

        low, high = 0, len(nums) - 1

        while low <= high:
            mid = (low + high) / 2
            if target == nums[mid]:
                return mid

            if nums[low] <= nums[mid]:
                if nums[low] <= target <= nums[mid]:
                    high = mid - 1
                else:
                    low = mid + 1
            else:
                if nums[mid] <= target <= nums[high]:
                    low = mid + 1
                else:
                    high = mid - 1

        return -1

34 Find First and Last Position of Element in Sorted Array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
    def searchRange(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        if not nums:
            return [-1, -1]

        def bisect_left(nums, target):
            l, r = 0, len(nums) - 1
            while l < r:
                m = (l + r) // 2
                if nums[m] < target:
                    l = m + 1
                else:
                    r = m
            return l if nums[l] == target else -1

        def bisect_right(nums, target):
            l, r = 0, len(nums) - 1
            while l < r:
                m = (l + r) // 2 + 1
                if nums[m] > target:
                    r = m - 1
                else:
                    l = m
            return l if nums[l] == target else -1

        return [bisect_left(nums, target), bisect_right(nums, target)]

39 Combination Sum

41 First Missing Positive

42 Trapping Rain Water

45 Jump Game II

46 Permutations

48 Rotate Image

49 Group Anagrams

53 Maximum Subarray

55 Jump Game

56 Merge Intervals

62 Unique Paths

64 Minimum Path Sum

70 Climbing Stairs

72 Edit Distance

75 Sort Colors

76 Minimum Window Substring

78 Subsets

84 Largest Rectangle in Histogram

85 Maximal Rectangle

94 Binary Tree Inorder Traversal

96 Unique Binary Search Trees

98 Validate Binary Search Tree

101 Symmetric Tree

102 Binary Tree Level Order Traversal

104 Maximum Depth of Binary Tree

105 Construct Binary Tree from Preorder and Inorder Traversal

114 Flatten Binary Tree to Linked List

121 Best Time to Buy and Sell Stock

124 Binary Tree Maximum Path Sum

128 Longest Consecutive Sequence

136 Single Number

138 Copy List with Random Pointer

139 Word Break

141 Linked List Cycle

142 Linked List Cycle II

146 LRU Cache

148 Sort List

152 Maximum Product Subarray

155 Min Stack

160 Intersection of Two Linked Lists

169 Majority Element

198 House Robber

199 Binary Tree Right Side View

200 Number of Islands

206 Reverse Linked List

207 Course Schedule

208 Implement Trie (Prefix Tree)

215 Kth Largest Element in an Array

221 Maximal Square

226 Invert Binary Tree

230 Kth Smallest Element in a BST

234 Palindrome Linked List

236 Lowest Common Ancestor of a Binary Tree

238 Product of Array Except Self

239 Sliding Window Maximum

240 Search a 2D Matrix II

253 Meeting Rooms II

279 Perfect Squares

283 Move Zeroes

287 Find the Duplicate Number

295 Find Median from Data Stream

297 Serialize and Deserialize Binary Tree

300 Longest Increasing Subsequence

322 Coin Change

337 House Robber III

338 Counting Bits

347 Top K Frequent Elements

394 Decode String

406 Queue Reconstruction by Height

416 Partition Equal Subset Sum

437 Path Sum III

438 Find All Anagrams in a String

448 Find All Numbers Disappeared in an Array

494 Target Sum

543 Diameter of Binary Tree

560 Subarray Sum Equals K

581 Shortest Unsorted Continuous Subarray

617 Merge Two Binary Trees

621 Task Scheduler

647 Palindromic Substrings

739 Daily Temperatures

763 Partition Labels