Easy

Solution 1: HashMap

  1. put all numbers x into HashMap O(n)
  2. traversal array to find if y in the HashMap (y=tragetSum-x) O(n)

Time complexity: O(n)

Space complexity: O(n)

Solution 2: Two pointers

  1. Sort the arrray. O(nLogn)
  2. use Left and Right pointer shrinking the sum to targetSum. O(n)

Time complexity: O(n Log n)  Space complexity: O(1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// JavaScript: O(nlog(n)) | O(1) space 
function twoNumberSum(array, targetSum) 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Program 
Given a array arr and a sequence s, check if s is subsequence of arr.

Leetcode Problem

Solution: Two Pointers

  1. Pointer a in array and one pointer b in sequence,
  2. if arr[a]!=sequence[b] a++
  3. else a++ & b++
  4. check if b reach end of length of sequence.

Time complexity: O(n)   n=array length

Space complexity: O(1)

1
2
3
4
5
6
7
8
9
function isValidSubsequence(array, sequence) 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Program 

Solution 2: One Pointer in traversal array

1
2
3
4
5
6
7
8
9
  // O(n) time | O(1) space - where n is the length of the array
  function isValidSubsequence(array, sequence) 

 

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Program 

Given BST and an Integer Value, find the closest value to the target value(12).

Solution: Binary search(while loop/recursion)

  1. Two Integer target and closest
  2. compare target and cur.value to decide go cur.left ot cur.right

Time complexity:O(log(n)) Space complexity: O(1)

While Loop:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
 // Average: O(log(n)) time | O(1) space
 // Worst: O(n) time | O(1) space
 function findClosestValueInBst(tree, target) 

 function findClosestValueInBstHelper(tree, target, closest) 

 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
class Program 

Recursion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// Average: O(log(n)) time | O(log(n)) space
// Worst: O(n) time | O(n) space
function findClosestValueInBst(tree, target) 

function findClosestValueInBstHelper(tree, target, closest) 

 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
class Program 
Path Sum

Find all brach sum in the tree added into a list

Solution: Recursion

 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 BinaryTree 
// O(n) time | O(n) space - where n is the number of nodes in the Binay tree
function branchSums(root) 

function calculateBranchSums(node, runningSum, sums) 

 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
class Program 
Find total depth of each node in Binary Tree.
104. Maximum Depth of Binary Tree

Solution: Recursion, Stack

Recursion:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
  //Average case: when the tree is balanced
  // O(n) time | O(h) space - where n is the number of nodes in
  // the Binary Tree and h is the height of the Binary Tree
  function nodeDepths(root, depth = 0) 
  // This is the class of the input binary tree.

  class BinaryTree 

 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
class Program 

Stack:

 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
36
// Average case: when the tree is balanced
// O(n) time | O(h) space - where n is the number of nodes in
// the Binary Tree and h is the height of the Binary Tree
function nodeDepths(root) 

// This is the class of the input binary tree.
class BinaryTree 

 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
36
37
38
39
40
41
42
class Program 

Solution: Recursion

Call  and go Children Node before resolve itself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Node 

 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
class Program 

Data Structure:

  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
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
class Node 

class Program {
    static class DoublyLinkedList 
Formula :

  1. when n>2   Fib(n)=Fib(n-1)+Fib(n-2)
  2. if n=2 return 1
  3. if n=1 return 0

Solution to get Fib(n): recursion , Iteration (better)

1. recursion

Time complexity: O(n)            Space Complexity: O(n)

When we want to Fib(n), use recursion function, and memorized calculated Fib(i)  in HashTable.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// O(2^n) time | O(n) space
function getNthFib(n) 

Java Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Program 

2.iteration (better)

Example: Fib(4)

  • initial fixed array [0,1]
  • Fib(2)=0+1=1    update array[1,1]   (move index 1 to 0, Fib(2) = index 1)
  • Fib(3)=1+1=2    update array[1,2]
  • Fib(4)=1+2=3    return Fib(4)

Time complexity: O(n)             Space complexity: O(1)


JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// O(n) time | O(n) space
function getNthFib(n, memoize = ) 

Java Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Program 

While Loop

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// O(n) time | O(1) space
function getNthFib(n) 

Product Sum is sum of all the elements in the array.

 Recursion:

  • [7,-1]   sum=6, m(depth)=2
  • [-13,8]   sum=5, m=3
  • Time = O(N), Space = O(D)   D=depth of the array  there is 3.

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function productSum(array, multiplier = 1) 

Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Program 

Give a sorted array, use Binary Search to find a value val in O(LogN) time complexity, and return its index.

Solution: Left Pointer and Right Pointer

  • while(left<=right)
  • index middle=start + ( end – start )/2

JavaScript-Recommend(while loop):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
// O(log(n)) time | O(1) space
function binarySearch(array, target) 

function binarySearchHelper(array, target, left, right) 

 

JavaScript(Recursion):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// O(log(n)) time | O(log(n)) space
function binarySearch(array, target) 

function binarySearchHelper(array, target, left, right) 

Java(Recursion):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class Program 

Problem: Give a unsorted array, and return three largest numbers.

Solution: Heap/Fixed Length of array

Fixed Length of array:

  • initial  int[] res =
  • traversal given array to keep three largest in res.

JavaScript:

 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
// O(n) time | O(1) space
function findThreeLargestNumbers(array) 

function updateLargest(threeLargest, num) 

function shiftAndUpdate(array, num, idx) 

 

Java:

 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
class Program 

Solution:  Time: O(n2)     Space:O(1)

  • First for loop can push the largest one to the index arr.length-1
  • Second round loop can push the 2nd Largest one to the index arr.length-2
  • So on so forth and Loop N times.

Example:
First Pass:
5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1.
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm does not swap them.

Second Pass:
1 4 2 5 8 ) –> ( 1 4 2 5 8 )
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 )
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.

