X Tutup
Skip to content

Latest commit

 

History

History
373 lines (337 loc) · 16.9 KB

File metadata and controls

373 lines (337 loc) · 16.9 KB
Problem.all.order(created_at: :desc).map do |problem| puts problem.id.to_s + '. ' + problem.title;  end
125. Valid Palindrome
14. Longest Common Prefix
58. Length of Last Word
13. Roman to Integer
169. Majority Element
88. Merge Sorted Array
605. Can Place Flowers
5. Longest Palindromic Substring
3494. Find the Minimum Amount of Time to Brew Potions
833. Find And Replace in String
49. Group Anagrams
3478. Choose K Elements With Maximum Sum
144. Binary Tree Preorder Traversal
1334. Find the City With the Smallest Number of Neighbors at a Threshold Distance
787. Cheapest Flights Within K Stops
743. Network Delay Time
433. Minimum Genetic Mutation
752. Open the Lock
1514. Path with Maximum Probability
207. Course Schedule
1584. Min Cost to Connect All Points
685. Redundant Connection II
684. Redundant Connection
1971. Find if Path Exists in Graph
127. Word Ladder
827. Making A Large Island
695. Max Area of Island
463. Island Perimeter
200. Number of Islands
797. All Paths From Source to Target
84. Largest Rectangle in Histogram
42. Trapping Rain Water
496. Next Greater Element I
739. Daily Temperatures
72. Edit Distance
583. Delete Operation for Two Strings
392. Is Subsequence
53. Maximum Subarray
1035. Uncrossed Lines
1143. Longest Common Subsequence
718. Maximum Length of Repeated Subarray
300. Longest Increasing Subsequence
674. Longest Continuous Increasing Subsequence
309. Best Time to Buy and Sell Stock with Cooldown
188. Best Time to Buy and Sell Stock IV
123. Best Time to Buy and Sell Stock III
714. Best Time to Buy and Sell Stock with Transaction Fee
122. Best Time to Buy and Sell Stock II
121. Best Time to Buy and Sell Stock
139. Word Break
279. Perfect Squares
322. Coin Change
377. Combination Sum IV
518. Coin Change II
474. Ones and Zeroes
494. Target Sum
1049. Last Stone Weight II
416. Partition Equal Subset Sum
337. House Robber III
213. House Robber II
198. House Robber
509. Fibonacci Number
225. Implement Stack using Queues
20. Valid Parentheses
232. Implement Queue using Stacks
18. 4Sum
459. Repeated Substring Pattern
541. Reverse String II
28. Find the Index of the First Occurrence in a String
15. 3Sum
454. 4Sum II
202. Happy Number
383. Ransom Note
1. Two Sum
242. Valid Anagram
349. Intersection of Two Arrays
24. Swap Nodes in Pairs
19. Remove Nth Node From End of List
707. Design Linked List
160. Intersection of Two Linked Lists
206. Reverse Linked List
203. Remove Linked List Elements
26. Remove Duplicates from Sorted Array
503. Next Greater Element II
303. Range Sum Query - Immutable
209. Minimum Size Subarray Sum
59. Spiral Matrix II
977. Squares of a Sorted Array
704. Binary Search
27. Remove Element
344. Reverse String
443. String Compression
334. Increasing Triplet Subsequence
238. Product of Array Except Self
151. Reverse Words in a String
345. Reverse Vowels of a String
1431. Kids With the Greatest Number of Candies
1071. Greatest Common Divisor of Strings
1768. Merge Strings Alternately

LeetCode skills

If you want to solve problems in the most understandable way, please look for Coding5DotCom.

Array

  • Array is consecutive in memory.
  • Cannot delete an item. Actually, it is overwrite. Delete a item of array will call the latter items move 1 to left. So it is O(n) time complexity.
  • C++ 2D array is also consecutive. But Java is not.

Hash function

You want to store students' information into a hash table. You want to query information by a student's name.

  • index = theHashFunction(student_name) the_information = the_hash_table[index].

Binary tree unified stack iteration

boolean mark solution.

Other Algorithms

Recursion

  • Recursion steps:
    1. Determine the parameters
    2. Determine the recursion logic
    3. Determine the return value
    4. Determine the exit logic

