PrimerPy
https://www.primerpy.com/
Recent content on PrimerPyHugo -- gohugo.ioen-usTue, 30 Jul 2019 09:27:29 -0400Search
https://www.primerpy.com/search/index.json
Tue, 30 Jul 2019 09:27:29 -0400https://www.primerpy.com/search/index.jsonData Structure and Algorithms Overview
https://www.primerpy.com/post/datastructure/content/overview/
Sat, 27 Jul 2019 17:10:52 -0400https://www.primerpy.com/post/datastructure/content/overview/Below is an overview of data structure and algorithms. I believe they will cover at least 85% of the use case.
There will be more updates/contents added in the future.Queue
https://www.primerpy.com/post/datastructure/content/queue/
Wed, 24 Jul 2019 22:38:27 -0400https://www.primerpy.com/post/datastructure/content/queue/Fundamentals A type of linear data structure Queues’ operations are subset of Arrays Can only add element (tail) from one end and remove element from the other end (head) First in First out Implementation I will implement a stack with the help of the dynamic array I built before Dynamic Array Code class Array: def __init__(self, arr=None, capacity=10): if isinstance(arr, list): self.Stack
https://www.primerpy.com/post/datastructure/content/stack/
Tue, 23 Jul 2019 22:00:01 -0400https://www.primerpy.com/post/datastructure/content/stack/Fundamentals Implementation I will implement a stack with the help of the dynamic array I built before Dynamic Array Code class Array: def __init__(self, arr=None, capacity=10): if isinstance(arr, list): self._data = arr[:] self._size = len(arr) return self._data = [None] * capacity self._size = 0 def get_size(self): return self._size def get_capacity(self): return len(self._data) def is_empty(self): return self._size == 0 def add_last(self, e): self.347. Top K Frequent Elements
https://www.primerpy.com/post/leetcoding/content/347-topkfreqelements/
Sun, 21 Jul 2019 14:34:51 -0400https://www.primerpy.com/post/leetcoding/content/347-topkfreqelements/Problem Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2] Example 2:
Input: nums = [1], k = 1 Output: [1] Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm’s time complexity must be better than O(n log n), where n is the array’s size.112. Path Sum
https://www.primerpy.com/post/leetcoding/content/112-pathsum/
Sat, 20 Jul 2019 20:43:22 -0400https://www.primerpy.com/post/leetcoding/content/112-pathsum/Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.220. Contains Duplicate III
https://www.primerpy.com/post/leetcoding/content/220-containsdumplicate3/
Fri, 19 Jul 2019 21:50:13 -0400https://www.primerpy.com/post/leetcoding/content/220-containsdumplicate3/Problem Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0 Output: true Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2 Output: true Example 3:Dynamic Array
https://www.primerpy.com/post/datastructure/content/dynamicarray/
Thu, 18 Jul 2019 22:34:00 -0400https://www.primerpy.com/post/datastructure/content/dynamicarray/Dynamic Array In Array, I pre-defined the capacity The array’s size need to be smaller than its capacity Now I will define a dynamic array whose capacity will grow or shrink depending on array’s length if size is approaching capacity, grow capacity by 2 if size is approaching 25% of capacity, shrink capacity by 2 Most of the array’s methods will remain the same, just add a new method resize Code class DynamicArray: """ Implement a dynamic array in python """ def __init__(self, data=None, capacity=10): """ Initialization, if data is a type of list(array), copy the conent over; else create a new _data """ if isinstance(data, list): self.257. Binary Tree Paths
https://www.primerpy.com/post/leetcoding/content/257-binarytreepaths/
Thu, 18 Jul 2019 21:31:19 -0400https://www.primerpy.com/post/leetcoding/content/257-binarytreepaths/Problem Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1->2->5", "1->3"] Explanation: All root-to-leaf paths are: 1->2->5, 1->3 Thought Process & White Board
Code class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def binaryTreePaths(self, root): res = [] if root is None: return res if root.19. Remove Nth Node From End of List
https://www.primerpy.com/post/leetcoding/content/19-remove-nth-node-from-end/
Wed, 17 Jul 2019 23:47:43 -0400https://www.primerpy.com/post/leetcoding/content/19-remove-nth-node-from-end/Problem Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Thought Process & White Board
Code class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeFromEnd(self, head, n): assert(n) dummyHead = ListNode(None) dummyHead.Array
https://www.primerpy.com/post/datastructure/content/array/
Tue, 16 Jul 2019 23:21:47 -0400https://www.primerpy.com/post/datastructure/content/array/What are arrays? A data structure that stores data in a continuous space For python, the most commonly used array-like data structure is list For Python, list can hold different types of data To access any element in an array, we can easily use index with time complexity of O(1) Complexity for Python List init O(1) In cpython, the init create a space of 4 to start with.279. Perfect Squares
https://www.primerpy.com/post/leetcoding/content/279-perfectsquares/
Mon, 15 Jul 2019 21:47:07 -0400https://www.primerpy.com/post/leetcoding/content/279-perfectsquares/Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4. Example 2:
Input: n = 13 Output: 2 Explanation: 13 = 4 + 9. Thought Process since 1 is a perfect square, so for any n, there must be a solution, the worst case is n I tried the brute force solution but failed, i.102. Binary Tree Level Order Traversal
https://www.primerpy.com/post/leetcoding/content/102-binarytreelevelordertraversal/
Sun, 14 Jul 2019 19:18:55 -0400https://www.primerpy.com/post/leetcoding/content/102-binarytreelevelordertraversal/Problem Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7 return its level order traversal as:
[ [3], [9,20], [15,7] ] Thought Process This is a typical BFS problem Can solve it with the help of a queue In Python, can use collection.Iterative Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/content/binary-tree-traversal-nr/
Sat, 13 Jul 2019 11:20:41 -0400https://www.primerpy.com/post/datastructure/content/binary-tree-traversal-nr/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] 94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] 145.Preorder, Inorder and Postorder Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/content/binary-tree-traversal/
Fri, 12 Jul 2019 23:55:34 -0400https://www.primerpy.com/post/datastructure/content/binary-tree-traversal/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,2,3] 94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes’ values.
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2] 145.Hash Tables
https://www.primerpy.com/post/datastructure/content/hash-tables/
Fri, 12 Jul 2019 23:55:32 -0400https://www.primerpy.com/post/datastructure/content/hash-tables/Definition What are Hash Tables? Hash Tables are key-value pairs key must be immutable Hash Function Hash functions convert the value to key One big challenge is to calculate the key more evenly to avoid collision One common way is to calculate the mod of a prime number (the number theory is beyond the scope here) but look at two examples below Example 1:237. Delete Node in a Linked List
https://www.primerpy.com/post/leetcoding/content/237-deletenodeinall/
Thu, 11 Jul 2019 12:07:30 -0400https://www.primerpy.com/post/leetcoding/content/237-deletenodeinall/Problem Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list – head = [4,5,1,9], which looks like following:
4->5->1->9 Example 1:
Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 -> 1 -> 9 after calling your function.24. Swap Nodes in Pairs
https://www.primerpy.com/post/leetcoding/content/24-swapnodesinpairs/
Thu, 11 Jul 2019 10:18:34 -0400https://www.primerpy.com/post/leetcoding/content/24-swapnodesinpairs/Problem Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3. Thought Process For every node pair: front and back front’s next will be pointed to the back’s next back’s next will be pointed to the front front’s previous node’s next will be pointed to back Setting up a dummy head node will be helpful White Board Below is the white board:203. Remove Linked List Elements
https://www.primerpy.com/post/leetcoding/content/203-removelinkedlist/
Wed, 10 Jul 2019 23:20:13 -0400https://www.primerpy.com/post/leetcoding/content/203-removelinkedlist/Problem Remove all elements from a linked list of integers that have value val.
Example:
Input: 1->2->6->3->4->5->6, val = 6 Output: 1->2->3->4->5 Thought Process the regular case is simple. e.g. to delete 6 below, we can use a node(delnode) to store 6’s next node
2->6->3 then 2’s next points to delnode’s next node, then 6’s next points to None
The tricky part is the edge case: if the deleted node is None, then return None if the deleted node is head, then delnode = head, delnode.455-AssignCookies
https://www.primerpy.com/post/leetcoding/content/455-assigncookies/
Tue, 09 Jul 2019 22:21:02 -0400https://www.primerpy.com/post/leetcoding/content/455-assigncookies/Problem Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content.70. Climbing Stairs
https://www.primerpy.com/post/leetcoding/content/70-climbingstairs/
Tue, 09 Jul 2019 21:44:40 -0400https://www.primerpy.com/post/leetcoding/content/70-climbingstairs/Problem You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2:226. Invert Binary Tree
https://www.primerpy.com/post/leetcoding/content/226-invertbinarytree/
Mon, 08 Jul 2019 20:55:54 -0400https://www.primerpy.com/post/leetcoding/content/226-invertbinarytree/Problem Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9 Output:
4 / \ 7 2 / \ / \ 9 6 3 1 Thought Process Can solve this question recursively.
if the root is None, return None
else, revert root’s left tree recursively, revert root’s right tree recursively
swap left, right tree
White Board Below is the white board:104. Maximum Depth of Binary Tree
https://www.primerpy.com/post/leetcoding/content/104-maxdepthbinarytree/
Mon, 08 Jul 2019 20:41:28 -0400https://www.primerpy.com/post/leetcoding/content/104-maxdepthbinarytree/Problem Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7 return its depth = 3.
Thought Process Can solve this question recursively.
find the max d for the left tree recursively find the max d for the right tree recursively return the larger d White Board Below is the white board:20. Valid Parentheses
https://www.primerpy.com/post/leetcoding/content/20-validparentheses/
Sun, 07 Jul 2019 11:30:56 -0400https://www.primerpy.com/post/leetcoding/content/20-validparentheses/Problem Given a string containing just the characters ‘(’, ‘)’, ‘{’, ‘}’, ‘[’ and ‘]’, determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true Example 2:
Input: "()[]{}" Output: true Example 3:206. Reverse Linked List
https://www.primerpy.com/post/leetcoding/content/206-reversell/
Sun, 07 Jul 2019 10:08:50 -0400https://www.primerpy.com/post/leetcoding/content/206-reversell/Problem Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL Output: NULL<-1<-2<-3<-4<-5 Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both? Thought Process if to reverse a link list iteratively, need three pointers to store
pre => previous node cur => current node nxt => next node (here nxt is different from node’s own next reference) Iterate thru ll, for any given state:447. Number of Boomerangs
https://www.primerpy.com/post/leetcoding/content/447-numberofboomerangs/
Sat, 06 Jul 2019 18:04:36 -0400https://www.primerpy.com/post/leetcoding/content/447-numberofboomerangs/Problem Given n points in the plane that are all pairwise distinct, a “boomerang” is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range -10000, 10000.454. 4Sum II
https://www.primerpy.com/post/leetcoding/content/454-4sum/
Sat, 06 Jul 2019 13:06:54 -0400https://www.primerpy.com/post/leetcoding/content/454-4sum/Problem Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2**28 to 2**28 - 1 and the result is guaranteed to be at most 2**31 - 1.1. Two Sum
https://www.primerpy.com/post/leetcoding/content/1-twosum/
Sat, 06 Jul 2019 12:14:37 -0400https://www.primerpy.com/post/leetcoding/content/1-twosum/Problem Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. Note:350. Intersection of Two Arrays II
https://www.primerpy.com/post/leetcoding/content/350-intertwoarrays/
Sat, 06 Jul 2019 10:50:21 -0400https://www.primerpy.com/post/leetcoding/content/350-intertwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2] Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9] Note:
Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Thought Process unlike 349, this problem requires each element appear as it shows in original arrays use a dict to store number count, (which I believe is similar to map in C++) for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 if num already exits in count, count[num] += 1 also it’s important to remove the num from nums2 for each iteration to avoid double count return a result that has num (key) * appearance (value) White Board Below is the white board:349. Intersection of Two Arrays
https://www.primerpy.com/post/leetcoding/content/349-intersecttwoarrays/
Fri, 05 Jul 2019 18:58:45 -0400https://www.primerpy.com/post/leetcoding/content/349-intersecttwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2] Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4] Note:
Each element in the result must be unique. The result can be in any order. Thought Process use a dict to store number count for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 for num in nums2, if num exists in nums1 and num does not exist in count, count[num] = 1 return only count keys White Board Below is the white board, and note the 2nd loop is not necessary3. Longest Substring Without Repeating Characters
https://www.primerpy.com/post/leetcoding/content/3-longeststringworepeat/
Fri, 05 Jul 2019 17:59:14 -0400https://www.primerpy.com/post/leetcoding/content/3-longeststringworepeat/Problem Given a string, find the length of the longest substring without repeating characters. Example 1:
Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.209. Minimize Size Subarray Sum
https://www.primerpy.com/post/leetcoding/content/209-minsizesubarraysum/
Fri, 05 Jul 2019 11:02:30 -0400https://www.primerpy.com/post/leetcoding/content/209-minsizesubarraysum/Problem Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn’t one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint. Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).167. Two Sum
https://www.primerpy.com/post/leetcoding/content/167-twosum/
Fri, 05 Jul 2019 08:51:11 -0400https://www.primerpy.com/post/leetcoding/content/167-twosum/Problem Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.75. Sort Colors
https://www.primerpy.com/post/leetcoding/content/75-sortcolors/
Fri, 05 Jul 2019 07:01:23 -0400https://www.primerpy.com/post/leetcoding/content/75-sortcolors/Problem Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library’s sort function for this problem.283. Move Zeros
https://www.primerpy.com/post/leetcoding/content/283-movezeroes/
Thu, 04 Jul 2019 22:10:21 -0400https://www.primerpy.com/post/leetcoding/content/283-movezeroes/Problem Given an array nums, write a func to move all 0 s to the end of it while keeping the relative order of the non-zero elements Must do this in-place without making a copy of array Minimize the total number of operations Thought Process Loop through the whole array filter out non-zeros fill the first part of the array with non-zeros fill the rest with 0 White Board Below is the white board:1. Two Sum
https://www.primerpy.com/post/leetcoding/hashtables/1_twosum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/1_twosum/Problem Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Note: Each element in the result should appear as many times as it shows in both arrays.102. Binary Tree Level Order Traversal
https://www.primerpy.com/post/leetcoding/binarytree/102_binarytreelevelordertraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/102_binarytreelevelordertraversal/Problem Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Thought Process This is a typical BFS problem Can solve it with the help of a queue In Python, can use collection.102. Binary Tree Level Order Traversal
https://www.primerpy.com/post/leetcoding/queue/102_binarytreelevelordertraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/queue/102_binarytreelevelordertraversal/Problem Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example: Given binary tree [3,9,20,null,null,15,7],
Example:
3 / \ 9 20 / \ 15 7
return its level order traversal as:
[ [3], [9,20], [15,7] ]
Thought Process White Board Below is the white board:
Code class ListQueue: # implement Queue based on List def __init__(self): self.array = [] self.104. Maximum Depth of Binary Tree
https://www.primerpy.com/post/leetcoding/binarytree/104_maxdepthbinarytree/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/104_maxdepthbinarytree/Problem Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
Example:
Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its depth = 3.
Thought Process Can solve this question recursively. find the max d for the left tree recursively find the max d for the right tree recursively return the larger d White Board Below is the white board:112. Path Sum
https://www.primerpy.com/post/leetcoding/recursion/112-pathsum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/recursion/112-pathsum/Problem Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
Example:
Given the below binary tree and sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1
return true, as there exist a root-to-leaf path 5-4-11-2 which sum is 22.144-Binary Tree Preorder Traversal
https://www.primerpy.com/post/leetcoding/stack/144_binarytreepreordertraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/stack/144_binarytreepreordertraversal/Problem Given a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
Thought Process Solve it recursively node first left tree right tree White Board Below is the white board:
Code class TN: def __init__(self, x): self.val = x self.left = None self.right = None class Sol: def pre(self, root): res = [] if root: res.167. Two Sum
https://www.primerpy.com/post/leetcoding/arrays/167_twosum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/167_twosum/Problem Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice.17. Letter Combinations of a Phone Number
https://www.primerpy.com/post/leetcoding/recursion/17.lettercombinationsofaphonenumber/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/recursion/17.lettercombinationsofaphonenumber/Problem Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.19. Remove Nth Node From End of List
https://www.primerpy.com/post/leetcoding/linkedlists/19-remove-nth-node-from-end/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/19-remove-nth-node-from-end/Problem Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1-2-3-4-5, and n = 2.
After removing the second node from the end, the linked list becomes 1-2-3-5.
Thought Process & White Board Code class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def removeFromEnd(self, head, n): assert(n) dummyHead = ListNode(None) dummyHead.next = head #initialize p, q = dummyHead, dummyHead for i in range(n+1): assert(q) q = q.20. Valid Parentheses
https://www.primerpy.com/post/leetcoding/stack/20_validparentheses/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/stack/20_validparentheses/Problem Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if: Open brackets must be closed by the same type of brackets. Open brackets must be closed in the correct order. Note that an empty string is also considered valid. Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true203. Remove Linked List Elements
https://www.primerpy.com/post/leetcoding/linkedlists/203_removelinkedlist/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/203_removelinkedlist/Problem Remove all elements from a linked list of integers that have value val.
Example:
Input: 1-2-6-3-4-5-6, val = 6 Output: 1-2-3-4-5
Thought Process the regular case is simple. e.g. to delete 6 below, we can use a node(delnode) to store 6's next node
2-6-3
then 2's next points to delnode's next node, then 6's next points to None
The tricky part is the edge case: if the deleted node is None, then return None if the deleted node is head, then delnode = head, delnode.206. Reverse Linked List
https://www.primerpy.com/post/leetcoding/linkedlists/206_reversell/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/206_reversell/Problem Reverse a singly linked list.
Example:
Input: 1-2-3-4-5-NULL Output: NULLFollow up:
A linked list can be reversed either iteratively or recursively. Could you implement both? Thought Process if to reverse a link list iteratively, need three pointers to store pre = previous node cur = current node nxt = next node (here nxt is different from node's own next reference) Iterate thru ll, for any given state: cur.209. Minimize Size Subarray Sum
https://www.primerpy.com/post/leetcoding/arrays/209_minsizesubarraysum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/209_minsizesubarraysum/Problem Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up: If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).219. Contains Duplicate II
https://www.primerpy.com/post/leetcoding/hashtables/219_containsdup/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/219_containsdup/Problem Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k. Example 1:
Input: nums = [1,2,3,1], k = 3 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1 Output: true
Example 3:
Input: nums = [1,2,3,1,2,3], k = 2 Output: false220. Contains Duplicate III
https://www.primerpy.com/post/leetcoding/binarytree/220-containsdumplicate3/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/220-containsdumplicate3/Problem Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2 Output: true226. Invert Binary Tree
https://www.primerpy.com/post/leetcoding/binarytree/226_invertbinarytree/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/binarytree/226_invertbinarytree/Problem Invert a binary tree.
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
Thought Process Can solve this question recursively. if the root is None, return None else, revert root's left tree recursively, revert root's right tree recursively swap left, right tree White Board Below is the white board:237. Delete Node in a Linked List
https://www.primerpy.com/post/leetcoding/linkedlists/237-deletenodeinall/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/237-deletenodeinall/Problem Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Given linked list -- head = [4,5,1,9], which looks like following:
4-5-1-9
Example 1:
Input: head = [4,5,1,9], node = 5 Output: [4,1,9] Explanation: You are given the second node with value 5, the linked list should become 4 - 1 - 9 after calling your function.
Example 2:24. Swap Nodes in Pairs
https://www.primerpy.com/post/leetcoding/linkedlists/24-swapnodesinpairs/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/linkedlists/24-swapnodesinpairs/Problem Given a linked list, swap every two adjacent nodes and return its head.
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example:
Given 1-2-3-4, you should return the list as 2-1-4-3.
Thought Process For every node pair: front and back front's next will be pointed to the back's next back's next will be pointed to the front front's previous node's next will be pointed to back Setting up a dummy head node will be helpful White Board Below is the white board:257. Binary Tree Paths
https://www.primerpy.com/post/leetcoding/recursion/257-binarytreepaths/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/recursion/257-binarytreepaths/Problem Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
Example:
Input: 1 / \ 2 3 \ 5 Output: ["1-2-5", "1-3"]
Explanation: All root-to-leaf paths are: 1-2-5, 1-3
Thought Process & White Board Code class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def binaryTreePaths(self, root): res = [] if root is None: return res if root.279. Perfect Squares
https://www.primerpy.com/post/leetcoding/graph/279_perfectsquares/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/graph/279_perfectsquares/Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example 1:
Input: n = 12 Output: 3 Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13 Output: 2 Explanation: 13 = 4 + 9.
Thought Process since 1 is a perfect square, so for any n, there must be a solution, the worst case is n I tried the brute force solution but failed, i.283. Move Zeros
https://www.primerpy.com/post/leetcoding/arrays/283_movezeroestemp/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/283_movezeroestemp/Problem Given an array nums, write a func to move all 0 s to the end of it while keeping the relative order of the non-zero elements Must do this in-place without making a copy of array Minimize the total number of operations Thought Process Loop through the whole array filter out non-zeros fill the first part of the array with non-zeros fill the rest with 0 White Board Below is the white board:3. Longest Substring Without Repeating Characters
https://www.primerpy.com/post/leetcoding/arrays/3_longeststringworepeat/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/3_longeststringworepeat/Problem Given a string, find the length of the longest substring without repeating characters. Example 1:
Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "347. Top K Frequent Elements
https://www.primerpy.com/post/leetcoding/queue/347-topkfreqelements/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/queue/347-topkfreqelements/Problem Given a non-empty array of integers, return the k most frequent elements.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2 Output: [1,2]
Example 2:
Input: nums = [1], k = 1 Output: [1]
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. Thought Process and White Board Use a hash-table to count the frequency of each number Sort the hash-table Return the top k elements by value Code class Solution: def _create_ht(self, nums): ht = {} for num in nums: if num in ht: ht[num] += 1 else: ht[num] = 1 return ht def _ord_dict_val(self, my_dict, k): ord_tuples = sorted([(v,k) for (k,v) in my_dict.349. Intersection of Two Arrays
https://www.primerpy.com/post/leetcoding/hashtables/349_intersecttwoarrays/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/349_intersecttwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [9,4]
Note: Each element in the result must be unique. The result can be in any order. Thought Process use a dict to store number count for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 for num in nums2, if num exists in nums1 and num does not exist in count, count[num] = 1 return only count keys White Board Below is the white board:350. Intersection of Two Arrays II
https://www.primerpy.com/post/leetcoding/hashtables/350_intertwoarrays/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/350_intertwoarrays/Problem Given two arrays, write a function to compute their intersection. Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2] Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] Output: [4,9]
Note: Each element in the result should appear as many times as it shows in both arrays. The result can be in any order. Thought Process unlike 349, this problem requires each element appear as it shows in original arrays use a dict to store number count, (which I believe is similar to map in C++) for num in nums1, if num exists in nums2 and num does not exist in count, count[num] = 1 if num already exits in count, count[num] += 1 also it's important to remove the num from nums2 for each iteration to avoid double count return a result that has num (key) * appearance (value) White Board Below is the white board:447. Number of Boomerangs
https://www.primerpy.com/post/leetcoding/hashtables/447_numberofboomerangs/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/447_numberofboomerangs/Problem Given n points in the plane that are all pairwise distinct, a "boomerang" is a tuple of points (i, j, k) such that the distance between i and j equals the distance between i and k (the order of the tuple matters). Find the number of boomerangs. You may assume that n will be at most 500 and coordinates of points are all in the range [-10000, 10000] (inclusive).454. 4Sum II
https://www.primerpy.com/post/leetcoding/hashtables/454_4sum/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/hashtables/454_4sum/Problem Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -2**28 to 2**28 - 1 and the result is guaranteed to be at most 2**31 - 1.455-AssignCookies
https://www.primerpy.com/post/leetcoding/greedy/455-assigncookies/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/greedy/455-assigncookies/Problem Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj = gi, we can assign the cookie j to the child i, and the child i will be content.70. Climbing Stairs
https://www.primerpy.com/post/leetcoding/dynamicprogramming/70.climbingstairs/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/dynamicprogramming/70.climbingstairs/Problem You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. step + 1 step steps Example 2:
Input: 3 Output: 3 Explanation: There are three ways to climb to the top.716. Max Stack
https://www.primerpy.com/post/leetcoding/stack/716-maxstack/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/stack/716-maxstack/Problem Design a max stack that supports push, pop, top, peekMax and popMax.
push(x) -- Push element x onto stack. pop() -- Remove the element on top of the stack and return it. top() -- Get the element on the top. peekMax() -- Retrieve the maximum element in the stack. popMax() -- Retrieve the maximum element in the stack, and remove it. If you find more than one maximum elements, only remove the top-most one.75. Sort Colors
https://www.primerpy.com/post/leetcoding/arrays/75_sortcolors/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/leetcoding/arrays/75_sortcolors/Problem Given an array with n objects colored red, white or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem.About PrimerPy
https://www.primerpy.com/page/about/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/page/about/PrimerPy Primerpy provides a primer on python and related data science topics. It covers all the prerequisites for Deep Learning, Machine Learning, and Artificial Intelligence. It is designated for tech stacks and programming languages used in data science.
So what are those?
Python Python is a clear winner in data science. We cover not only the native Python features, such as loops, functions and objects, but also important libraries such as Numpy, Pandas, Matplotlib, Bokeh, scikit-learn, statsmodels and sqlalchemy etc.Array
https://www.primerpy.com/post/datastructure/array/array/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/array/array/What are arrays? A data structure that stores data in a continuous space For python, the most commonly used array-like data structure is list For Python, list can hold different types of data To access any element in an array, we can easily use index with time complexity of O(1) Complexity for Python List init O(1) In cpython, the init create a space of 4 to start with.Dijkstra
https://www.primerpy.com/post/datastructure/graph/dijkstra/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/graph/dijkstra/What are arrays? A data structure that stores data in a continuous space For python, the most commonly used array-like data structure is list For Python, list can hold different types of data To access any element in an array, we can easily use index with time complexity of O(1) Complexity for Python List init O(1) In cpython, the init create a space of 4 to start with.Dynamic Array
https://www.primerpy.com/post/datastructure/array/dynamicarray/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/array/dynamicarray/Dynamic Array In Array, I pre-defined the capacity The array's size need to be smaller than its capacity Now I will define a dynamic array whose capacity will grow or shrink depending on array's length if size is approaching capacity, grow capacity by 2 if size is approaching 25% of capacity, shrink capacity by 2 Most of the array's methods will remain the same, just add a new method resize Code class DynamicArray: """ Implement a dynamic array in python """ def __init__(self, data=None, capacity=10): """ Initialization, if data is a type of list(array), copy the conent over; else create a new _data """ if isinstance(data, list): self.Hash Tables
https://www.primerpy.com/post/datastructure/hashtables/hashtables/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/hashtables/hashtables/Definition What are Hash Tables? Hash Tables are key-value pairs key must be immutable Hash Function Hash functions convert the value to key One big challenge is to calculate the key more evenly to avoid collision One common way is to calculate the mod of a prime number (the number theory is beyond the scope here) but look at two examples below Example 1:
10 % 4 - 2 20 % 4 - 0 30 % 4 - 2 40 % 4 - 0 50 % 4 - 2Iterative Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/stack/binarytreetraversalnr/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/stack/binarytreetraversalnr/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,2,3]
94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3Overview
https://www.primerpy.com/post/datastructure/array/overview/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/array/overview/Below is an overview of data structure and algorithms. I believe they will cover at least 85% of the use case.Preorder, Inorder and Postorder Traversal for a Binary Tree
https://www.primerpy.com/post/datastructure/recursion/binarytreetraversal/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/recursion/binarytreetraversal/Problems There are three ways to traverse a binary tree: preorder, inorder and postorder.
On Leetcode, there are three problems
144. Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3
Output: [1,2,3]
94. Binary Tree Inorder Traversal Given a binary tree, return the inorder traversal of its nodes' values.
Input: [1,null,2,3] 1 \ 2 / 3Queue
https://www.primerpy.com/post/datastructure/queue/queue/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/queue/queue/Fundamentals Implementation A type of linear data structure Queues' operations are subset of Arrays Can only add element (tail) from one end and remove element from the other end (head) First in First out I will implement a stack with the help of the dynamic array I built before Dynamic Array Code class Array: def __init__(self, arr=None, capacity=10): if isinstance(arr, list): self._data = arr[:] self._size = len(arr) return self.Stack
https://www.primerpy.com/post/datastructure/stack/stack/
Mon, 01 Jan 0001 00:00:00 +0000https://www.primerpy.com/post/datastructure/stack/stack/Fundamentals Implementation I will implement a stack with the help of the dynamic array I built before Dynamic Array Code class Array: def __init__(self, arr=None, capacity=10): if isinstance(arr, list): self._data = arr[:] self._size = len(arr) return self._data = [None] * capacity self._size = 0 def get_size(self): return self._size def get_capacity(self): return len(self._data) def is_empty(self): return self._size == 0 def add_last(self, e): self.add(self._size, e) def add_first(self, e): self.add(0, e) def add(self, index, e): """delete from back to front""" if not 0 <= index <= self.