From 3f395901fba06e5f9f7d5f73c4f843e921965169 Mon Sep 17 00:00:00 2001 From: 149ps Date: Sun, 5 Jun 2022 12:15:16 -0700 Subject: [PATCH 01/14] O(nlogn) time and O(n) space using sorting. --- ...Array Such That Maximum Difference Is K.py | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 2294. Partition Array Such That Maximum Difference Is K/2294. Partition Array Such That Maximum Difference Is K.py diff --git a/2294. Partition Array Such That Maximum Difference Is K/2294. Partition Array Such That Maximum Difference Is K.py b/2294. Partition Array Such That Maximum Difference Is K/2294. Partition Array Such That Maximum Difference Is K.py new file mode 100644 index 0000000..06c852c --- /dev/null +++ b/2294. Partition Array Such That Maximum Difference Is K/2294. Partition Array Such That Maximum Difference Is K.py @@ -0,0 +1,45 @@ +""" +You are given an integer array nums and an integer k. You may partition nums into one or more subsequences such that each element in nums appears in exactly one of the subsequences. + +Return the minimum number of subsequences needed such that the difference between the maximum and minimum values in each subsequence is at most k. + +A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. + +Example 1: + +Input: nums = [3,6,1,2,5], k = 2 +Output: 2 +Explanation: +We can partition nums into the two subsequences [3,1,2] and [6,5]. +The difference between the maximum and minimum value in the first subsequence is 3 - 1 = 2. +The difference between the maximum and minimum value in the second subsequence is 6 - 5 = 1. +Since two subsequences were created, we return 2. It can be shown that 2 is the minimum number of subsequences needed. +Example 2: + +Input: nums = [1,2,3], k = 1 +Output: 2 +Explanation: +We can partition nums into the two subsequences [1,2] and [3]. +The difference between the maximum and minimum value in the first subsequence is 2 - 1 = 1. +The difference between the maximum and minimum value in the second subsequence is 3 - 3 = 0. +Since two subsequences were created, we return 2. Note that another optimal solution is to partition nums into the two subsequences [1] and [2,3]. +Example 3: + +Input: nums = [2,2,4,5], k = 0 +Output: 3 +Explanation: +We can partition nums into the three subsequences [2,2], [4], and [5]. +The difference between the maximum and minimum value in the first subsequences is 2 - 2 = 0. +The difference between the maximum and minimum value in the second subsequences is 4 - 4 = 0. +The difference between the maximum and minimum value in the third subsequences is 5 - 5 = 0. +Since three subsequences were created, we return 3. It can be shown that 3 is the minimum number of subsequences needed. +""" +class Solution: + def partitionArray(self, nums: List[int], k: int) -> int: + nums.sort() + min_val,result = -sys.maxsize-1,0 + for num in nums: + if num > min_val + k: + min_val = num + result += 1 + return result \ No newline at end of file From dd786218f4ffe0acff0b1646ce297cb650a27ab5 Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Thu, 8 Jun 2023 22:53:35 -0700 Subject: [PATCH 02/14] O(n) time and O(1) space using linear search --- ...ind Smallest Letter Greater Than Target.py | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 744. Find Smallest Letter Greater Than Target/744. Find Smallest Letter Greater Than Target.py diff --git a/744. Find Smallest Letter Greater Than Target/744. Find Smallest Letter Greater Than Target.py b/744. Find Smallest Letter Greater Than Target/744. Find Smallest Letter Greater Than Target.py new file mode 100644 index 0000000..e18629c --- /dev/null +++ b/744. Find Smallest Letter Greater Than Target/744. Find Smallest Letter Greater Than Target.py @@ -0,0 +1,41 @@ +''' +You are given an array of characters letters that is sorted in non-decreasing order, and a character target. There are at least two different characters in letters. + +Return the smallest character in letters that is lexicographically greater than target. If such a character does not exist, return the first character in letters. + + + +Example 1: + +Input: letters = ["c","f","j"], target = "a" +Output: "c" +Explanation: The smallest character that is lexicographically greater than 'a' in letters is 'c'. +Example 2: + +Input: letters = ["c","f","j"], target = "c" +Output: "f" +Explanation: The smallest character that is lexicographically greater than 'c' in letters is 'f'. +Example 3: + +Input: letters = ["x","x","y","y"], target = "z" +Output: "x" +Explanation: There are no characters in letters that is lexicographically greater than 'z' so we return letters[0]. + + +Constraints: + +2 <= letters.length <= 104 +letters[i] is a lowercase English letter. +letters is sorted in non-decreasing order. +letters contains at least two different characters. +target is a lowercase English letter. +''' +class Solution: + def nextGreatestLetter(self, letters: List[str], target: str) -> str: + result,diff = letters[0],sys.maxsize + for letter in letters: + cur_diff = ord(letter) - ord(target) + if cur_diff > 0 and cur_diff < diff: + diff = cur_diff + result = letter + return result \ No newline at end of file From a70b5f5c4bf59c620682e26317bd6ef6d2b617a8 Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sun, 18 Jun 2023 17:57:18 -0700 Subject: [PATCH 03/14] O(n) time and O(1) space --- .../1732. Find the Highest Altitude.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 1732. Find the Highest Altitude/1732. Find the Highest Altitude.py diff --git a/1732. Find the Highest Altitude/1732. Find the Highest Altitude.py b/1732. Find the Highest Altitude/1732. Find the Highest Altitude.py new file mode 100644 index 0000000..a9d0dd4 --- /dev/null +++ b/1732. Find the Highest Altitude/1732. Find the Highest Altitude.py @@ -0,0 +1,32 @@ +""" +There is a biker going on a road trip. The road trip consists of n + 1 points at different altitudes. The biker starts his trip on point 0 with altitude equal 0. + +You are given an integer array gain of length n where gain[i] is the net gain in altitude between points i​​​​​​ and i + 1 for all (0 <= i < n). Return the highest altitude of a point. + + + +Example 1: + +Input: gain = [-5,1,5,0,-7] +Output: 1 +Explanation: The altitudes are [0,-5,-4,1,1,-6]. The highest is 1. +Example 2: + +Input: gain = [-4,-3,-2,-1,4,3,2] +Output: 0 +Explanation: The altitudes are [0,-4,-7,-9,-10,-6,-3,-1]. The highest is 0. + + +Constraints: + +n == gain.length +1 <= n <= 100 +-100 <= gain[i] <= 100 +""" +class Solution: + def largestAltitude(self, gain: List[int]) -> int: + result,cur = -sys.maxsize-1,0 + for num in gain: + cur += num + result = max(result, cur) + return max(result,0) \ No newline at end of file From f56944b5aa9d4094c9a340fdd08a26dfe70cd976 Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Fri, 12 Jan 2024 19:44:42 -0800 Subject: [PATCH 04/14] O(n) time to build hashmap and O(26) space for building Hashmap --- ...er of Steps to Make Two Strings Anagram.py | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 1347. Minimum Number of Steps to Make Two Strings Anagram/1347. Minimum Number of Steps to Make Two Strings Anagram.py diff --git a/1347. Minimum Number of Steps to Make Two Strings Anagram/1347. Minimum Number of Steps to Make Two Strings Anagram.py b/1347. Minimum Number of Steps to Make Two Strings Anagram/1347. Minimum Number of Steps to Make Two Strings Anagram.py new file mode 100644 index 0000000..7a06e86 --- /dev/null +++ b/1347. Minimum Number of Steps to Make Two Strings Anagram/1347. Minimum Number of Steps to Make Two Strings Anagram.py @@ -0,0 +1,37 @@ +""" +You are given two strings of the same length s and t. In one step you can choose any character of t and replace it with another character. + +Return the minimum number of steps to make t an anagram of s. + +An Anagram of a string is a string that contains the same characters with a different (or the same) ordering. + + + +Example 1: + +Input: s = "bab", t = "aba" +Output: 1 +Explanation: Replace the first 'a' in t with b, t = "bba" which is anagram of s. +Example 2: + +Input: s = "leetcode", t = "practice" +Output: 5 +Explanation: Replace 'p', 'r', 'a', 'i' and 'c' from t with proper characters to make t anagram of s. +Example 3: + +Input: s = "anagram", t = "mangaar" +Output: 0 +Explanation: "anagram" and "mangaar" are anagrams. + + +Constraints: + +1 <= s.length <= 5 * 104 +s.length == t.length +s and t consist of lowercase English letters only. +""" +class Solution: + def minSteps(self, s: str, t: str) -> int: + counter_s = collections.Counter(s) + counter_t = collections.Counter(t) + return sum([val - counter_t[key] if val > counter_t[key] else 0 for key,val in counter_s.items()]) \ No newline at end of file From 5d5504a1f58df19f5521c87ab556b7702354e076 Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sat, 13 Jan 2024 19:11:09 -0800 Subject: [PATCH 05/14] O(n) time and O(n) space using hashmap(Counter) --- ...657. Determine if Two Strings Are Close.py | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 1657. Determine if Two Strings Are Close/1657. Determine if Two Strings Are Close.py diff --git a/1657. Determine if Two Strings Are Close/1657. Determine if Two Strings Are Close.py b/1657. Determine if Two Strings Are Close/1657. Determine if Two Strings Are Close.py new file mode 100644 index 0000000..34d8039 --- /dev/null +++ b/1657. Determine if Two Strings Are Close/1657. Determine if Two Strings Are Close.py @@ -0,0 +1,47 @@ +""" +Two strings are considered close if you can attain one from the other using the following operations: + +Operation 1: Swap any two existing characters. +For example, abcde -> aecdb +Operation 2: Transform every occurrence of one existing character into another existing character, and do the same with the other character. +For example, aacabb -> bbcbaa (all a's turn into b's, and all b's turn into a's) +You can use the operations on either string as many times as necessary. + +Given two strings, word1 and word2, return true if word1 and word2 are close, and false otherwise. + + + +Example 1: + +Input: word1 = "abc", word2 = "bca" +Output: true +Explanation: You can attain word2 from word1 in 2 operations. +Apply Operation 1: "abc" -> "acb" +Apply Operation 1: "acb" -> "bca" +Example 2: + +Input: word1 = "a", word2 = "aa" +Output: false +Explanation: It is impossible to attain word2 from word1, or vice versa, in any number of operations. +Example 3: + +Input: word1 = "cabbba", word2 = "abbccc" +Output: true +Explanation: You can attain word2 from word1 in 3 operations. +Apply Operation 1: "cabbba" -> "caabbb" +Apply Operation 2: "caabbb" -> "baaccc" +Apply Operation 2: "baaccc" -> "abbccc" + + +Constraints: + +1 <= word1.length, word2.length <= 105 +word1 and word2 contain only lowercase English letters. +""" +class Solution: + def closeStrings(self, word1: str, word2: str) -> bool: + count_word1 = collections.Counter(word1) + count_word2 = collections.Counter(word2) + counter1 = collections.Counter(count_word1.values()) + counter2 = collections.Counter(count_word2.values()) + return len(count_word1.keys() - count_word2.keys()) == 0 and len(counter1 - counter2) == 0 \ No newline at end of file From 739893ebdcb524ab5ec9981463ee78145a3b85ad Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sat, 10 Feb 2024 00:11:08 -0800 Subject: [PATCH 06/14] O(n^2) time and O(1) space using concept of expansion around the center. --- .../647. Palindromic Substrings_2.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 647. Palindromic Substrings/647. Palindromic Substrings_2.py diff --git a/647. Palindromic Substrings/647. Palindromic Substrings_2.py b/647. Palindromic Substrings/647. Palindromic Substrings_2.py new file mode 100644 index 0000000..9bc5fe2 --- /dev/null +++ b/647. Palindromic Substrings/647. Palindromic Substrings_2.py @@ -0,0 +1,15 @@ +class Solution: + def dfs(self, left, right,s): + final = 0 + while left >= 0 and right < len(s) and s[left] == s[right]: + left -= 1 + right += 1 + final += 1 + return final + + def countSubstrings(self, s: str) -> int: + result = 0 + for i in range(len(s)): + result += self.dfs(i,i,s) + result += self.dfs(i,i+1,s) + return result \ No newline at end of file From ded3bd4065287e4a722704b4eecdae2654d352ea Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sat, 9 Mar 2024 02:27:41 -0800 Subject: [PATCH 07/14] O(nlogm) time with binary search. M being longer and n being shorter. --- .../2540. Minimum Common Value.py | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 2540. Minimum Common Value/2540. Minimum Common Value.py diff --git a/2540. Minimum Common Value/2540. Minimum Common Value.py b/2540. Minimum Common Value/2540. Minimum Common Value.py new file mode 100644 index 0000000..973be0f --- /dev/null +++ b/2540. Minimum Common Value/2540. Minimum Common Value.py @@ -0,0 +1,47 @@ +""" +Given two integer arrays nums1 and nums2, sorted in non-decreasing order, return the minimum integer common to both arrays. If there is no common integer amongst nums1 and nums2, return -1. + +Note that an integer is said to be common to nums1 and nums2 if both arrays have at least one occurrence of that integer. + + + +Example 1: + +Input: nums1 = [1,2,3], nums2 = [2,4] +Output: 2 +Explanation: The smallest element common to both arrays is 2, so we return 2. +Example 2: + +Input: nums1 = [1,2,3,6], nums2 = [2,3,4,5] +Output: 2 +Explanation: There are two common elements in the array 2 and 3 out of which 2 is the smallest, so 2 is returned. + + +Constraints: + +1 <= nums1.length, nums2.length <= 105 +1 <= nums1[i], nums2[j] <= 109 +Both nums1 and nums2 are sorted in non-decreasing order. +""" +class Solution: + def getCommon(self, nums1: List[int], nums2: List[int]) -> int: + def binary_search(target,nums): + left,right = 0,len(nums)-1 + while left <= right: + mid = left + (right- left)//2 + if nums[mid] == target: return True + elif nums[mid] > target: + right = mid - 1 + else: + left = mid + 1 + return False + if len(nums1) > len(nums2): + for num in nums2: + if binary_search(num,nums1): + return num + return -1 + else: + for num in nums1: + if binary_search(num,nums2): + return num + return -1 \ No newline at end of file From 165b66e1d308c5e688f19ed96ae540870885a47f Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sat, 9 Mar 2024 02:30:32 -0800 Subject: [PATCH 08/14] O(n+m) time using two pointer --- .../2540. Minimum Common Value_1.py | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 2540. Minimum Common Value/2540. Minimum Common Value_1.py diff --git a/2540. Minimum Common Value/2540. Minimum Common Value_1.py b/2540. Minimum Common Value/2540. Minimum Common Value_1.py new file mode 100644 index 0000000..aeac882 --- /dev/null +++ b/2540. Minimum Common Value/2540. Minimum Common Value_1.py @@ -0,0 +1,11 @@ +class Solution: + def getCommon(self, nums1: List[int], nums2: List[int]) -> int: + i, j = 0, 0 + while i < len(nums1) and j < len(nums2): + if nums1[i] < nums2[j]: + i += 1 + elif nums1[i] > nums2[j]: + j += 1 + else: + return nums1[i] + return -1 From 0be02cf357b3c70f0c307c4757d9004f72a3938b Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Wed, 1 May 2024 20:29:04 -0700 Subject: [PATCH 09/14] new files --- ...e Integer That Exists With Its Negative.py | 38 +++++++++++++++ .../349. Intersection of Two Arrays_1.py | 10 ++-- .../791. Custom Sort String.py | 46 +++++++++++++++++++ 3 files changed, 89 insertions(+), 5 deletions(-) create mode 100644 2441. Largest Positive Integer That Exists With Its Negative/2441. Largest Positive Integer That Exists With Its Negative.py create mode 100644 791. Custom Sort String/791. Custom Sort String.py diff --git a/2441. Largest Positive Integer That Exists With Its Negative/2441. Largest Positive Integer That Exists With Its Negative.py b/2441. Largest Positive Integer That Exists With Its Negative/2441. Largest Positive Integer That Exists With Its Negative.py new file mode 100644 index 0000000..af52e44 --- /dev/null +++ b/2441. Largest Positive Integer That Exists With Its Negative/2441. Largest Positive Integer That Exists With Its Negative.py @@ -0,0 +1,38 @@ +""" +Given an integer array nums that does not contain any zeros, find the largest positive integer k such that -k also exists in the array. + +Return the positive integer k. If there is no such integer, return -1. + + + +Example 1: + +Input: nums = [-1,2,-3,3] +Output: 3 +Explanation: 3 is the only valid k we can find in the array. +Example 2: + +Input: nums = [-1,10,6,7,-7,1] +Output: 7 +Explanation: Both 1 and 7 have their corresponding negative values in the array. 7 has a larger value. +Example 3: + +Input: nums = [-10,8,6,7,-2,-3] +Output: -1 +Explanation: There is no a single valid k, we return -1. + + +Constraints: + +1 <= nums.length <= 1000 +-1000 <= nums[i] <= 1000 +nums[i] != 0 +""" +class Solution: + def findMaxK(self, nums: List[int]) -> int: + result = -1 + hset = set(nums) + for num in nums: + if (-1)*num in hset: + result = max(result, num) + return result diff --git a/349. Intersection of Two Arrays/349. Intersection of Two Arrays_1.py b/349. Intersection of Two Arrays/349. Intersection of Two Arrays_1.py index e721779..78d7e7e 100644 --- a/349. Intersection of Two Arrays/349. Intersection of Two Arrays_1.py +++ b/349. Intersection of Two Arrays/349. Intersection of Two Arrays_1.py @@ -1,16 +1,16 @@ class Solution: def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: - i,j = 0,0 nums1.sort() nums2.sort() result = [] + i,j= 0,0 while i < len(nums1) and j < len(nums2): - if nums1[i] > nums2[j]: - j += 1 - elif nums1[i] < nums2[j]: + if nums1[i] < nums2[j]: i += 1 + elif nums1[i] > nums2[j]: + j += 1 else: - if nums1[i] not in result: + if not result or result[-1] != nums1[i]: result.append(nums1[i]) i += 1 j += 1 diff --git a/791. Custom Sort String/791. Custom Sort String.py b/791. Custom Sort String/791. Custom Sort String.py new file mode 100644 index 0000000..1df68cb --- /dev/null +++ b/791. Custom Sort String/791. Custom Sort String.py @@ -0,0 +1,46 @@ +""" +You are given two strings order and s. All the characters of order are unique and were sorted in some custom order previously. + +Permute the characters of s so that they match the order that order was sorted. More specifically, if a character x occurs before a character y in order, then x should occur before y in the permuted string. + +Return any permutation of s that satisfies this property. + + + +Example 1: + +Input: order = "cba", s = "abcd" + +Output: "cbad" + +Explanation: "a", "b", "c" appear in order, so the order of "a", "b", "c" should be "c", "b", and "a". + +Since "d" does not appear in order, it can be at any position in the returned string. "dcba", "cdba", "cbda" are also valid outputs. + +Example 2: + +Input: order = "bcafg", s = "abcd" + +Output: "bcad" + +Explanation: The characters "b", "c", and "a" from order dictate the order for the characters in s. The character "d" in s does not appear in order, so its position is flexible. + +Following the order of appearance in order, "b", "c", and "a" from s should be arranged as "b", "c", "a". "d" can be placed at any position since it's not in order. The output "bcad" correctly follows this rule. Other arrangements like "bacd" or "bcda" would also be valid, as long as "b", "c", "a" maintain their order. +""" +import collections + + +class Solution: + def customSortString(self, order: str, s: str) -> str: + hmap, count = {}, collections.Counter(s) + for i,char in enumerate(order): + hmap[char] = i + j = 0 + result,temp = "","" + for key,val in hmap.items(): + if key in count: + result += count[key] * key + for k,v in count.items(): + if k not in hmap: + temp += k*v + return result + temp \ No newline at end of file From 3b9421612a98c2b321e7b813e3b21079b3670d2f Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Wed, 15 May 2024 19:57:59 -0700 Subject: [PATCH 10/14] new LC --- .../165. Compare Version Numbers.py | 44 ++++++++++++++ .../2331. Evaluate Boolean Binary Tree.py | 58 +++++++++++++++++++ .../791. Custom Sort String.py | 12 ++-- 3 files changed, 108 insertions(+), 6 deletions(-) create mode 100644 165. Compare Version Numbers/165. Compare Version Numbers.py create mode 100644 2331. Evaluate Boolean Binary Tree/2331. Evaluate Boolean Binary Tree.py diff --git a/165. Compare Version Numbers/165. Compare Version Numbers.py b/165. Compare Version Numbers/165. Compare Version Numbers.py new file mode 100644 index 0000000..4e2bd0b --- /dev/null +++ b/165. Compare Version Numbers/165. Compare Version Numbers.py @@ -0,0 +1,44 @@ +""" +Given two version numbers, version1 and version2, compare them. + +Version numbers consist of one or more revisions joined by a dot '.'. Each revision consists of digits and may contain leading zeros. Every revision contains at least one character. Revisions are 0-indexed from left to right, with the leftmost revision being revision 0, the next revision being revision 1, and so on. For example 2.5.33 and 0.1 are valid version numbers. + +To compare version numbers, compare their revisions in left-to-right order. Revisions are compared using their integer value ignoring any leading zeros. This means that revisions 1 and 001 are considered equal. If a version number does not specify a revision at an index, then treat the revision as 0. For example, version 1.0 is less than version 1.1 because their revision 0s are the same, but their revision 1s are 0 and 1 respectively, and 0 < 1. + +Return the following: + +If version1 < version2, return -1. +If version1 > version2, return 1. +Otherwise, return 0. + + +Example 1: + +Input: version1 = "1.01", version2 = "1.001" +Output: 0 +Explanation: Ignoring leading zeroes, both "01" and "001" represent the same integer "1". +Example 2: + +Input: version1 = "1.0", version2 = "1.0.0" +Output: 0 +Explanation: version1 does not specify revision 2, which means it is treated as "0". +Example 3: + +Input: version1 = "0.1", version2 = "1.1" +Output: -1 +Explanation: version1's revision 0 is "0", while version2's revision 0 is "1". 0 < 1, so version1 < version2. +""" +class Solution: + def compareVersion(self, version1: str, version2: str) -> int: + version1_list = version1.split(".") + version2_list = version2.split(".") + for str1, str2 in itertools.zip_longest(version1_list, version2_list): + num1 = int(str1) if str1 else 0 + num2 = int(str2) if str2 else 0 + if num1 > num2: + return 1 + elif num1 < num2: + return -1 + else: + continue + return 0 diff --git a/2331. Evaluate Boolean Binary Tree/2331. Evaluate Boolean Binary Tree.py b/2331. Evaluate Boolean Binary Tree/2331. Evaluate Boolean Binary Tree.py new file mode 100644 index 0000000..91eeb2c --- /dev/null +++ b/2331. Evaluate Boolean Binary Tree/2331. Evaluate Boolean Binary Tree.py @@ -0,0 +1,58 @@ +""" +You are given the root of a full binary tree with the following properties: + +Leaf nodes have either the value 0 or 1, where 0 represents False and 1 represents True. +Non-leaf nodes have either the value 2 or 3, where 2 represents the boolean OR and 3 represents the boolean AND. +The evaluation of a node is as follows: + +If the node is a leaf node, the evaluation is the value of the node, i.e. True or False. +Otherwise, evaluate the node's two children and apply the boolean operation of its value with the children's evaluations. +Return the boolean result of evaluating the root node. + +A full binary tree is a binary tree where each node has either 0 or 2 children. + +A leaf node is a node that has zero children. + + + +Example 1: + + +Input: root = [2,1,3,null,null,0,1] +Output: true +Explanation: The above diagram illustrates the evaluation process. +The AND node evaluates to False AND True = False. +The OR node evaluates to True OR False = True. +The root node evaluates to True, so we return true. +Example 2: + +Input: root = [0] +Output: false +Explanation: The root node is a leaf node and it evaluates to false, so we return false. + + +Constraints: + +The number of nodes in the tree is in the range [1, 1000]. +0 <= Node.val <= 3 +Every node has either 0 or 2 children. +Leaf nodes have a value of 0 or 1. +Non-leaf nodes have a value of 2 or 3. +""" + + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def evaluateTree(self, root: Optional[TreeNode]) -> bool: + if not root.left and not root.right: + return 0 if root.val == 0 else 1 + left = self.evaluateTree(root.left) + right = self.evaluateTree(root.right) + return left | right if root.val == 2 else left & right + + diff --git a/791. Custom Sort String/791. Custom Sort String.py b/791. Custom Sort String/791. Custom Sort String.py index 1df68cb..d115433 100644 --- a/791. Custom Sort String/791. Custom Sort String.py +++ b/791. Custom Sort String/791. Custom Sort String.py @@ -33,14 +33,14 @@ class Solution: def customSortString(self, order: str, s: str) -> str: hmap, count = {}, collections.Counter(s) - for i,char in enumerate(order): + for i, char in enumerate(order): hmap[char] = i j = 0 - result,temp = "","" - for key,val in hmap.items(): + result, temp = "", "" + for key, val in hmap.items(): if key in count: result += count[key] * key - for k,v in count.items(): + for k, v in count.items(): if k not in hmap: - temp += k*v - return result + temp \ No newline at end of file + temp += k * v + return result + temp From f7cdfd75e38fa8501333571bbf2aebf94251c265 Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sun, 19 May 2024 00:08:53 -0700 Subject: [PATCH 11/14] O(n) time and O(logn) space for recursive stack --- ...16. Populating Next Right Pointers in Each Node.py | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/116. Populating Next Right Pointers in Each Node/116. Populating Next Right Pointers in Each Node.py b/116. Populating Next Right Pointers in Each Node/116. Populating Next Right Pointers in Each Node.py index 11ab077..60d401f 100644 --- a/116. Populating Next Right Pointers in Each Node/116. Populating Next Right Pointers in Each Node.py +++ b/116. Populating Next Right Pointers in Each Node/116. Populating Next Right Pointers in Each Node.py @@ -28,16 +28,13 @@ def __init__(self, val, left, right, next): self.next = next """ class Solution: - def connect(self, root: 'Node') -> 'Node': - if not root: - return None - if root.left: - root.left.next = root.right + def connect(self, root: 'Optional[Node]') -> 'Optional[Node]': + if not root: return None if root.right: + if root.left: + root.left.next = root.right if root.next: root.right.next = root.next.left - else: - root.right.next = None self.connect(root.left) self.connect(root.right) return root From 6b95d675d55a3ad50135bc3b71961a096e9c0588 Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sun, 19 May 2024 00:32:28 -0700 Subject: [PATCH 12/14] O(n) time and O(n) using recursive stack --- .../1325. Delete Leaves With a Given Value.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 1325. Delete Leaves With a Given Value/1325. Delete Leaves With a Given Value.py diff --git a/1325. Delete Leaves With a Given Value/1325. Delete Leaves With a Given Value.py b/1325. Delete Leaves With a Given Value/1325. Delete Leaves With a Given Value.py new file mode 100644 index 0000000..4cc6325 --- /dev/null +++ b/1325. Delete Leaves With a Given Value/1325. Delete Leaves With a Given Value.py @@ -0,0 +1,48 @@ +""" +Given a binary tree root and an integer target, delete all the leaf nodes with value target. + +Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and has the value target, it should also be deleted (you need to continue doing that until you cannot). + + + +Example 1: + + + +Input: root = [1,2,3,2,null,2,4], target = 2 +Output: [1,null,3,null,4] +Explanation: Leaf nodes in green with value (target = 2) are removed (Picture in left). +After removing, new nodes become leaf nodes with value (target = 2) (Picture in center). +Example 2: + + + +Input: root = [1,3,3,3,2], target = 3 +Output: [1,3,null,null,2] +Example 3: + + + +Input: root = [1,2,null,2,null,2], target = 2 +Output: [1] +Explanation: Leaf nodes in green with value (target = 2) are removed at each step. + + +Constraints: + +The number of nodes in the tree is in the range [1, 3000]. +1 <= Node.val, target <= 1000 +""" + + +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right +class Solution: + def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: + if root.left: root.left = self.removeLeafNodes(root.left, target) + if root.right: root.right = self.removeLeafNodes(root.right, target) + return None if not root.left and not root.right and root.val == target else root From 7639dd197fbf117a94bf866b76afc501fd37b73a Mon Sep 17 00:00:00 2001 From: Parth Shah Date: Sat, 7 Sep 2024 18:19:07 -0700 Subject: [PATCH 13/14] 3217-> O(n) time and O(n) space using hashset --- ...Nodes From Linked List Present in Array.py | 79 +++++++++++++++++++ .../725. Split Linked List in Parts.py | 63 +++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 3217. Delete Nodes From Linked List Present in Array/3217. Delete Nodes From Linked List Present in Array.py create mode 100644 725. Split Linked List in Parts/725. Split Linked List in Parts.py diff --git a/3217. Delete Nodes From Linked List Present in Array/3217. Delete Nodes From Linked List Present in Array.py b/3217. Delete Nodes From Linked List Present in Array/3217. Delete Nodes From Linked List Present in Array.py new file mode 100644 index 0000000..b4b9fbc --- /dev/null +++ b/3217. Delete Nodes From Linked List Present in Array/3217. Delete Nodes From Linked List Present in Array.py @@ -0,0 +1,79 @@ +""" +You are given an array of integers nums and the head of a linked list. Return the head of the modified linked list after removing all nodes from the linked list that have a value that exists in nums. + + + +Example 1: + +Input: nums = [1,2,3], head = [1,2,3,4,5] + +Output: [4,5] + +Explanation: + + + +Remove the nodes with values 1, 2, and 3. + +Example 2: + +Input: nums = [1], head = [1,2,1,2,1,2] + +Output: [2,2,2] + +Explanation: + + + +Remove the nodes with value 1. + +Example 3: + +Input: nums = [5], head = [1,2,3,4] + +Output: [1,2,3,4] + +Explanation: + + + +No node has value 5. +""" +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next + +class Solution: + def modifiedList(self, nums, head): + hset = set(nums) + temp = ListNode(-100) + temp.next = head + result = temp + while temp.next: + if temp.next.val in hset: + temp.next = temp.next.next + else: + temp = temp.next + return result.next + +head = ListNode(1) +head.next = ListNode(2) +head.next.next = ListNode(3) +head.next.next.next = ListNode(4) +head.next.next.next.next = ListNode(5) + +# Sample input for nums +nums = [1, 2, 3] + +# Create an instance of the Solution class +solution = Solution() + +# Call the modifiedList method, passing both nums and head +result = solution.modifiedList(nums, head) + +# Print the modified linked list +while result: + print(result.val) + result = result.next \ No newline at end of file diff --git a/725. Split Linked List in Parts/725. Split Linked List in Parts.py b/725. Split Linked List in Parts/725. Split Linked List in Parts.py new file mode 100644 index 0000000..ef9ad10 --- /dev/null +++ b/725. Split Linked List in Parts/725. Split Linked List in Parts.py @@ -0,0 +1,63 @@ +""" +Given the head of a singly linked list and an integer k, split the linked list into k consecutive linked list parts. + +The length of each part should be as equal as possible: no two parts should have a size differing by more than one. This may lead to some parts being null. + +The parts should be in the order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal to parts occurring later. + +Return an array of the k parts. + + + +Example 1: + + +Input: head = [1,2,3], k = 5 +Output: [[1],[2],[3],[],[]] +Explanation: +The first element output[0] has output[0].val = 1, output[0].next = null. +The last element output[4] is null, but its string representation as a ListNode is []. +Example 2: + + +Input: head = [1,2,3,4,5,6,7,8,9,10], k = 3 +Output: [[1,2,3,4],[5,6,7],[8,9,10]] +Explanation: +The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts. + + +Constraints: + +The number of nodes in the list is in the range [0, 1000]. +0 <= Node.val <= 1000 +1 <= k <= 50 +""" + + +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def splitListToParts(self, head, k): + count, temp = 0, head + while temp: + temp = temp.next + count += 1 + chunk_size = count // k + extra_part = count % k + cur = head + result = [] + for i in range(k): + part_length = chunk_size + (1 if i < extra_part else 0) + part_head = cur + for j in range(part_length - 1): + if cur: + cur = cur.next + if cur: + next_part = cur.next + cur.next = None + cur = next_part + result.append(part_head) + return result From c18874f28151804de92002b5c256aba152de0766 Mon Sep 17 00:00:00 2001 From: Parth Shah <5869983+149ps@users.noreply.github.com> Date: Sat, 7 Sep 2024 18:31:18 -0700 Subject: [PATCH 14/14] Create static.yml --- .github/workflows/static.yml | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 .github/workflows/static.yml diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml new file mode 100644 index 0000000..f2c9e97 --- /dev/null +++ b/.github/workflows/static.yml @@ -0,0 +1,43 @@ +# Simple workflow for deploying static content to GitHub Pages +name: Deploy static content to Pages + +on: + # Runs on pushes targeting the default branch + push: + branches: ["main"] + + # Allows you to run this workflow manually from the Actions tab + workflow_dispatch: + +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write + +# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. +# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. +concurrency: + group: "pages" + cancel-in-progress: false + +jobs: + # Single deploy job since we're just deploying + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + - name: Setup Pages + uses: actions/configure-pages@v5 + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + # Upload entire repository + path: '.' + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4