Grokking the Coding Interview

Overview

A comprehensive guide for java coding interviews covering areas like algorithms, datastructures, sorting, leetcode problems, concurrency, java fundamentals.

Github: https://github.com/gitorko/project01

Preparation

  • We will first understand the fundamentals of data structure, like how heap, queue, stacks work and how to implement them from scratch.
  • Then we will look at the various sorting algorithms.
  • Then we will move to leetcode problems covering easy, medium & hard problems.
  • Then we will move to concurrency problems, how atomic variable work, how locks work etc.
  • Then we will cover some SQL and database queries.
  • The problems solved here are concise & small making it easy to understand and revise.
  • All problems solved here are developed with test driven approach, with various test that can be run locally.
  • Each of the solutions follow certain pattern. Eg: if you learn back-tracking solution in one problem the pattern is similar when you solve it in other problem. This is very important when it comes to the learning aspect.
  • Most problems have a parent problem, Once you solve this parent problem you can solve various subset or variation of this problem. Such problems are grouped as similar in the solutions.

Approach To Solve

Given a problem here are some questions that should help you figure out the general direction of how to solve it

  1. Which data structure can I use? Arrays, LinkedList, HashMap, Heap, Tree, or Trie
  2. Do I need to use 2 data structures? eg: LRU
  3. How do I break the problem into smaller units, is there a problem within a problem, can i write a decision tree?
  4. Does this problem look similar to other problems you have solved?
  5. Will sorting make the problem easier to solve?
  6. Can I use any algorithmic techniques, like bfs, dfs, two pointer etc.
  7. Do any design patterns apply that could make it easier to maintain, like observer pattern?
  8. What is the time & space complexity? Best case, worst case time complexity? Average case is usually difficult to derive.

Tips

  1. Linked list problems often use a dummy node.
  2. To delete a node in the link list you need previous node or be position one node behind.
  3. Time complexity is O(number of branches ^ n)
  4. In-order traversal of BST results in ascending order array.
  5. BFS requires a queue, DFS requires recursion.
  6. If the char set is bound to 26 chars, use char[26] array instead of Map or Set.

Algo Techniques

  • Sorting
  • Map & Set
  • Recursion
  • Fast pointer & Slow pointer
  • Min-Heap vs Max-Heap (Priority Queue)
  • Binary search
  • BFS vs DFS
  • Two Pointers
  • Sliding Window
  • Fast pointer vs Slow pointer
  • Backtracking
  • Matrix
  • Prefix sum
  • Divide & Conquer
  • Memoization / Dynamic programming
  • Greedy
  • Topological Sort
  • Intervals
  • Cyclic Sort
  • Bitwise XOR / Bit manipulation
  • Trie
  • Stacks & Queue

Big-O

1log(n) < √(n) < n < nlog(n) < n^2 < n^3 < 2^n < n!

Algorithms and Data Structures Cheatsheet

Coding

Sorting

IdLeetcodeSolutionType
1Bubble SortSolutionEASY
2Selection sortSolutionEASY
3Insertion sortSolutionEASY
4MergeSortSolutionMEDIUM
5912. Sort an ArraySolutionMEDIUM
6QuickSortSolutionMEDIUM
7912. Sort an ArraySolutionMEDIUM
8Shell sortSolutionHARD
9Counting sortSolutionEASY
10Radix sortSolutionMEDIUM
11Bucket sortSolutionEASY
12Heap sortSolutionMEDIUM
13704. Binary SearchSolutionEASY
14Employee SearchSolutionEASY

Data Structure

IdLeetcodeSolutionType
1Implement Circular ArraySolutionEASY
2622. Design Circular QueueSolutionMEDIUM
3Implement ArrayList with arraySolutionEASY
4Insert to BST, Delete from BST, Find from BSTSolutionEASY
5Implement Doubly Linked ListSolutionEASY
6707. Design Linked ListSolutionMEDIUM
7706. Design HashMapSolutionEASY
8Implement MapSolutionMEDIUM
9Implement Max HeapSolutionEASY
10Implement Min HeapSolutionEASY
11Implement QueueSolutionEASY
12Implement StackSolutionEASY
13208. Implement Trie, Prefix TreeSolutionEASY
14225. Implement Stack using QueuesSolutionEASY

LeetCode - Easy