Dynamic programming

The principle of dynamic programming is from top to bottom, from left to right, from less to more, from near to far, from known to unknown and take turns being the boss.

Monotonic stack

  • Push indies one by one.
  • Only the useful indies are kept in the stack. Useless indices are popped (or eaten by followed larger (or smaller) index).

Graph theory

The principle of traversal (DFS or BFS) between undirected graph or directed graph are similar.

  • First rule: don't visited nodes again. This rule make starting from a node to traverse the undirected graph have a direction.

  • The adjacent nodes of undirected graph are its non-visited neighbors.

  • The adjacent nodes of directed graph are its targeted nodes.

  • Truth: An undirected graph can be understood as a bidirectional directed graph. Sometimes, we make use of it.

Minimum spanning a tree

  • Prim's algorithm can be used to minimum spanning a tree. It added the closest node to the tree each time. It uses a min_distances. It is recommended to use a priority_queue.
  • Kruskal's algorithm can also be used to minimum spanning a tree, but it adds the shortest edge each time. To combine the two nodes of an edge, UnionFind is used.

Shortest path

  • This is graph, not a tree. It can have cycles and many connected components.
  • Dijkstra's algorithm finds the shortest path from one vertex to all other vertices. It is like Prim's algorithm, also uses a min_distances, but the distance is to the original source vertex. All the weights of edges must not be a negative value.
  • Bellman_Ford algorithm finds the shortest path from one vertex to all other vertices. It effectively works in the cases of negative edges and is able to detect negative weight cycles. It also uses min_distances. Relaxation works by continuously shortening the calculated distance. It's straightforward and easily to be coded. The improved way with a queue is commonly more efficient. Relaxing All Edges by vertices.length – 1 times gives us Single Source Shortest Path to all vertices.
  • Bellman_Ford algorithm need to start from one source vertex each time and find the shortest paths to the source vertex. Floyd–Warshall algorithm can find all vertices' shortest paths.
  • What Floyd–Warshall algorithm solves can also be done by iterating through vertices and apply Bellman_Ford algorithm on each vertex; But if it is a Dense Graph, Floyd–Warshall algorithm is faster.
  • If all edges' weights are not negative, what Floyd–Warshall algorithm solves can also be done by iterating through vertices and apply Dijkstra algorithm on each vertex.
  • The time complexity of running V times Dijkstra algorithm is E * logE * V.
  • The time complexity of Floyd–Warshall algorithm is V * V * V. For a dense graph, Floyd–Warshall algorithm is still faster.
  • A* algorithm use a priority queue, pop() to get the vertex closest to the destination vertex. We need to choose proper math formula to determine which one is the closest. We to the very near place of destination vertex, we can use some special method to make it can handle the last part.

|Algorithm name|Focus|Key implementation methods|mark visited| |Prim's algorithm|Vertices|| |Kruskal's algorithm|Edges|Union-Find| |Dijkstra's algorithm|Vertices|| |Bellman-Ford algorithm|Edges(Vertices+Edges for SPFA)|| |Dijkstra's by heap sort - min_distance = A*| UnionFind + Heap sort = Kruskal BFS + heap sort = A*

Add a table to show the differences between A-Start and breadth-first search

Others

  • Find all the prime numbers within 1000000.

Solutions which need a perfection

Skipped problems/solutions

Binary Tree

  • Remember to add the recursion steps (described above in this doc) first

Backtracking

Greedy Algorithm

Dynamic programming

backpack problems

palindrome issue key: from middle, 2-d, +1 or +2, dp.size = len(s), do it on left-bottom side.

Graph

Failed in 2 rounds

other finished problems

Other algorithm

https://leetcode.cn/problems/closest-equal-element-queries

Timeout1

class Solution:

def solveQueries(self, nums: List[int], queries: List[int]) -> List[int]:

n = len(nums)

answer = []

for i in range(len(queries)):

index = queries[i]

num = nums[index]

k = 1

while k < n:

if num == nums[(index + k) % n]:

answer.append(k)

break

if num == nums[index - k]:

answer.append(k)

break

k += 1

if k == n:

answer.append(-1)

return answer

X Tutup