Giter Club home page Giter Club logo

algorithm's Introduction

Algorithm

I'm learning algorithm at LeetCode and HackerRank. This repo contains some techniques and the list of solutions. Solutions are written as markdown files following the naming convention:

leetcode/${id}.${name}.md

CheckList

  • Do you understand the question? Can you rephrase it?
  • What is your strategy for the resolution?
  • The estimation of time complexity and space complexity?
  • Illustrate the solution steps using a simple example?
  • Corner cases, are they being considered?
  • Any ideas of further optimization? Saying it rather than writing it, because of time constraint, readability, or other reasons.

Array

Boyer–Moore majority vote algorithm. Finding a majority element that occurs ≥ N/2 times. Done in O(N) runtime and O(1) space. See https://en.wikipedia.org/wiki/Boyer%E2%80%93Moore_majority_vote_algorithm.

Hash code of the array. Returns a hash code based on the contents of the specified array (overloaded methods: boolean[], byte[], char[], double[], float[], int[], long[], Object[], short[]):

java.util.Arrays.hashCode(int[] a);

2 Pointers (Fast & Slow). One slow pointer and one fast pointer. They both move forwards at same speed unless in some cases, slow pointer needs to stop. This strategy can be used to manipulate the array in place. Example: LeetCode 27 Remove Element.

2 Pointers (Left & Right). Left pointer moves right, right pointer moves left. ⚠️ Make sure they stop at the right moment to avoid collapse.

Find Max (Min). Do not use sorting to find max or min values from an array. This can be done using variables and in one iteration. Time complexity: O(N).

Sorting. Sometimes sorting is useful before addressing the real problem. It enables the relationship between neighbour elements. The time complexity is O(N log N).

Permutation. The next permutation in lexicographic order can be generated using the method created by Narayana Pandita, see Wikipedia: Permutation - Generation in lexicographic order

Related problems:

Prefix Sum. In computer science, the prefix sum, cumulative sum, inclusive scan, or simply scan of a sequence of numbers x0, x1, x2, ... is a second sequence of numbers y0, y1, y2, ..., the sums of prefixes (running totals) of the input sequence. See https://en.wikipedia.org/wiki/Prefix_sum.

Related problems:

Priority Queue

Kth Element. Find the Kth largest or smallest element in a collection or array. This can be done using a priority queue with K elements. If looking for the Kth largest element, use a min heap, so that peek (poll) from the priority queue returns the Kth element. If looking for the Kth smallest, use a max heap, so that peek (poll) from the priority queue returns the Kth element.

Related problems:

Hash Table

Use array as hash table. If possible, use an array as the reference table for finding the right element. Compared to any Map implementation, using array is faster and consumes less memory. This is typically possible when the keys are ASCII characters. You can create an array with 128 elements, for boolean status (boolean[]), char count (int[]), etc.

int[] counts = new int[128];
for (char c : word.toCharArray()) {
    counts[c]++;
}

Related problems:

Use Hashtable to Store References. Use hashtable to store the target references. It helps to reduce cost for lookup operation, compared to double for-loop.

Related problems:

Linked List

2 pointers. One slow pointer (1x speed) and one fast pointer (2x speed). It allows to resolve circular issue, because the faster one will be 1 round faster after some moves. 2 pointers strategy can also be used for keeping a distance between two pointers.

Related problems:

Changing "next" reference. In sinlge linked list, changing the reference of the "next" node can be useful for some operations, such as reversing the list. Here is an illustration:

Input:   1 -> 2 -> 3 -> 4 -> 5
Output:  1 <- 2 <- 3 <- 4 <- 5

Related problems:

String

Two Pointers. Use two pointers L, R for switching characters.

Related problems:

Permutation in String. Maintain a sliding window [L, R] in the string, use two variables: int[] stock and int todo to record respectively what are the remaining characters available for permutation as ASCII table, and the remaining number of characters to do to have a match.

  • When R (right pointer) moves forward, it consumes more chars from the stock table.
  • When L (left pointer) moves forward, it recover the consumed chars from the stock table.

Related problems:

String construction. When resolving exercises, it's better to use java.lang.StringBuilder rather than string concatenation using +. Even better, use char array char[] and fill it manually, which is efficient and allows navigation.

Constructor Description
StringBuilder() Constructor without additional arguments
StringBuilder(String) Constructor with an initial string
StringBuilder(int) Constructor with initial capacity
String(char[]) Constructor with a char array
String(char[], int, int) Constructor with offset and length

Bit Manipulation

Power of Two. An integer is power of two if it is positive and has only one bit.

N Binary
1 ... 0000 0000 0000 0001
2 ... 0000 0000 0000 0010
4 ... 0000 0000 0000 0100
8 ... 0000 0000 0000 1000
16 ... 0000 0000 0001 0000

Tree