IdLeetcodeSolutionType
167. Add BinarySolutionEASY - Number
2989. Add to Array-Form of IntegerSolutionEASY - Number
3455. Assign CookiesSolutionEASY - Number
4682. Baseball GameSolutionEASY - Number
5121. Best Time to Buy and Sell StockSolutionEASY - Number
6605. Can Place FlowersSolutionEASY - Number
7724. Find Pivot IndexSolutionEASY - Number
89. Palindrome NumberSolutionEASY - Number
9860. Lemonade ChangeSolutionEASY - Number
101572. Matrix Diagonal SumSolutionEASY - Number
11485. Max Consecutive OnesSolutionEASY - Number
1253. Maximum SubarraySolutionEASY - Number
1388. Merge Sorted ArraySolutionEASY - Number
141984. Minimum Difference Between Highest and Lowest of K ScoresSolutionEASY - Number
15268. Missing NumberSolutionEASY - Number
16283. Move ZeroesSolutionEASY - Number
171523. Count Odd Numbers in an Interval RangeSolutionEASY - Number
18119. Pascal's Triangle IISolutionEASY - Number
19118. Pascal's TriangleSolutionEASY - Number
2066. Plus OneSolutionEASY - Number
211299. Replace Elements with Greatest Element on Right SideSolutionEASY - Number
227. Reverse IntegerSolutionEASY - Number
231470. Shuffle the ArraySolutionEASY - Number
24136. Single NumberSolutionEASY - Number
25228. Summary RangesSolutionEASY - Number
26263. Ugly NumberSolutionEASY - Number
27242. Valid AnagramSolutionEASY - String
28389. Find the DifferenceSolutionEASY - String
29412. Fizz BuzzSolutionEASY - String
301071. Greatest Common Divisor of StringsSolutionEASY - String
31205. Isomorphic StringsSolutionEASY - String
32392. Is SubsequenceSolutionEASY - String
3358. Length of Last WordSolutionEASY - String
3414. Longest Common PrefixSolutionEASY - String
351189. Maximum Number of BalloonsSolutionEASY - String
36Minimum append to make string palindromeSolutionEASY - String
371047. Remove All Adjacent Duplicates In StringSolutionEASY - String
38344. Reverse StringSolutionEASY - String
3913. Roman to IntegerSolutionEASY - String
4028. Implement strStrSolutionMEDIUM - String
41929. Unique Email AddressesSolutionEASY - String
42953. Verifying an Alien DictionarySolutionEASY - String
43219. Contains Duplicate IISolutionEASY - Map & Set
44217. Contains DuplicateSolutionEASY - Map & Set
451603. Design Parking SystemSolutionEASY - Map & Set
46202. Happy NumberSolutionEASY - Map & Set
47705. Design HashSetSolutionEASY - Map & Set
48169. Majority ElementSolutionEASY - Map & Set
491. Two SumSolutionEASY - Map & Set
50387. First Unique Character in a StringSolutionEASY - Map & Set
51290. Word PatternSolutionEASY - Map & Set
521636. Sort Array by Increasing FrequencySolutionEASY - Heap
53703. Kth Largest Element in a StreamSolutionEASY - Heap
541046. Last Stone WeightSolutionEASY - Heap
551005. Maximize Sum Of Array After K NegationsSolutionEASY - Heap
56349. Intersection of Two ArraysSolutionEASY - Sliding window / Two pointer
57696. Count Binary SubstringsSolutionEASY - Sliding window / Two pointer
58FactorialSolutionEASY - Sliding window / Two pointer
59509. Fibonacci NumberSolutionEASY - Sliding window / Two pointer
60125. Valid PalindromeSolutionEASY - Sliding window / Two pointer
61674. Longest Continuous Increasing SubsequenceSolutionEASY - Sliding window / Two pointer
6226. Remove Duplicates from Sorted ArraySolutionEASY - Sliding window / Two pointer
6327. Remove ElementSolutionEASY - Sliding window / Two pointer
64977. Squares of a Sorted ArraySolutionEASY - Sliding window / Two pointer
65680. Valid Palindrome IISolutionEASY - Sliding window / Two pointer
66463. Island PerimeterSolutionEASY - Matrix
67Ones in RangeSolutionEASY - Pre-Sum
68303. Range Sum Query - ImmutableSolutionEASY - Pre-Sum
6970. Climbing StairsSolutionEASY - DP
70338. Counting BitsSolutionEASY - DP
71746. Min Cost Climbing StairsSolutionEASY - DP
721137. N-th Tribonacci NumberSolutionEASY - DP
73203. Remove Linked List ElementsSolutionEASY - Link List
74141. Linked List CycleSolutionEASY - Link List
75142. Linked List Cycle IISolutionEASY - Link List
76160. Intersection of Two Linked ListsSolutionEASY - Link List
7721. Merge Two Sorted ListsSolutionEASY - Link List
78876. Middle of the Linked ListSolutionEASY - Link List
79234. Palindrome Linked ListSolutionEASY - Link List
8083. Remove Duplicates from Sorted ListSolutionEASY - Link List
81206. Reverse Linked ListSolutionEASY - Link List
82235. Lowest Common Ancestor of a Binary Search TreeSolutionEASY - Binary Tree
83938. Range Sum of BSTSolutionEASY - Binary Tree
84Binary Tree two sum different levelSolutionEASY - Binary Tree
85Create Binary Tree from Level orderSolutionEASY - Binary Tree
86Get height of binary treeSolutionEASY - Binary Tree
87104. Maximum Depth of Binary TreeSolutionEASY - Binary Tree
88111. Minimum Depth of Binary TreeSolutionEASY - Binary Tree
89Get size of binary treeSolutionEASY - Binary Tree
90543. Diameter of Binary TreeSolutionEASY - Binary Tree
91226. Invert Binary TreeSolutionEASY - Binary Tree
92617. Merge Two Binary TreesSolutionEASY - Binary Tree
93257. Binary Tree PathsSolutionEASY - Binary Tree
94112. Path SumSolutionEASY - Binary Tree
95100. Same TreeSolutionEASY - Binary Tree
96671. Second Minimum Node In a Binary TreeSolutionEASY - Binary Tree
97572. Subtree of Another TreeSolutionEASY - Binary Tree
98404. Sum of Left LeavesSolutionEASY - Binary Tree
99144. Binary Tree Preorder TraversalSolutionEASY - Binary Tree
100145. Binary Tree Postorder TraversalSolutionEASY - Binary Tree
10194. Binary Tree Inorder TraversalSolutionEASY - Binary Tree
102102. Binary Tree Level Order TraversalSolutionEASY - Binary Tree
103144. Binary Tree Preorder TraversalSolutionEASY - Binary Tree
104145. Binary Tree Postorder TraversalSolutionEASY - Binary Tree
10594. Binary Tree Inorder TraversalSolutionEASY - Binary Tree
106107. Binary Tree Level Order Traversal IISolutionEASY - Binary Tree
107783. Minimum Distance Between BST NodesSolutionEASY - Binary Tree
108606. Construct String from Binary TreeSolutionEASY - Binary Tree
109101. Symmetric TreeSolutionEASY - Binary Tree
110441. Arranging CoinsSolutionEASY - Binary Search
111108. Convert Sorted Array to Binary Search TreeSolutionEASY - Binary Search
112374. Guess Number Higher or LowerSolutionEASY - Binary Search
1131539. Kth Missing Positive NumberSolutionEASY - Binary Search
11435. Search Insert PositionSolutionEASY - Binary Search
11569. SqrtxSolutionEASY - Binary Search
116367. Valid Perfect SquareSolutionEASY - Binary Search
117844. Backspace String CompareSolutionEASY - Stack & Monotonic Stack
118155. Min StackSolutionEASY - Stack & Monotonic Stack
119Nearest Greater to RightSolutionEASY - Stack & Monotonic Stack
120496. Next Greater Element ISolutionEASY - Stack & Monotonic Stack
121Nearest Greater to RightSolutionEASY - Stack & Monotonic Stack
12220. Valid ParenthesesSolutionEASY - Stack & Monotonic Stack
12371. Simplify PathSolutionEASY - Stack & Monotonic Stack
124Sort a stackSolutionEASY - Stack & Monotonic Stack
125733. Flood FillSolutionEASY - Graph
1261260. Shift 2D GridSolutionEASY - Graph
1271114. Print in OrderSolutionEASY - Thread
128448. Find All Numbers Disappeared in an ArraySolutionEASY - Cyclic sort
129191. Number of 1 BitsSolutionEASY - Bit Manipulation
130190. Reverse BitsSolutionEASY - Bit Manipulation
131339. Nested List Weight SumSolutionEASY - Generic

LeetCode - Medium