Third Pass:
1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 )

Java code:

 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
class Program 
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater elements one position up to make space for the swapped element.

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Best: O(n) time | O(1) space
// Average: O(n^2) time | O(1) space // Worst: O(n^2) time | O(1) space 
function insertionSort(array) 

function swap(i, j, array) 

 

Java code:

 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 Program 

Algorithm:

The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.

1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.

In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.

PS: Bubble sort , insertion sort and selection sort may not most efficient sorting algorithm, but they are easy to implement.
Time: O(n)   Space: O(1)

 

 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
class Program 

Solution: Two Pointers

  1. Left Pointer=0, Right Pointer= arr.length-1
  2. if ( arr[Left]=arr[Right])  keep moving to the middle, else return false

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// O(n) time | O(1) space
function isPalindrome(string) 

 
Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Program 
Given String "zhy" and integer value 2. Shifted by 2 = "zab"

A:65   Z:90

a:97   z:122

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
// O(n) time | O(n) space
function caesarCipherEncryptor(string, key) 

function getNewLetter(letter, key, alphabet) 

 

Java code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Program 

Middle
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. Notice that the solution set must not contain duplicate triplets.

Solution:  Two Pointers | O(n^2) time | O(n) space

  1. Sort the array in ascending order.
  2. for loop to traverse array,  initial Left=i+1, Right=arr.length-1
  3. curSum = arr[i] + arr[left] + arr[right]
  4. while(left
  5. if (curSum>target) , right–, else left++
  6. if(curSum==target)  add to result List, then right– && left++

JavaScript Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
// O(n^2) time | O(n) space
function threeNumberSum(array, targetSum) 

Java Code:

 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
class Program 
Given two arrays of integers, compute the pair of values (one value in each array) with the smallest (non-negative) difference. Return the difference.

Examples :
1
2
3
4
Input : 
A[] =  
B[] =  
Output : 3 That is, the pair (11, 8)

Solution: Two Pointers || Time: O( N log( N ) + M log( M )) | Space: O( 1 )

  1. Sort two array A, B with length N, M in ascending order.
  2. while ( ismallest to get min difference.
  3. Start two pointers i, j from A[ 0 ], B[ 0 ], then compare pointers
  4. if A[ i ] < B[ j ], i++, else j++
  5. if A[ i ] = B[ j ]  return pair ( A[ i ], B[ j ] )

JavaScript Code:

 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
// O(nlog(n) + mlog(m)) time | O(1) space
function smallestDifference(arrayOne, arrayTwo) 

Java Code:

 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
class Program 
Given an array and Integer toMove, move all the toMoves  in array to the end in O(1) space complexity.

Example:

1
2
The original list is : ['3', '5', '7', '9', '11'] ToMove : 5
The modified element moved list is : ['3', '7', '9', '11', '5']

Solution: Two Pointers   || Time : O ( N ) | Space : O ( 1 )

  1. i = 0, j = arr.length – 1
  2. while( i < j )
  3.      while( i < j and arr [ j ] = toMove)  then j–
  4.            if ( arr[ i ]==toMove ) then swap ( arr[ i ] , arr[ j ] )  ,  i++
  5. return array

JavaScript Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// O(n) time | O(1) space - where n is the length of the array 
function moveElementToEnd(array, toMove) 

function swap(i, j, array) 

Java Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Program 
Give an array, return true or false if it's Monotonic Array. Monotonic  can be entirely Non-Decreasing or Non-Increasing.

Tricky: Array may contain duplicate Integer.

896. Monotonic Array

Solution:  || Time : O ( N ) | Space : O ( 1 )

  1. determine the direction ( downward or upward trending )

JavaScript Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// O(n) time | O(1) space - n = length of the array 
function isMonotonic(array) 

Java Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Program 
Given an m x n matrix, return all elements of the matrix in spiral order.  N: total number of vertices

54. Spiral Matrix

54. Spiral Matrix

Solution:  Iteration  || Time : O ( N ) | Space : O ( 1 ) / Recursion   || Time : O ( N ) | Space : O ( N )

  1. initial four pointers:
  2. startColomn = 0, endColomn = arr[0].length - 1, startRow = 0, endRow = arr.length-1
  3. use iterative method (optimal) or recursive method to traverse 2D array.

Shrink to calculate inner perimeter:

Iterative method:

JavaScript Code:

 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
// O(n) time | O(n) space - where n is the total number of elements in the array 
function spiralTraverse(array) 

Java Code:

 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
class Program 

Recursive method:

JavaScript Code:

 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
// O(n) time | O(n) space - where n is the total number of elements in the array 
function spiralTraverse(array) 

Java Code:

 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
class Program 
Peak i definitions:

  • arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
  • arr[i] > arr[i + 1] > ... > arr[arr.length - 1]

845. Longest Mountain in Array

Solution: Time O(n) | Space O(1)

  1. Iterate array to Find peeks in the array, once find a peek, expand its left and right to see how far this peek goes, then save its length to compare next length of finding peek. O(n)

Old Method:

  1. Iterate array to Find all peeks in the array.  O(n)
  2. compare each peek length to get longest peek. O(n)

Example: Traversing the array, find 4 is one peek, expand its left and right to get length=3, save it and continue, find 10 is peek, expand to get it length =6, compare Math.max(4,6) =6…To the end of array. return the length.

JavaScript Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// O(n) time | O(1) space - where n is the length of the input array 
function longestPeak(array) 

Java Code:

 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
class Program 
Problem : Return true or false to validate if it's Binary Search Tree.

Leetcode Link

JavaScript Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class BST 
// O(n) time | O(d) space 
function validateBst(tree) 

function validateBstHelper(tree, minValue, maxValue) 
exports.BST = BST;
exports.validateBst = validateBst;

Java Code:

class Program 

Problem : use Pre-order, In-order,  Post-order to traverse a Binary Search Tree

Solution : Recursion

Pre-order:

function preorder(root)
   if not root: return
   print(root.val)
   preorder(root.left)
   preorder(root.right)

In-order:

function preorder(root)
   if not root: return
   preorder(root.left)
   print(root.val)
   preorder(root.right)

Post-order:

function preorder(root)
   if not root: return
   preorder(root.left)
   preorder(root.right)
   print(root.val)

JavaScript Code:

 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
// O(n) time | O(n) space
function inOrderTraverse(tree, array) 
// O(n) time | O(n) space
function preOrderTraverse(tree, array) 
// O(n) time | O(n) space
function postOrderTraverse(tree, array) 
exports.inOrderTraverse = inOrderTraverse;
exports.preOrderTraverse = preOrderTraverse;
exports.postOrderTraverse = postOrderTraverse;

Java Code:

class Program 

Problem : Given a distinct Sorted array, build a Minimum Height BST

Solution : Recursion

Find the middle value as root Node A, then all the values in the left of root will be placed in the left of BST, and all the values in the right of root will be placed in the right of BST.  Use same function to find Left and Right Node of A

JavaScript Code:

 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
36
37
// O(n) time | O(n) space - where n is the length of the array 

function minHeightBst(array) 

function constructMinHeightBst(array, startIdx, endIdx) 
class BST 

Java Code:

 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
class Program 

Problem: invert the BST

Solution: While loop && Recursion

BFS the tree into queue, use queue to traverse it, level by level from top.

  1. poll root node from queue
  2. swap (root.left, root.right), add into queue
  3. repeat step one until queue is empty

While loop:
JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// O(n) time | O(n) space
function invertBinaryTree(tree) 

function swapLeftAndRight(tree) 

Recursion:
JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// O(n) time | O(d) space
function invertBinaryTree(tree) 

function swapLeftAndRight(tree) 

Problem : Given an array with only positive integers, find max subset sum no adjacent

Solution: DP

Formula :

Java Code ( Optimal )   Use 3 Integers : Current = Max ( First , Second ) instead of DP array :

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// O(n) time | O(1) space
function maxSubsetSumNoAdjacent(array) 

Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
class Program 

Problem:

Formula:

Time Complexity (space in optimal solution based on 2*rows or 2*columns):

JavaScript(optimal):

 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
// O(nm) time | O(min(n, m)) space
function levenshteinDistance(str1, str2) 

Java Code :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Program 

Optimal:

 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 Program 
Your Content Goes Here

Problem:

Given an array , return boolean if it has a single cycle: number of forward steps are based on value in array, finally re-arrive to starting index by visiting all indices just once.

Leetcode:

457. Circular Array Loop

Solution: While loop

Extra space: use another array (initial vaule=0) to record number of visit, if any vaule >1, return false

No extra space:
Edge cases:

  1. when we are back to starting index and total number of visited index
  2. when total number of visited =N, and we are not back to starting index, return false

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// O(n) time | O(1) space - where n is the length of the input array 
function hasSingleCycle(array) 

function getNextIdx(currentIdx, array) 

Java Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Program 

Problem:

Use BFS to traverse all node of  G (V,E), and put them into an array, then return the array.

Solution: Queue+While loop

Time complexity : O ( | V | + | E | )     ;   Space complexity: O ( | V | )


JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
// O(n) time | O(1) space - where n is the length of the input array 
function hasSingleCycle(array) 

function getNextIdx(currentIdx, array) 

Java Code :

 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
class Program 

Problem:

Given an m x n 2d grid map of '1's (river) and '0's (land), return the number of islands. Return an array, each value =  length of  a river.

An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

Leetcode: 200. Number of Islands

Solution:

Traverse matrix

if matrix [ x ] [ y ]=1, apply BFS or DFS to find length of this river

push length into result array, then mark them as visited… Next, continue traverse matrix

Finally, return the result array.

JavaScript:

 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
36
37
38
39
40
41
42
// O(wh) time | O(wh) space
function riverSizes(matrix) 

function traverseNode(i, j, matrix, visited, sizes) 

function getUnvisitedNeighbors(i, j, matrix, visited) 

Java Code:

 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
class Program 

Problem:

Given three Nodes: top_Ancestor, descendant_One, descendant_Two. find and return the youngest common ancestor of One and Two.

Leetcode:
235. Lowest Common Ancestor of a Binary Search Tree
236. Lowest Common Ancestor of a Binary Tree

Solution: Time: O( D )  ||  Space: O( 1 )

D=depth of lowest node of One and Two

Bring two nodes to the same level ,

then go up step by step using while loop

return if go up step are the same.

  • find the depth of two nodes a, b, steps to same level= |a-b|

JavaScript:

 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
36
37
38
39
40
class AncestralTree 
// O(d) time | O(1) space - where d is the depth (height) of the ancestral tree 
function getYoungestCommonAncestor(topAncestor, descendantOne, descendantTwo) 

function getDescendantDepth(descendant, topAncestor) 

function backtrackAncestralTree(lowerDescendant, higherDescendant, diff) 

exports.AncestralTree = AncestralTree;
exports.getYoungestCommonAncestor = getYoungestCommonAncestor;

Java Code:

 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
class Program 

Problem: Given head of Linked List, Remove Nth Node From End.

Solution: Two Pointers || Time: O(N) Space: O(1)

  1. let Slow Fast Pointer =head, let fast pointer move N steps, Now Fast Point is N nodes ahead of Slow Pointer.
  2. Continuing move both Pointers to traverse Linked List until Fast.Next=null, remove slow pointer node: slow.previous=slow.next.

Edge case: N=length of Linked List, when Fast move N node, Fast=null, return slow.next node.
JavaScript:

 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
class LinkedList  

// O(n) time | O(1) space
function removeKthNodeFromEnd(head, k) 
exports.LinkedList = LinkedList;
exports.removeKthNodeFromEnd = removeKthNodeFromEnd;

Java Code:

 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 Program 

Problem: Given an array with unique integers, return all possible array.

Solution: Swap in Array (Optimal), Recursion.

Swap Code:

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// Upper Bound: O(n^2*n!) time | O(n*n!) space
// Roughly: O(n*n!) time | O(n*n!) space
function getPermutations(array) 

function permutationsHelper(array, currentPermutation, permutations) 
exports.getPermutations = getPermutations;

Java:

 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 Program 

Recursion Code:
JavaScript:

 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
// O(n*n!) time | O(n*n!) space
function getPermutations(array) 

function permutationsHelper(i, array, permutations) 

function swap(i, j, array) 
exports.getPermutations = getPermutations;

Java:

 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 Program 

Problem: Given an array, return the Powerset. it's defined as the set of all sub of another set.

Solution: Iteration or Recursion

Iteration: Time,Space=O(2^n*n)

  1. []
  2. add 1,
  3. add 2,
  4. add 3,

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// O(n*2^n) time | O(n*2^n) space
function powerset(array) 
exports.powerset = powerset;

Java Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Program 

Problem: Given a sorted Matrix and an Integer, return the index of the Integer in that Matrix.

Solution: While lopp

  1. Martix[row][col]
    starts from Top Left
  2. if(Martix[row][col] >targer)  col--;
  3. if(Martix[row][col]
  4. else return Martix[row][col]

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// O(n + m) time | O(1) space
function searchInSortedMatrix(matrix, target) 
exports.searchInSortedMatrix = searchInSortedMatrix;

Java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Program 

Problem: Define Min Max Stack Data Structure with peek(), pop(), push(), getMin(), getMax().

Solution:

  1. Use List> minMaxStack to store history min and max value.
  2. Use List stack to store Stack Values


JavaScript:

 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
36
37
class MinMaxStack 

Java Code:

 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
36
37
38
39
40
class MinMaxStack 

Problem: Given a String, return  the Longest Palindromic Substring.

A palindrome [pælin'drɔmik] is defined as a string that's written the same forward as backward.

Solution: Iteration || Time=O(n^2)  Space=O(1)

Traverse the String to check each center and expand from them.

  1. At index i, if (Str[i-1]==Str[i+1]) odd
  2. else if(Str[i]==Str[i-1]) even

Palindrome can be either if even length or odd length.


JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// O(n^2) time | O(1) space
function longestPalindromicSubstring(string) 

function getLongestPalindromeFrom(string, leftIdx, rightIdx) 
exports.longestPalindromicSubstring = longestPalindromicSubstring;

JavaScript:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// O(w * n * log(n)) time | O(wn) space - where w is the number of words and n is 
function groupAnagrams(words) 
exports.groupAnagrams = groupAnagrams;

Java Code:

 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
class Program 

Problem:

Given an array of strings strs, group the anagrams together. You can return the answer in any order.

An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.

Leetcode: 49. Group Anagrams

Solution: check out comments in Code

Java Code:

 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
class Program 

 

Problem : Construct Suffix Trie Tree in order to recognize if given string a is suffix of string b

Asterisk means end of the string.


JavaScript:

 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 SuffixTrie 

Java Code:

 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
36
37
38
39
40
41
42
43
44
45
46
47
48
class TrieNode