There are two types traverals: depth-first search (DFS) and breath-first search (BFS). For depth-first search, the traversal can be pre-order (NLR), in-order (LNR), out-order (RNL), and post-order (LRN).

Depth-first search: pre-order

preorder traversal

Depth-first search: in-order

inorder traversal

Depth-first search: post-order

postorder traversal

Breath-first search:

breath first search traversal

Graph

In mathematics, and more specifically in graph theory, a graph is a structure amounting to a set of objects in which some pairs of the objects are in some sense "related". Graph can be undirected or directed. The figure below shows an example network with 8 vertices and 10 edges.

Small Network

Graph (undirected graph):

Undirected

Directed Graph:

Directed

Dynamic Programming

Dynamic programming (DP) is a method for solving complex problems by breaking them down into simpler subproblems. Remember the three steps:

  1. Defining sub-problems
  2. Finding recurrences
  3. Solving the base cases

For more detail, see Stanford University Online Lecture CS 97SI: https://web.stanford.edu/class/cs97si/04-dynamic-programming.pdf.

Number

Enrich Integer Via Bits. You can provide additional information to an integer by using the unused bits. This is possible when integer is served as an emumerate value, e.g. only using 0 as false and 1 as true. This strategy is useful when you need to do something in-place, or you are not allowed to use more complex data structure.

Related problems:

Search and Sort

Custom Binary Search. In some cases, the problem can be solved by using a binary-search-like strategy to find the target item by eliminating half of the items.

Related problems:

Custom Data Structure

LRU Cache. Discards the least recently used items first. See YouTube video Implement An LRU Cache - The LRU Cache Eviction Policy ("LRU Cache" on LeetCode) for more detail explanation.

Related problems:

Useful APIs

Useful APIs in Java.

Method Description
String(char[] value, int offset, int count): String String constructor, useful for creating a string from a char array.
String#substring(int beginIndex, int endIndex): String Extracts a substring from string.

Corner Cases

TreeNode:

  • Can root be null?

Integer:

  • Boundaries: Integer.MIN_VALUE and Integer.MAX_VALUE good boundaries? Comparison will fail when the integer itself is one of these values.
  • Risk of overflow?
  • Average for sum of two integers: prefer start + (end - start) / 2 rather than (start + end) / 2, so that the overflow problem can be avoided.
  • Integer division: when both dividend and divisor are integer, the quotient will be an integer too. For example, 3 / 2 = 1. In order to have an accurate result, you need to ensure either divident or divisor to be a float or a double.

Array:

  • Can array be null?
  • The length of the array?
  • Subarray: how to define subarray, at least 1 item or 2 items?

2D Array:

  • Coordinate (x, y) or (i, j): which position is (0, 0), what direction is the axes? It's easy to draw diagram on whitebroad using (x, y) like in Math. But in the program, it's easier to use (i, j).

Comparator:

  • Compare one field after another, if one field is different, compute the diff and return the result. Only when this field is equal on both instances, you can pass to the next field. Be careful about problem "Comparison method violates its general contract!"

HackerRank

Too lazy to add 🙈

LeetCode