IdLeetcodeSolutionType
1665. Non-decreasing ArraySolutionMEDIUM - Number
21968. Array With Elements Not Equal to Average of NeighborsSolutionMEDIUM - Number
3853. Car FleetSolutionMEDIUM - Number
41958. Check if Move is LegalSolutionMEDIUM - Number
538. Count and SaySolutionMEDIUM - Number
62466. Count Ways To Build Good StringsSolutionMEDIUM - Number
71921. Eliminate Maximum Number of MonstersSolutionMEDIUM - Number
8Pair with diffSolutionMEDIUM - Number
9532. K-diff Pairs in an ArraySolutionMEDIUM - Number
1018. 4SumSolutionMEDIUM - Number
1112. Integer to RomanSolutionMEDIUM - Number
12841. Keys and RoomsSolutionMEDIUM - Number
13670. Maximum SwapSolutionMEDIUM - Number
14152. Maximum Product SubarraySolutionMEDIUM - Number
15918. Maximum Sum Circular SubarraySolutionMEDIUM - Number
161899. Merge Triplets to Form Target TripletSolutionMEDIUM - Number
171007. Minimum Domino Rotations For Equal RowSolutionMEDIUM - Number
182439. Minimize Maximum of ArraySolutionMEDIUM - Number
19Smallest Positive IntegerSolutionMEDIUM - Number
202028. Find Missing ObservationsSolutionMEDIUM - Number
2131. Next PermutationSolutionMEDIUM - Number
222001. Number of Pairs of Interchangeable RectanglesSolutionMEDIUM - Number
2350. Pow x, nSolutionMEDIUM - Number
24238. Product of Array Except SelfSolutionMEDIUM - Number
2580. Remove Duplicates from Sorted Array IISolutionMEDIUM - Number
26402. Remove K DigitsSolutionMEDIUM - Number
271041. Robot Bounded In CircleSolutionMEDIUM - Number
28Shuffle ArraySolutionMEDIUM - Number
2975. Sort ColorsSolutionMEDIUM - Number
30280. Wiggle SortSolutionMEDIUM - Number
312348. Number of Zero-Filled SubarraysSolutionMEDIUM - Number
32Caesar CipherSolutionMEDIUM - String
33165. Compare Version NumbersSolutionMEDIUM - String
34271. Encode and Decode StringsSolutionMEDIUM - String
35395. Longest Substring with At Least K Repeating CharactersSolutionMEDIUM - String
361963. Minimum Number of Swaps to Make the String BalancedSolutionMEDIUM - String
3743. Multiply StringsSolutionMEDIUM - String
38752. Open the LockSolutionMEDIUM - String
39647. Palindromic SubstringsSolutionMEDIUM - String
40838. Push DominoesSolutionMEDIUM - String
411209. Remove All Adjacent Duplicates in String IISolutionMEDIUM - String
426. Zigzag ConversionSolutionMEDIUM - String
431461. Check If a String Contains All Binary Codes of Size KSolutionMEDIUM - Map & Set
44554. Brick WallSolutionMEDIUM - Map & Set
452013. Detect SquaresSolutionMEDIUM - Map & Set
461296. Divide Array in Sets of K Consecutive NumbersSolutionMEDIUM - Map & Set
47535. Encode and Decode TinyURLSolutionMEDIUM - Map & Set
48973. K Closest Points to OriginSolutionMEDIUM - Map & Set
4949. Group AnagramsSolutionMEDIUM - Map & Set
50846. Hand of StraightsSolutionMEDIUM - Map & Set
51380. Insert Delete GetRandomSolutionMEDIUM - Map & Set
521930. Unique Length 3 Palindromic SubsequencesSolutionMEDIUM - Map & Set
53128. Longest Consecutive SequenceSolutionMEDIUM - Map & Set
54146. LRU CacheSolutionMEDIUM - Map & Set
55146. LRU CacheSolutionMEDIUM - Map & Set
56187. Repeated DNA SequencesSolutionMEDIUM - Map & Set
57621. Task SchedulerSolutionMEDIUM - Map & Set
5816. 3Sum ClosestSolutionMEDIUM - Map & Set
591396. Design Underground SystemSolutionMEDIUM - Map & Set
6036. Valid SudokuSolutionMEDIUM - Map & Set
61215. Kth Largest Element in an ArraySolutionMEDIUM - Heap
621985. Find the Kth Largest Integer in the ArraySolutionMEDIUM - Heap
631094. Car PoolingSolutionMEDIUM - Heap
641167. Minimum Cost to Connect SticksSolutionMEDIUM - Heap
651834. Single-Threaded CPUSolutionMEDIUM - Heap
66355. Design TwitterSolutionMEDIUM - Heap
67451. Sort Characters By FrequencySolutionMEDIUM - Heap
681405. Longest Happy StringSolutionMEDIUM - Heap
69983. Minimum Cost For TicketsSolutionMEDIUM - Heap
701882. Process Tasks Using ServersSolutionMEDIUM - Heap
71767. Reorganize StringSolutionMEDIUM - Heap
72358. Rearrange String k Distance ApartSolutionMEDIUM - Heap
731845. Seat Reservation ManagerSolutionMEDIUM - Heap
74Sort K sorted arraySolutionMEDIUM - Heap
75347. Top K Frequent ElementsSolutionMEDIUM - Heap
76692. Top K Frequent WordsSolutionMEDIUM - Heap
77438. Find All Anagrams in a StringSolutionMEDIUM - Sliding window / Two pointer
78122. Best Time to Buy and Sell Stock IISolutionMEDIUM - Sliding window / Two pointer
79881. Boats to Save PeopleSolutionMEDIUM - Sliding window / Two pointer
80Boats to Save People without count per boatSolutionMEDIUM - Sliding window / Two pointer
8111. Container With Most WaterSolutionMEDIUM - Sliding window / Two pointer
821838. Frequency of the Most Frequent ElementSolutionMEDIUM - Sliding window / Two pointer
83904. Fruit Into BasketsSolutionMEDIUM - Sliding window / Two pointer
845. Longest Palindromic SubstringSolutionMEDIUM - Sliding window / Two pointer
85424. Longest Repeating Character ReplacementSolutionMEDIUM - Sliding window / Two pointer
86159. Longest Substring with At Most Two Distinct CharactersSolutionMEDIUM - Sliding window / Two pointer
87340. Longest Substring with At Most K Distinct CharactersSolutionMEDIUM - Sliding window / Two pointer
883. Longest Substring Without Repeating CharactersSolutionMEDIUM - Sliding window / Two pointer
891004. Max Consecutive Ones IIISolutionMEDIUM - Sliding window / Two pointer
901423. Maximum Points You Can Obtain from CardsSolutionMEDIUM - Sliding window / Two pointer
911888. Minimum Number of Flips to Make the Binary String AlternatingSolutionMEDIUM - Sliding window / Two pointer
9264. Minimum Path SumSolutionMEDIUM - Sliding window / Two pointer
93209. Minimum Size Subarray SumSolutionMEDIUM - Sliding window / Two pointer
94763. Partition LabelsSolutionMEDIUM - Sliding window / Two pointer
95567. Permutation in StringSolutionMEDIUM - Sliding window / Two pointer
96151. Reverse Words in a StringSolutionMEDIUM - Sliding window / Two pointer
97581. Shortest Unsorted Continuous SubarraySolutionMEDIUM - Sliding window / Two pointer
981343. Number of Sub-arrays of Size K and Average Greater than or Equal to ThresholdSolutionMEDIUM - Sliding window / Two pointer
991498. Number of Subsequences That Satisfy the Given Sum ConditionSolutionMEDIUM - Sliding window / Two pointer
10015. 3SumSolutionMEDIUM - Sliding window / Two pointer
101167. Two Sum II - Input Array Is SortedSolutionMEDIUM - Sliding window / Two pointer
1021254. Number of Closed IslandsSolutionMEDIUM - Matrix
1031905. Count Sub IslandsSolutionMEDIUM - Matrix
104289. Game of LifeSolutionMEDIUM - Matrix
1051428. Leftmost Column with at Least a OneSolutionMEDIUM - Matrix
106695. Max Area of IslandSolutionMEDIUM - Matrix
107221. Maximal SquareSolutionMEDIUM - Matrix
108200. Number of IslandsSolutionMEDIUM - Matrix
109417. Pacific Atlantic Water FlowSolutionMEDIUM - Matrix
11048. Rotate ImageSolutionMEDIUM - Matrix
11173. Set Matrix ZeroesSolutionMEDIUM - Matrix
1121091. Shortest Path in Binary MatrixSolutionMEDIUM - Matrix
11354. Spiral MatrixSolutionMEDIUM - Matrix
11459. Spiral Matrix IISolutionMEDIUM - Matrix
115130. Surrounded RegionsSolutionMEDIUM - Matrix
116286. Walls and GatesSolutionMEDIUM - Matrix
11779. Word SearchSolutionMEDIUM - Matrix
118113. Path Sum IISolutionMEDIUM - Backtracking
11977. CombinationsSolutionMEDIUM - Backtracking
12039. Combination SumSolutionMEDIUM - Backtracking
12140. Combination Sum IISolutionMEDIUM - Backtracking
1222101. Detonate the Maximum BombsSolutionMEDIUM - Backtracking
1231239. Maximum Length of a Concatenated String with Unique CharactersSolutionMEDIUM - Backtracking
124131. Palindrome PartitioningSolutionMEDIUM - Backtracking
12522. Generate ParenthesesSolutionMEDIUM - Backtracking
12646. PermutationsSolutionMEDIUM - Backtracking
12747. Permutations IISolutionMEDIUM - Backtracking
128String permutationSolutionMEDIUM - Backtracking
12917. Letter Combinations of a Phone NumberSolutionMEDIUM - Backtracking
13093. Restore IP AddressesSolutionMEDIUM - Backtracking
1311849. Splitting a String Into Descending Consecutive ValuesSolutionMEDIUM - Backtracking
13290. Subsets IISolutionMEDIUM - Backtracking
13378. SubsetsSolutionMEDIUM - Backtracking
1341376. Time Needed to Inform All EmployeesSolutionMEDIUM - Backtracking
1351980. Find Unique Binary StringSolutionMEDIUM - Backtracking
136523. Continuous Subarray SumSolutionMEDIUM - Pre-Sum
137926. Flip String to Monotone IncreasingSolutionMEDIUM - Pre-Sum
1382017. Grid GameSolutionMEDIUM - Pre-Sum
139528. Random Pick with WeightSolutionMEDIUM - Pre-Sum
140304. Range Sum Query 2D - ImmutableSolutionMEDIUM - Pre-Sum
141560. Subarray Sum Equals KSolutionMEDIUM - Pre-Sum
142325. Maximum Size Subarray Sum Equals kSolutionMEDIUM - Pre-Sum
1430/1 knapsackSolutionMEDIUM - DP
144894. All Possible Full Binary TreesSolutionMEDIUM - DP
1451626. Best Team With No ConflictsSolutionMEDIUM - DP
146309. Best Time to Buy and Sell Stock with CooldownSolutionMEDIUM - DP
147518. Coin Change 2SolutionMEDIUM - DP
148322. Coin ChangeSolutionMEDIUM - DP
149377. Combination Sum IVSolutionMEDIUM - DP
15091. Decode WaysSolutionMEDIUM - DP
151740. Delete and EarnSolutionMEDIUM - DP
152Egg DropSolutionMEDIUM - DP
1531884. Egg Drop With 2 Eggs and N FloorsSolutionMEDIUM - DP
154198. House RobberSolutionMEDIUM - DP
155213. House Robber IISolutionMEDIUM - DP
156337. House Robber IIISolutionMEDIUM - DP
157343. Integer BreakSolutionMEDIUM - DP
15897. Interleaving StringSolutionMEDIUM - DP
1591143. Longest Common SubsequenceSolutionMEDIUM - DP
160300. Longest Increasing SubsequenceSolutionMEDIUM - DP
161516. Longest Palindromic SubsequenceSolutionMEDIUM - DP
162473. Matchsticks to SquareSolutionMEDIUM - DP
1631911. Maximum Alternating Subsequence SumSolutionMEDIUM - DP
1642002. Maximum Product of the Length of Two Palindromic SubsequencesSolutionMEDIUM - DP
165673. Number of Longest Increasing SubsequenceSolutionMEDIUM - DP
166256. Paint HouseSolutionMEDIUM - DP
167416. Partition Equal Subset SumSolutionMEDIUM - DP
168698. Partition to K Equal Sum SubsetsSolutionMEDIUM - DP
169279. Perfect SquaresSolutionMEDIUM - DP
170Rod CuttingSolutionMEDIUM - DP
1712140. Solving Questions With BrainpowerSolutionMEDIUM - DP
1721140. Stone Game IISolutionMEDIUM - DP
173877. Stone GameSolutionMEDIUM - DP
174SubSet SumSolutionMEDIUM - DP
175SubSet Sum CountSolutionMEDIUM - DP
176494. Target SumSolutionMEDIUM - DP
177120. TriangleSolutionMEDIUM - DP
178Unbounded knapsackSolutionMEDIUM - DP
1791035. Uncrossed LinesSolutionMEDIUM - DP
18095. Unique Binary Search Trees IISolutionMEDIUM - DP
18196. Unique Binary Search TreesSolutionMEDIUM - DP
18263. Unique Paths IISolutionMEDIUM - DP
18362. Unique PathsSolutionMEDIUM - DP
184139. Word BreakSolutionMEDIUM - DP
1852. Add Two NumbersSolutionMEDIUM - Link List
186138. Copy List with Random PointerSolutionMEDIUM - Link List
187287. Find the Duplicate NumberSolutionMEDIUM - Link List
188147. Insertion Sort ListSolutionMEDIUM - Link List
189109. Convert Sorted List to Binary Search TreeSolutionMEDIUM - Link List
19086. Partition ListSolutionMEDIUM - Link List
19182. Remove Duplicates from Sorted List IISolutionMEDIUM - Link List
19219. Remove Nth Node From End of ListSolutionMEDIUM - Link List
193143. Reorder ListSolutionMEDIUM - Link List
19492. Reverse Linked List IISolutionMEDIUM - Link List
195Reverse link list even oddSolutionMEDIUM - Link List
196189. Rotate ArraySolutionMEDIUM - Link List
19761. Rotate ListSolutionMEDIUM - Link List
198148. Sort ListSolutionMEDIUM - Link List
19924. Swap Nodes in PairsSolutionMEDIUM - Link List
200513. Find Bottom Left Tree ValueSolutionMEDIUM - Binary Tree
201173. Binary Search Tree IteratorSolutionMEDIUM - Binary Tree
202230. Kth Smallest Element in a BSTSolutionMEDIUM - Binary Tree
20399. Recover Binary Search TreeSolutionMEDIUM - Binary Tree
20498. Validate Binary Search TreeSolutionMEDIUM - Binary Tree
205Check Level Order Traversal of BSTSolutionMEDIUM - Binary Tree
206110. Balanced Binary TreeSolutionMEDIUM - Binary Tree
2071110. Delete Nodes And Return ForestSolutionMEDIUM - Binary Tree
208979. Distribute Coins in Binary TreeSolutionMEDIUM - Binary Tree
209114. Flatten Binary Tree to Linked ListSolutionMEDIUM - Binary Tree
210106. Construct Binary Tree from Inorder and Postorder TraversalSolutionMEDIUM - Binary Tree
211105. Construct Binary Tree from Preorder and Inorder TraversalSolutionMEDIUM - Binary Tree
2121448. Count Good Nodes in Binary TreeSolutionMEDIUM - Binary Tree
213236. Lowest Common Ancestor of a Binary TreeSolutionMEDIUM - Binary Tree
214236. Lowest Common Ancestor of a Binary TreeSolutionMEDIUM - Binary Tree
215437. Path Sum IIISolutionMEDIUM - Binary Tree
216814. Binary Tree PruningSolutionMEDIUM - Binary Tree
217199. Binary Tree Right Side ViewSolutionMEDIUM - Binary Tree
218129. Sum Root to Leaf NumbersSolutionMEDIUM - Binary Tree
219107. Binary Tree Level Order Traversal IISolutionMEDIUM - Binary Tree
220662. Maximum Width of Binary TreeSolutionMEDIUM - Binary Tree
221103. Binary Tree Zigzag Level Order TraversalSolutionMEDIUM - Binary Tree
222538. Convert BST to Greater TreeSolutionMEDIUM - Binary Tree
223450. Delete Node in a BSTSolutionMEDIUM - Binary Tree
224951. Flip Equivalent Binary TreesSolutionMEDIUM - Binary Tree
225701. Insert into a Binary Search TreeSolutionMEDIUM - Binary Tree
2261993. Operations on TreeSolutionMEDIUM - Binary Tree
227116. Populating Next Right Pointers in Each NodeSolutionMEDIUM - Binary Tree
228669. Trim a Binary Search TreeSolutionMEDIUM - Binary Tree
229252. Meeting RoomsSolutionMEDIUM - Interval
2301288. Remove Covered IntervalsSolutionMEDIUM - Interval
23157. Insert IntervalSolutionMEDIUM - Interval
232986. Interval List IntersectionsSolutionMEDIUM - Interval
23356. Merge IntervalsSolutionMEDIUM - Interval
234253. Meeting Rooms IISolutionMEDIUM - Interval
235435. Non-overlapping IntervalsSolutionMEDIUM - Interval
2361011. Capacity To Ship Packages Within D DaysSolutionMEDIUM - Binary Search
237658. Find K Closest ElementsSolutionMEDIUM - Binary Search
23834. Find First and Last Position of Element in Sorted ArraySolutionMEDIUM - Binary Search
239875. Koko Eating BananasSolutionMEDIUM - Binary Search
2401898. Maximum Number of Removable CharactersSolutionMEDIUM - Binary Search
2412616. Minimize the Maximum Difference of PairsSolutionMEDIUM - Binary Search
242153. Find Minimum in Rotated Sorted ArraySolutionMEDIUM - Binary Search
24381. Search in Rotated Sorted Array IISolutionMEDIUM - Binary Search
24433. Search in Rotated Sorted ArraySolutionMEDIUM - Binary Search
24574. Search a 2D MatrixSolutionMEDIUM - Binary Search
246981. Time Based Key-Value StoreSolutionMEDIUM - Binary Search
247210. Course Schedule IISolutionMEDIUM - Topological Sort
248456. 132 PatternSolutionMEDIUM - Stack & Monotonic Stack
249735. Asteroid CollisionSolutionMEDIUM - Stack & Monotonic Stack
250739. Daily TemperaturesSolutionMEDIUM - Stack & Monotonic Stack
251394. Decode StringSolutionMEDIUM - Stack & Monotonic Stack
2521856. Maximum Subarray Min-ProductSolutionMEDIUM - Stack & Monotonic Stack
2531249. Minimum Remove to Make Valid ParenthesesSolutionMEDIUM - Stack & Monotonic Stack
254150. Evaluate Reverse Polish NotationSolutionMEDIUM - Stack & Monotonic Stack
255901. Online Stock SpanSolutionMEDIUM - Stack & Monotonic Stack
256721. Accounts MergeSolutionMEDIUM - Graph
257787. Cheapest Flights Within K StopsSolutionMEDIUM - Graph
258133. Clone GraphSolutionMEDIUM - Graph
2592359. Find Closest Node to Given Two NodesSolutionMEDIUM - Graph
260323. Number of Connected Components in an Undirected GraphSolutionMEDIUM - Graph
261207. Course ScheduleSolutionMEDIUM - Graph
262802. Find Eventual Safe StatesSolutionMEDIUM - Graph
263261. Graph Valid TreeSolutionMEDIUM - Graph
2642477. Minimum Fuel Cost to Report to the CapitalSolutionMEDIUM - Graph
2652492. Minimum Score of a Path Between Two CitiesSolutionMEDIUM - Graph
2661584. Min Cost to Connect All PointsSolutionMEDIUM - Graph
2671443. Minimum Time to Collect All Apples in a TreeSolutionMEDIUM - Graph
268743. Network Delay TimeSolutionMEDIUM - Graph
2691514. Path with Maximum ProbabilitySolutionMEDIUM - Graph
270684. Redundant ConnectionSolutionMEDIUM - Graph
2711466. Reorder Routes to Make All Paths Lead to the City ZeroSolutionMEDIUM - Graph
272994. Rotting OrangesSolutionMEDIUM - Graph
273934. Shortest BridgeSolutionMEDIUM - Graph
2741129. Shortest Path with Alternating ColorsSolutionMEDIUM - Graph
275909. Snakes and LaddersSolutionMEDIUM - Graph
276Bathroom ProblemSolutionMEDIUM - Thread
2771115. Print FooBar AlternatelySolutionMEDIUM - Thread
2781115. Print FooBar AlternatelySolutionMEDIUM - Thread
2791115. Print FooBar AlternatelySolutionMEDIUM - Thread
2801116. Print Zero Even OddSolutionMEDIUM - Thread
281134. Gas StationSolutionMEDIUM - Greedy
28245. Jump Game IISolutionMEDIUM - Greedy
2831871. Jump Game VIISolutionMEDIUM - Greedy
28455. Jump GameSolutionMEDIUM - Greedy
285179. Largest NumberSolutionMEDIUM - Greedy
286678. Valid Parenthesis StringSolutionMEDIUM - Greedy
2871029. Two City SchedulingSolutionMEDIUM - Greedy
288307. Range Sum Query - MutableSolutionMEDIUM - Segment Tree
289307. Range Sum Query - MutableSolutionMEDIUM - Segment Tree
290211. Design Add and Search Words Data StructureSolutionMEDIUM - Prefix Tree / Trie
291442. Find All Duplicates in an ArraySolutionMEDIUM - Cyclic sort
292371. Sum of Two IntegersSolutionMEDIUM - Bit Manipulation
2931472. Design Browser HistorySolutionMEDIUM - Generic
2941472. Design Browser HistorySolutionMEDIUM - Generic
2951472. Design Browser HistorySolutionMEDIUM - Generic
2961268. Search Suggestions SystemSolutionMEDIUM - Generic

LeetCode - Hard

IdLeetcodeSolutionType
1273. Integer to English WordsSolutionHARD - Number
242. Trapping Rain WaterSolutionHARD - Number
3472. Concatenated WordsSolutionHARD - String
42306. Naming a CompanySolutionHARD - String
5154. Find Minimum in Rotated Sorted Array IISolutionHARD - String
6295. Find Median from Data StreamSolutionHARD - Map & Set
7460. LFU CacheSolutionHARD - Map & Set
8149. Max Points on a LineSolutionHARD - Map & Set
91383. Maximum Performance of a TeamSolutionHARD - Heap
101851. Minimum Interval to Include Each QuerySolutionHARD - Heap
1176. Minimum Window SubstringSolutionHARD - Sliding window / Two pointer
12239. Sliding Window MaximumSolutionHARD - Sliding window / Two pointer
13312. Burst BalloonsSolutionHARD - DP
141220. Count Vowels PermutationSolutionHARD - DP
1572. Edit DistanceSolutionHARD - DP
1632. Longest Valid ParenthesesSolutionHARD - DP
171547. Minimum Cost to Cut a StickSolutionHARD - DP
181553. Minimum Number of Days to Eat N OrangesSolutionHARD - DP
1952. N-Queens IISolutionHARD - DP
2051. N-QueensSolutionHARD - DP
21920. Number of Music PlaylistsSolutionHARD - DP
22132. Palindrome Partitioning IISolutionHARD - DP
231866. Number of Ways to Rearrange Sticks With K Sticks VisibleSolutionHARD - DP
2410. Regular Expression MatchingSolutionHARD - DP
25691. Stickers to Spell WordSolutionHARD - DP
261406. Stone Game IIISolutionHARD - DP
27140. Word Break IISolutionHARD - DP
2823. Merge k Sorted ListsSolutionHARD - Link List
2925. Reverse Nodes in k-GroupSolutionHARD - Link List
30297. Serialize and Deserialize Binary TreeSolutionHARD - Binary Tree
31124. Binary Tree Maximum Path SumSolutionHARD - Binary Tree
32352. Data Stream as Disjoint IntervalsSolutionHARD - Interval
334. Median of Two Sorted ArraysSolutionHARD - Binary Search
34410. Split Array Largest SumSolutionHARD - Binary Search
35269. Alien DictionarySolutionHARD - Topological Sort
36115. Distinct SubsequencesSolutionHARD - Stack & Monotonic Stack
3784. Largest Rectangle in HistogramSolutionHARD - Stack & Monotonic Stack
38329. Longest Increasing Path in a MatrixSolutionHARD - Stack & Monotonic Stack
391964. Find the Longest Valid Obstacle Course at Each PositionSolutionHARD - Stack & Monotonic Stack
40895. Maximum Frequency StackSolutionHARD - Stack & Monotonic Stack
4185. Maximal RectangleSolutionHARD - Stack & Monotonic Stack
421857. Largest Color Value in a Directed GraphSolutionHARD - Graph
432421. Number of Good PathsSolutionHARD - Graph
44332. Reconstruct ItinerarySolutionHARD - Graph
45778. Swim in Rising WaterSolutionHARD - Graph
46127. Word LadderSolutionHARD - Graph
47212. Word Search IISolutionHARD - Prefix Tree / Trie
4841. First Missing PositiveSolutionHARD - Cyclic sort