Id Problem Runtime (Java)
1 Two Sum 2ms
2 Add Two Numbers 2ms
3 Longest Substring Without Repeating Characters 14ms
5 Longest Palindromic Substring 16ms
7 Reverse Integer 1ms
9 Palindrome Number 7ms
11 Max Area 1ms
12 Integer to roman 7ms
13 Roman to Integer 5ms
14 Longest Common Prefix 4ms
15 3Sum 39ms
17 Letter Combinations of a Phone Number 0ms
19 Remove Nth Node From End of List 0ms
20 Valid Parentheses 4ms
21 Merge two sorted lists 5ms
22 Generate Parentheses 0ms
23 Merge K Sorted Lists 5ms
26 Remove Duplicates From Sorted Array 1ms
27 Remove Element 0ms
28 Implement strStr() 2ms
31 Next Permutation 0ms
33 Search in Rotated Sorted Array 0ms
34 Find First and Last Position of Element in Sorted Array 0ms
35 Search Insert Position 0ms
36 Valid sudoku 7ms
38 Count and say 4ms
39 Combination Sum 5ms
40 Combination Sum II 4ms
46 Permutations 3ms
47 Permutations II 1ms
48 Rotate Image 0ms
49 Group Anagrams 12ms
50 Pow x-n 26ms
53 Maximum Subarray 0ms
54 Spiral Matrix 0ms
56 Merge Intervals 7ms
58 Length of Last Word 0ms
62 Unique Paths 0ms
64 Minimum Path Sum 2ms
65 Valid Number 1ms
66 Plus One 0ms
67 Add Binary 1ms
70 Climbing Stairs 2ms
75 Sort Colors 0ms
76 Minimum Window Substring 5ms
77 Combinations 2ms
78 Subsets 1ms
79 Word Search 4ms
83 Remove Duplicates from Sorted List 0ms
86 Partition List 0ms
88 Merge Sorted Array 2ms
90 Subsets II 1ms
91 Decode Ways 1ms
92 Reverse Linked List II 0ms
94 Binary Tree Inorder Traversal 0ms
98 Validate Binary Search Tree 0ms
100 Same Tree 1ms
101 Symmetric Tree 5ms
102 Binary Tree Level Order Traversal 1ms
103 Binary Tree Zigzag Level Order Traversal 1ms
104 Maximun Depth of a Binary Tree 0ms
107 Binary Tree Level Order Traversal II 1ms
108 Convert Sorted Array to Binary Search Tree 0ms
110 Balanced Binary Tree 1ms
111 Minimum Depth of Binary Tree 0ms
112 Path Sum 0ms
113 Path Sum II 1ms
114 Flatten Binary Tree to Linked List 0ms
118 Pascal Triangle 0ms
119 Pascal triangle II 2ms
120 Triangle 2ms
121 Best Time to Buy and Sell Stock 1ms
122 Best time to buy and sell stock II 2ms
125 Valid Palindrome 2ms
133 Clone Graph 1ms
136 Single Number 0ms
138 Copy List with Random Pointer 1ms
139 Word Break 2ms
141 Linked List Cycle 0ms
144 Binary Tree Preorder Traversal 0ms
146 LRU Cache 61ms
151 Reverse Words in a String 1ms
152 Maximum Product Subarray 1ms
153 Find Minimum in Rotated Sorted Array 0ms
155 Min Stack 47ms
160 Intersection of Two Linked Lists 1ms
162 Find Peak Element 1ms
163 Missing ranges 13ms
165 Compare Version Numbers 4ms
167 Two Sum II - Input array is sorted 0ms
168 Excel sheet column title 0ms
169 Majority Element 3ms
171 Excel Sheet Column Number 1ms
172 Factorial Trailing Zeroes 2ms
179 Largest Number 3ms
186 Reverse Words in a String II 3ms
189 Rotate array 1ms
190 Reverse Bits 1ms
191 Number of 1 Bits 0ms
195 Tenth line 15ms
198 House Robber 0ms
199 Binary Tree Right Side View 1ms
200 Number of Islands 1ms
202 Happy Number 1ms
203 Remove linked list elements 2ms
204 Count Primes 32ms
205 Isomorphic strings 50ms
206 Reverse Linked List 0ms
215 Kth Largest Element in an Array 4ms
217 Contains Duplicate 9ms
219 Contains Duplicate II 8ms
221 Maximal Square 4ms
222 Count Complete Tree Nodes 1ms
225 Implement Stack Using Queues 45ms
226 Invert Binary Tree 0ms
228 Summary ranges 0ms
230 Kth Smallest Element in a BST 0ms
231 Power of Two 1ms
232 Implement Queue Using Stacks 42ms
234 Palindrome Linked List 1ms
235 Lowest Common Ancestor of a Binary Search Tree 4ms
236 Lowest Common Ancestor of a Binary Tree 5ms
237 Delete Node in a Linked List 0ms
238 Product of Array Except Self 1ms
240 Search a 2D matrix II 13ms
242 Valid Anagram 4ms
243 Shortest Word Distance 1ms
244 Shortest word distence II 27ms
245 Shortest word distance III 6ms
246 Strobogrammatic Number 0ms
252 Meeting rooms 13ms
253 Meeting rooms 19ms
256 Paint House 1ms
257 Binary Tree Paths 7ms
258 Add Digits 1ms
260 Single number III 10ms
263 Ugly Number 1ms
266 Palindrome permutation 1ms
268 Missing Number 0ms
270 Closest Binary Search Tree Value 0ms
271 Encode and decode strings 15ms
274 H-Index 3ms
278 First Bad Version 10ms
279 Perfect squares 58ms
280 Wiggle sort 1ms
283 Move Zeroes 1ms
288 Unique word abbreviation 79ms
289 Game of Life 0ms
293 Flip game 1ms
297 Serialize and Deserialize Binary Tree 23ms
298 Binary tree longest consecuritve sequence 3ms
300 Longest Increasing Subsequence 1ms
303 Range Sum Query - Immutable 52ms
304 Range Sum Query 2D - Immutable 57 ms
311 Sparse Matrix Multiplication 0ms
318 Maximum product of word lengths 71ms
320 Generalized abbreviation 21ms
322 Coin Change 9ms
326 Power of Three 21ms
332 Reconstruct Itinerary 36ms
338 Counting Bits 1ms
342 Power of Four 1ms
343 Integer break 0ms
344 Reverse String 1ms
345 Reverse Vowels of a String 2ms
346 Moving Average From Data Stream 69ms
347 Top K Frequent Elements 10ms
349 Intersection of Two Arrays 2ms
350 Intersection of two arrays II 2ms
351 Android unlock pattern 13ms
357 Count numbers with unique digits 0ms
359 Logger rate limiter 187ms
360 Sort transformed array 1ms
367 Valid perfect square 400ms
369 Plus one linked list 1ms
374 Guess number higher or lower 2ms
378 Kth Smallest Element in a Sorted Matrix 1ms
382 Linked list random node 146ms
383 Ransom note 18ms
387 First Unique Character in a String 31ms
388 Longest Absolute File Path 0ms
389 Find the difference 9ms
392 Is Subsequence 0ms
394 Decode String 0ms
398 Find the Difference 1ms
400 Nth Digit 7ms
401 Binary watch 1ms
402 Remove K digits 29ms
404 Sum of Left Leaves 3ms
405 Convert a Number to Hexadecimal 0ms
406 Queue reconstruction by height 15ms
408 Valid Word Abbreviation 22ms
409 Longest Palindrome 2ms
412 Fizz Buzz 1ms
414 Third Maximum Number 6ms
415 Add Strings 9ms
429 N-ary Tree Level Order Traveral 4ms
437 Path Sum III 6ms
438 Find All Anagrams in a String 9ms
443 String Compression 1ms
448 Find All Numbers Disappeared in an Array 6ms
451 Sort Characters By Frequency 6ms
461 Hamming Distance 0ms
463 Island Perimeter 53ms
476 Number Complement 5ms
482 License Key Formatting 8ms
485 Max Consecutive Ones 4ms
500 Keyboard Row 1ms
509 Fibonacci Number 12ms
520 Detect Capital 14ms
541 Reverse String II 2ms
543 Diameter of Binary Tree 0ms
559 Maximum Depth of N-ary Tree 2ms
557 Reverse Words in a String III 5ms
560 Subarray Sum Equals K 12ms
561 Array Partition I 20ms
572 Subtree of Another Tree 6ms
576 Permutation in String 7ms
581 Shortest Unsorted Continuous Subarray 8ms
589 N-ary Tree Preorder Traversal 8ms
590 N-ary Tree Postorder Traversal 4ms
595 Big Countries 1672ms
606 Construct String from Binary Tree 12ms
617 Merge Two Binary Tree 6ms
621 Task Scheduler 4ms
623 Add One Row to Tree 4ms
637 Average of Levels in Binary Tree 2ms
647 Palindromic Substrings 1ms
654 Maximum Binary Tree 6ms
657 Robot returns to Origin 9ms
669 Trim a Binary Search Tree 0ms
671 Second Minimum Node In a Binary Tree 2ms
674 Longest Continuous Increasing Subsequence 2ms
680 Valid Palindrome II 7ms
682 Maximum Product of Three Numbers 3ms
692 Top K Frequent Words 6ms
693 Binary Number with Alternating Bits 0ms
695 Max Area of Island 2ms
700 Search in a Binary Search Tree 2ms
703 Kth Largest Element in a Stream 62ms
709 To Lower Case 0ms
719 Max Stack 89ms
746 Min Cost Climbing Stairs 1ms
771 Jewels and Stones 0ms
784 Letter Case Permutation 1ms
790 Rotate String 0ms
804 Unique Morse Code Words 4ms
821 Shortest Distance to a Character 4ms
832 Flipping an Image 0ms
844 Backspace String Compare 0ms
872 Leaf-Similar Trees 0ms
876 Middle of the Linked List 1ms
890 Find and Replace Pattern 2ms
891 Most Common Word 4ms
896 Monotonic Array 12ms
905 Sort Array By Parity 12ms
916 Word Subsets 23ms
917 Reverse Only Letters 3ms
922 Sort Array By Parity II 4ms
925 Long Pressed Name 3ms
929 Unique Email Addresses 10ms
931 Minimum Falling Path Sum 3ms
935 Knight Dialer 20ms
937 Reorder Log Files 2ms
938 Range Sum of BST 0ms
953 Verifying an Alien Dictionary 3ms
961 N-Repeated Element in Size 2N Array 4ms
965 Univalued Binary Tree 3ms
973 K Closest Points to Origin 20ms
974 Subarray Sums Divisible by K 4ms
977 Squares of a sorted array 20ms
981 Time Based Key-Value Store 211ms
1002 Find Common Characters 2ms
1013 Partition Array Into Three Parts With Equal Sum 1ms

References

algorithm's People

Contributors

mincong-h avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

algorithm's Issues

Repo clean up

  • delete class path
  • delete bin
  • delete project
  • delete term to explain
  • update README, remove the code link
  • all explanations should go to mincong-h.github.io

Generally speaking, code do not need to be runnable. If they were real results from different algorithms, that's good enough.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.