Concurrency

IdLeetcodeSolutionType
1Long Adder & Long AccumulatorSolutionMEDIUM
2CallableSolutionEASY
3Create Dead LockSolutionMEDIUM
4Produce ConsumerSolutionEASY
5Produce ConsumerSolutionEASY
6Produce ConsumerSolutionEASY
7SemaphoreSolutionMEDIUM
8ScheduledExecutorServiceSolutionMEDIUM
9Stop ThreadSolutionEASY
10Stop ThreadSolutionEASY
11Print Even OddSolutionEASY
12Thread StarvationSolutionEASY
13Thread Abort PolicySolutionEASY
14Read Write lockSolutionMEDIUM
15ReentrantLockSolutionMEDIUM
16Stamped LockSolutionMEDIUM
17Fork JoinSolutionMEDIUM
18Common WordsSolutionEASY
19Common Words multi threadSolutionMEDIUM
20Concurrent ModificationSolutionEASY
21Cyclic BarrierSolutionMEDIUM
22Count Down LatchSolutionEASY
23Increment ArraySolutionMEDIUM
24PhaserSolutionMEDIUM
25Completable FutureSolutionEASY
26AtomicStampedReferenceSolutionMEDIUM
27AtomicReferenceSolutionMEDIUM
28Implement Custom Thread PoolSolutionMEDIUM
29Implement Custom SemaphoreSolutionMEDIUM
30Parallel StreamSolutionMEDIUM

Java Concurrency

LinkedBlockingQueue (unbounded)

  1. SynchronousQueue - space for only 1
  2. ArrayBlockingQueue (bounded)
  3. DelayQueue - unbounded blocking queue of delayed elements, element can only be taken when its delay has expired.

Thread Pool Size

  1. cpu intensive = num of cores
  2. io intensive = time it takes for IO to complete.
  3. ideal thread pool size = cores * (1 + (wait time/cpu time))

https://youtu.be/ErNre5varF8

Types of ExecutorService

  1. ExecutorService uses BlockingQueue by default
  2. newFixedThreadPool - LinkedBlockingQueue
  3. newSingleThreadExecutor
  4. newCachedThreadPool - SynchronousQueue, dynamically scale the threads to handle the amount of tasks, threads are idle for 60 second, they will be scaled down

Rejection policy

  1. AbortPolicy - This is the default policy. It causes the executor to throw a RejectedExecutionException.
  2. CallerRunsPolicy - the producer thread will be employed to run the task it just submitted. This is effective back pressure.
  3. DiscardOldestPolicy - accept the task and throw away the oldest task in the BlockingQueue
  4. DiscardPolicy - accept the task but silently throw it away
  5. Custom Policy - We can implement the RejectedExecutionHandler interface and provide our own logic to handle

Mutex vs Semaphore

  1. Mutex (or Mutual Exclusion Semaphores) is a locking mechanism used to synchronize access to a resource. Only one task can acquire the mutex. It means there will be ownership associated with mutex, and only the owner can release the lock (mutex).
  2. Semaphore (or Binary Semaphore) is signaling mechanism (“I am done, you can carry on” kind of signal). A binary semaphore is NOT protecting a resource from access. Semaphores are more suitable for some synchronization problems like producer-consumer.

Short version:

  1. Mutex can be released only by the thread that had acquired it.
  2. Binary Semaphore can be signaled by any thread (or process).

Read vs Write lock

Read Lock – if no thread acquired the write lock or requested for it then multiple threads can acquire the read lock Write Lock – if no threads are reading or writing then only one thread can acquire the write lock

Concurrency

  1. CyclicBarrier - CyclicBarriers are used in programs in which we have a fixed number of threads that must wait for each other to reach a common point before continuing execution.
  2. Phaser
  3. CountDownLatch
  4. Exchanger - share objects between two threads of type T
  5. Semaphore
  6. SynchronousQueue

More Questions

  1. ShutdownNow vs Shutdown
  2. Dynamic Striping - Striped64 class
  3. Deadlock vs Livelock
  4. Lock vs Synchronized Block
  5. ReentrantReadWriteLock.ReadLock vs ReentrantReadWriteLock.WriteLock
  6. Stamped lock - optimistic locking
  7. DelayQueue

SQL

Start a Postgres DB

 1docker run -p 5432:5432 --name pg-container -e POSTGRES_PASSWORD=password -d postgres:9.6.10
 2docker ps
 3docker exec -it pg-container psql -U postgres -W postgres
 4CREATE USER test WITH PASSWORD 'test@123';
 5CREATE DATABASE "test-db" WITH OWNER "test" ENCODING UTF8 TEMPLATE template0;
 6grant all PRIVILEGES ON DATABASE "test-db" to test;
 7\c test-db
 8
 9docker stop pg-container
10docker start pg-container

Create the tables & Seed the test data

 1create table department
 2(
 3    id serial not null
 4        constraint department_pk
 5            primary key,
 6    name varchar
 7);
 8
 9alter table department owner to test;
10
11create table employee
12(
13    id serial not null
14        constraint employee_pk
15            primary key,
16    name varchar,
17    salary integer,
18    department_id integer,
19    manager integer,
20    dob date
21);
22
23alter table employee owner to test;
24
25create table project
26(
27    id serial not null
28        constraint project_pk
29            primary key,
30    name varchar
31);
32
33alter table project owner to test;
34
35create table employee_project_mapping
36(
37    id serial not null
38        constraint employee_project_mapping_pk
39            primary key,
40    emp_id integer
41        constraint fk1
42            references employee
43            on update cascade on delete cascade,
44    project_id integer
45        constraint fk2
46            references project
47            on update cascade on delete cascade
48);
49
50alter table employee_project_mapping owner to test;
51
52INSERT INTO department (id, name) VALUES (1, 'IT');
53INSERT INTO department (id, name) VALUES (2, 'Sales');
54INSERT INTO department (id, name) VALUES (3, 'Admin');
55
56INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (1, 'Joe', 85000, 1, 5, '1990-02-10');
57INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (2, 'Henry', 80000, 2, null, '1975-02-10');
58INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (3, 'Sam', 60000, 2, 4, '1975-02-10');
59INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (4, 'Max', 90000, 1, 5, '1981-02-10');
60INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (5, 'Janet', 69000, 1, 1, '1983-02-10');
61INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (6, 'Max', 84000, 1, 1, '2005-02-10');
62INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (7, 'Will', 70000, 1, 1, '1982-02-10');
63INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (8, 'Raj', 65000, null, 1, '1978-02-10');
64INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (9, 'Suresh', 62000, null, 1, '1978-02-10');
65INSERT INTO employee (id, name, salary, department_id, manager, dob) VALUES (10, 'Sam', 61000, 2, 1, '1985-02-10');
66
67INSERT INTO project (id, name) VALUES (1, 'Project 1');
68INSERT INTO project (id, name) VALUES (2, 'Project 2');
69INSERT INTO project (id, name) VALUES (3, 'Project 3');
70INSERT INTO project (id, name) VALUES (4, 'Project 4');
71
72INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (1, 1, 1);
73INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (2, 1, 2);
74INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (3, 3, 3);
75INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (4, 4, 3);
76INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (5, 5, 2);
77INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (6, 6, 1);
78INSERT INTO employee_project_mapping (id, emp_id, project_id) VALUES (7, 7, 2);
  1--SQL Query PostgreSQL
  2
  3--first max salary
  4select distinct salary
  5from employee
  6order by salary desc
  7limit 1;
  8
  9-- https://leetcode.com/problems/second-highest-salary/
 10-- second max salary
 11select distinct salary
 12from employee
 13order by salary desc
 14limit 1 offset 1;
 15
 16-- second max salary
 17select max(salary)
 18from employee
 19where salary < (select max(salary) from employee);
 20
 21-- if 2nd salary doesnt exist show null
 22select NULLIF(
 23               (select distinct salary
 24                from employee
 25                order by salary Desc
 26                limit 1 offset 1), null
 27           ) as SecondHighestSalary;
 28
 29-- https://leetcode.com/problems/department-top-three-salaries/
 30-- top 3 salaries in each department
 31select d.name, e.id, e.name, e.salary
 32from employee e,
 33     department d
 34where e.department_id = d.id
 35  and (
 36          select count(distinct (e2.salary))
 37          from employee e2
 38          where e2.salary > e.salary
 39            and e2.department_id = e.department_id
 40      ) < 3
 41order by (d.name, e.name);
 42
 43--max salary in each department
 44select d.name, max(e.salary)
 45from employee e,
 46     department d
 47where e.department_id = d.id
 48group by d.id;
 49
 50--max salary in each department with employee name
 51select d.name, e.id, e.name, e.salary
 52from employee e,
 53     department d
 54where e.department_id = d.id
 55  and (
 56          select count(distinct (e2.salary))
 57          from employee e2
 58          where e2.salary > e.salary
 59            and e.department_id = e2.department_id
 60      ) < 1
 61order by (d.name, e.name);
 62
 63--find all employee and department they work in, only show employees who have a department assigned.
 64SELECT e.name, d.name
 65FROM employee e
 66         INNER JOIN department d ON e.department_id = d.id;
 67
 68--inner join
 69SELECT e.name, d.name
 70FROM employee e,
 71     department d
 72where e.department_id = d.id;
 73
 74--find all employee who dont have a department
 75SELECT e.name, d.name
 76FROM employee e
 77         LEFT JOIN department d ON e.department_id = d.id
 78where d.name is null;
 79
 80--find max salary in department even if no employee in it.
 81SELECT d.name, max(e.salary)
 82FROM employee e
 83         RIGHT JOIN department d ON e.department_id = d.id
 84GROUP BY d.name;
 85
 86--find department without an employee
 87SELECT d.name, e.name
 88FROM employee e
 89         RIGHT JOIN department d ON e.department_id = d.id
 90where e.name is null;
 91
 92--show all employee and department even if they dont have assignment
 93SELECT e.name, d.name
 94FROM employee e
 95         FULL JOIN department d ON e.department_id = d.id;
 96
 97--find all employees having salary greater than average
 98SELECT e.name, e.salary
 99FROM employee e
100WHERE salary > (SELECT AVG(salary) from employee);
101
102-- find people with same name in same department
103SELECT e.name as emp_name, d.name as department
104FROM employee e,
105     department d
106where e.department_id = d.id
107group by emp_name, department
108having count(*) > 1;
109
110-- find all employees and their manager
111SELECT e.name, m.name
112FROM employee e,
113     employee m
114WHERE e.manager = m.id;
115
116-- find all employees who dont have a manager
117SELECT e.name, m.name
118FROM employee e
119         LEFT JOIN employee m on e.manager = m.id
120WHERE m.name is null;
121
122-- find all employees and their manager, if they dont have manager show null
123SELECT e.name, m.name
124FROM employee e
125         LEFT JOIN employee m on e.manager = m.id;
126
127-- find all employees and the projects they are working in along with department.
128-- one employee can work on multiple projects
129select e.name, d.name department, p.name project
130from employee e,
131     department d,
132     employee_project_mapping m,
133     project p
134where e.department_id = d.id
135  and e.id = m.emp_id
136  and m.project_id = p.id;
137
138-- find employees who age is greater than 25
139select e.name, e.dob, age(CURRENT_DATE, e.dob)
140from employee e
141where EXTRACT(YEAR FROM age(CURRENT_DATE, e.dob)) > 25;
142
143-- find the oldest employee
144select e.id, e.name, max(age(CURRENT_DATE, e.dob)) emp_age
145from employee e group by e.id, e.name
146order by emp_age desc limit 1;
147
148--find the project and number of employees working on it.
149select p.name project, count(*)
150from project p,
151     employee_project_mapping m,
152     employee e
153where p.id = m.project_id
154  and m.emp_id = e.id
155group by project;
156
157--find the projects with no employees
158select p.id, p.name
159from project p
160         left join employee_project_mapping m on p.id = m.project_id
161where m.emp_id is null;
162
163--find the employees with no project
164select e.id, e.name
165from employee e
166         left join employee_project_mapping m on e.id = m.emp_id
167where m.project_id is null;
168
169--oldest person in each department
170select d.name, e.id, e.name, e.dob
171from employee e,
172     department d
173where e.department_id = d.id
174  and (
175          select count(distinct(e2.dob))
176          from employee e2
177          where e.dob > e2.dob
178            and e.department_id = e2.department_id
179      ) < 1
180order by (d.name, e.name);
181
182--current date
183SELECT CURRENT_DATE;
184SELECT extract(year from CURRENT_DATE) as "Year";
185
186--find all employee born between 1980-1990
187select *
188from employee e
189where e.dob between '01-01-1980' and '01-01-1990';
190
191--find all employees who name begins with M
192select *
193from employee
194where name like 'M%';
195
196--find all employees other than Max
197select *
198from employee
199where name <> 'Max';
200
201--find all employees with name of Max
202select *
203from employee
204where name = 'Max';
205
206--find employees who are in project1 and project2
207select e.id, e.name
208from employee e,
209     employee_project_mapping m,
210     project p
211where m.emp_id = e.id
212  and m.project_id = p.id
213  and p.name = 'Project 1'
214INTERSECT
215select e.id, e.name
216from employee e,
217     employee_project_mapping m,
218     project p
219where m.emp_id = e.id
220  and m.project_id = p.id
221  and p.name = 'Project 2';

Youtube Channels

NeetCode

Tushar Roy - Coding Made Simple

References

https://www.youtube.com/c/NeetCode

https://medium.com/interviewnoodle/grokking-leetcode-a-smarter-way-to-prepare-for-coding-interviews-e86d5c9fe4e1

https://designgurus.org/course/grokking-the-coding-interview

https://algs4.cs.princeton.edu/cheatsheet/

https://www.bigocheatsheet.com/

https://seanprashad.com/leetcode-patterns/

https://www.teamblind.com/post/New-Year-Gift---Curated-List-of-Top-75-LeetCode-Questions-to-Save-Your-Time-OaM1orEU

https://walkccc.me/LeetCode/preface/

https://neetcode.io/

comments powered by Disqus