diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index e308575..0000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "DockerRun.DisableDockerrc": true -} \ No newline at end of file diff --git a/DataBase/Pandas/595_BigCountries/description.md b/DataBase/Pandas/595_BigCountries/description.md deleted file mode 100644 index 90bad21..0000000 --- a/DataBase/Pandas/595_BigCountries/description.md +++ /dev/null @@ -1,54 +0,0 @@ -### 595. Big Countries -|Easy - -SQL Schema -Table: World -``` -+-------------+---------+ -| Column Name | Type | -+-------------+---------+ -| name | varchar | -| continent | varchar | -| area | int | -| population | int | -| gdp | bigint | -+-------------+---------+ -``` -In SQL, name is the primary key column for this table. -Each row of this table gives information about the name of a country, the continent to which it belongs, its area, the population, and its GDP value. - -### A country is big if: - -it has an area of at least three million (i.e., 3000000 km2), or - -it has a population of at least twenty-five million (i.e., 25000000). - -Find the name, population, and area of the big countries. - -Return the result table in any order. - -The result format is in the following example. - - - -Example 1: -``` -Input: -World table: -+-------------+-----------+---------+------------+--------------+ -| name | continent | area | population | gdp | -+-------------+-----------+---------+------------+--------------+ -| Afghanistan | Asia | 652230 | 25500100 | 20343000000 | -| Albania | Europe | 28748 | 2831741 | 12960000000 | -| Algeria | Africa | 2381741 | 37100000 | 188681000000 | -| Andorra | Europe | 468 | 78115 | 3712000000 | -| Angola | Africa | 1246700 | 20609294 | 100990000000 | -+-------------+-----------+---------+------------+--------------+ -Output: -+-------------+------------+---------+ -| name | population | area | -+-------------+------------+---------+ -| Afghanistan | 25500100 | 652230 | -| Algeria | 37100000 | 2381741 | -+-------------+------------+---------+ -``` \ No newline at end of file diff --git a/DataBase/Pandas/595_BigCountries/solution.py b/DataBase/Pandas/595_BigCountries/solution.py deleted file mode 100644 index 5b62eef..0000000 --- a/DataBase/Pandas/595_BigCountries/solution.py +++ /dev/null @@ -1,6 +0,0 @@ -import pandas as pd - -def big_countries(world: pd.DataFrame) -> pd.DataFrame: - - df = world[(world['area'] >= 3000000) | (world['population'] >= 25000000)] - return df[['name', 'population', 'area']] \ No newline at end of file diff --git a/DataStractures/Array101/1004_MaxConsecutiveOnesIII/1004_max_consecutive_onesIII.md b/DataStractures/Array101/1004_MaxConsecutiveOnesIII/1004_max_consecutive_onesIII.md new file mode 100644 index 0000000..663686d --- /dev/null +++ b/DataStractures/Array101/1004_MaxConsecutiveOnesIII/1004_max_consecutive_onesIII.md @@ -0,0 +1,29 @@ +### 1004. Max Consecutive Ones III +|Medium + +Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's. + + + +Example 1: +``` +Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2 +Output: 6 +Explanation: [1,1,1,0,0,1,1,1,1,1,1] +Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. +``` +Example 2: +``` +Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3 +Output: 10 +Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1] +Bolded numbers were flipped from 0 to 1. The longest subarray is underlined. +``` + +### Constraints: + +1 <= nums.length <= 105 + +nums[i] is either 0 or 1. + +0 <= k <= nums.length diff --git a/DataStractures/Array101/1004_MaxConsecutiveOnesIII/solution.py b/DataStractures/Array101/1004_MaxConsecutiveOnesIII/solution.py new file mode 100644 index 0000000..3273304 --- /dev/null +++ b/DataStractures/Array101/1004_MaxConsecutiveOnesIII/solution.py @@ -0,0 +1,9 @@ +class Solution: + def longestOnes(self, nums: list[int], k: int) -> int: + zero, l = 0, 0 + for r, n in enumerate(nums): + zero += n == 0 + if zero > k: + zero -= nums[l] == 0 + l+=1 + return r - l + 1 diff --git a/DataStractures/Array101/1051_HeightChecker/description.md b/DataStractures/Array101/1051_HeightChecker/description.md new file mode 100644 index 0000000..a779cdc --- /dev/null +++ b/DataStractures/Array101/1051_HeightChecker/description.md @@ -0,0 +1,43 @@ +### 1051. Height Checker +|Easy + +A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array expected where expected[i] is the expected height of the ith student in line. + +You are given an integer array heights representing the current order that the students are standing in. Each heights[i] is the height of the ith student in line (0-indexed). + +Return the number of indices where heights[i] != expected[i]. + + + +Example 1: +``` +Input: heights = [1,1,4,2,1,3] +Output: 3 +Explanation: +heights: [1,1,4,2,1,3] +expected: [1,1,1,2,3,4] +Indices 2, 4, and 5 do not match. +``` +Example 2: +``` +Input: heights = [5,1,2,3,4] +Output: 5 +Explanation: +heights: [5,1,2,3,4] +expected: [1,2,3,4,5] +All indices do not match. +``` +Example 3: +``` +Input: heights = [1,2,3,4,5] +Output: 0 +Explanation: +heights: [1,2,3,4,5] +expected: [1,2,3,4,5] +All indices match. +``` + +### Constraints: + +1 <= heights.length <= 100 +1 <= heights[i] <= 100 diff --git a/DataStractures/Array101/1051_HeightChecker/solution.py b/DataStractures/Array101/1051_HeightChecker/solution.py new file mode 100644 index 0000000..ed40ceb --- /dev/null +++ b/DataStractures/Array101/1051_HeightChecker/solution.py @@ -0,0 +1,24 @@ +class Solution: + def heightChecker(self, heights: list[int]) -> int: + + initial_heights =heights.copy() + + for i in range(len(heights)): + min_index=i + + for j in range(i+1, len(heights)): + + if heights[j] None: + """ + Do not return anything, modify arr in-place instead. + """ + n = len(arr) + arr2=[] + + for i in range(len(arr)): + if arr[i]==0: + arr2.append(i) + + k=0 + for i in range(len(arr2)): + arr.insert(arr2[i]+k, 0) + k +=1 + + m= len(arr) + for i in range(m-n): + arr.pop() + + return arr + #Approach 02 + # i = 0 + # while i int: + + counter = 0 + for i in range(len(nums)): + a = str(nums[i]) + b = len(a) + + if b % 2 == 0: + counter += 1 + + return counter \ No newline at end of file diff --git a/DataStractures/Array101/1299_ReplaceElementswithGreatestElementonRightSide/description.md b/DataStractures/Array101/1299_ReplaceElementswithGreatestElementonRightSide/description.md new file mode 100644 index 0000000..8b03936 --- /dev/null +++ b/DataStractures/Array101/1299_ReplaceElementswithGreatestElementonRightSide/description.md @@ -0,0 +1,32 @@ +### 1299. Replace Elements with Greatest Element on Right Side +|Easy + +Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace the last element with -1. + +After doing so, return the array. + + + +Example 1: +``` +Input: arr = [17,18,5,4,6,1] +Output: [18,6,6,6,1,-1] +Explanation: +- index 0 --> the greatest element to the right of index 0 is index 1 (18). +- index 1 --> the greatest element to the right of index 1 is index 4 (6). +- index 2 --> the greatest element to the right of index 2 is index 4 (6). +- index 3 --> the greatest element to the right of index 3 is index 4 (6). +- index 4 --> the greatest element to the right of index 4 is index 5 (1). +- index 5 --> there are no elements to the right of index 5, so we put -1. +``` +Example 2: +``` +Input: arr = [400] +Output: [-1] +Explanation: There are no elements to the right of index 0. +``` + +### Constraints: + +1 <= arr.length <= 104 +1 <= arr[i] <= 105 diff --git a/DataStractures/Array101/1299_ReplaceElementswithGreatestElementonRightSide/solution.py b/DataStractures/Array101/1299_ReplaceElementswithGreatestElementonRightSide/solution.py new file mode 100644 index 0000000..cc2f6a8 --- /dev/null +++ b/DataStractures/Array101/1299_ReplaceElementswithGreatestElementonRightSide/solution.py @@ -0,0 +1,21 @@ +class Solution: + def replaceElements(self, arr: List[int]) -> List[int]: + + # max= arr[len(arr)-1] + # for i in range (len(arr)-1, -1, -1): + # if i == len(arr)-1: + # arr[i]=-1 + # else: + # temp= arr[i] + # arr[i]=max + # if temp>max: + # max=temp + # return arr + #Approach 02 + me,arr[-1] = arr[-1],-1 + + for i in range(len(arr)-2,-1,-1): + arr[i],me = me,max(me,arr[i]) + + return arr + diff --git a/DataStractures/Array101/1346_CheckIfNandItsDoubleExist/description.md b/DataStractures/Array101/1346_CheckIfNandItsDoubleExist/description.md new file mode 100644 index 0000000..0036628 --- /dev/null +++ b/DataStractures/Array101/1346_CheckIfNandItsDoubleExist/description.md @@ -0,0 +1,29 @@ +### 1346. Check If N and Its Double Exist +|Easy + + +Given an array arr of integers, check if there exist two indices i and j such that : +``` +i != j +0 <= i, j < arr.length +arr[i] == 2 * arr[j] +``` + +Example 1: +``` +Input: arr = [10,2,5,3] +Output: true +Explanation: For i = 0 and j = 2, arr[i] == 10 == 2 * 5 == 2 * arr[j] +``` +Example 2: +``` +Input: arr = [3,1,7,11] +Output: false +Explanation: There is no i and j that satisfy the conditions. +``` + +### Constraints: + +2 <= arr.length <= 500 + +-103 <= arr[i] <= 103 diff --git a/DataStractures/Array101/1346_CheckIfNandItsDoubleExist/solution.py b/DataStractures/Array101/1346_CheckIfNandItsDoubleExist/solution.py new file mode 100644 index 0000000..d2f165a --- /dev/null +++ b/DataStractures/Array101/1346_CheckIfNandItsDoubleExist/solution.py @@ -0,0 +1,35 @@ +class Solution: + def checkIfExist(self, arr: list[int]) -> bool: + +##Soltion one:## + +# for i in range(len(arr)): +# for j in range(len(arr)): +# if 2*arr[j]==arr[i] and i!=j: +# return True +# else: +# return False + + +##Solution Two:## + for i in range(len(arr)): + if arr[i]*2 in arr and arr.index(arr[i]*2) != i: + return True + return False + + + +##Solution Three# + # arr.sort() + # for i in range(len(arr)): + # product = arr[i]*2 + # lo,hi = 0,len(arr)-1 + # while lo<=hi: + # mid = (lo+hi)//2 + # if arr[mid]==product and mid!= i: + # return True + # elif arr[mid]= 3 +There exists some index i (0-indexed) with 0 < i < arr.length - 1 such that: +arr[0] < arr[1] < ... < arr[i - 1] < arr[i] +arr[i] > arr[i + 1] > ... > arr[arr.length - 1] +``` +Given an integer array nums​​​, return the minimum number of elements to remove to make nums​​​ a mountain array. + + + +Example 1: +``` +Input: nums = [1,3,1] +Output: 0 +Explanation: The array itself is a mountain array so we do not need to remove any elements. +``` +Example 2: +``` +Input: nums = [2,1,1,5,6,2,3,1] +Output: 3 +Explanation: One solution is to remove the elements at indices 0, 1, and 5, making the array nums = [1,5,6,3,1]. +``` + +### Constraints: + +3 <= nums.length <= 1000 + +1 <= nums[i] <= 109 + +It is guaranteed that you can make a mountain array out of nums. diff --git a/DataStractures/Array101/1671. Minimum Number of Removals to Make Mountain Array/solution.py b/DataStractures/Array101/1671. Minimum Number of Removals to Make Mountain Array/solution.py new file mode 100644 index 0000000..a7d928f --- /dev/null +++ b/DataStractures/Array101/1671. Minimum Number of Removals to Make Mountain Array/solution.py @@ -0,0 +1,23 @@ +class Solution: + def minimumMountainRemovals(self, nums: list[int]) -> int: + N = len(nums) + LIS = [1] * N + LDS = [1] * N + + # Longest Increasing Subsequences from Left + for i in range(N): + for j in range(i): + if nums[j] < nums[i]: + LIS[i] = max(LIS[i], 1 + LIS[j]) + + #Longest Increasing Subsequences from Right + for i in range(N-1,-1,-1): + for j in range(i+1, N): + if nums[j] < nums[i]: + LDS[i] = max(LDS[i], 1 + LDS[j]) + + ans = 1000 + for a,b in zip(LIS, LDS): + if a == 1 or b == 1: continue + else: ans = min(ans, N - a - b + 1) + return ans diff --git a/DataStractures/Array101/1870._MinimumSpeedtoArriveonTime/description.md b/DataStractures/Array101/1870._MinimumSpeedtoArriveonTime/description.md new file mode 100644 index 0000000..fc67e54 --- /dev/null +++ b/DataStractures/Array101/1870._MinimumSpeedtoArriveonTime/description.md @@ -0,0 +1,52 @@ +### 1870. Minimum Speed to Arrive on Time +|Medium + +You are given a floating-point number hour, representing the amount of time you have to reach the office. To commute to the office, you must take n trains in sequential order. You are also given an integer array dist of length n, where dist[i] describes the distance (in kilometers) of the ith train ride. + +Each train can only depart at an integer hour, so you may need to wait in between each train ride. + +For example, if the 1st train ride takes 1.5 hours, you must wait for an additional 0.5 hours before you can depart on the 2nd train ride at the 2 hour mark. +Return the minimum positive integer speed (in kilometers per hour) that all the trains must travel at for you to reach the office on time, or -1 if it is impossible to be on time. + +Tests are generated such that the answer will not exceed 107 and hour will have at most two digits after the decimal point. + + + +Example 1: +``` +Input: dist = [1,3,2], hour = 6 +Output: 1 +Explanation: At speed 1: +- The first train ride takes 1/1 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 1 hour mark. The second train takes 3/1 = 3 hours. +- Since we are already at an integer hour, we depart immediately at the 4 hour mark. The third train takes 2/1 = 2 hours. +- You will arrive at exactly the 6 hour mark. +``` +Example 2: +``` +Input: dist = [1,3,2], hour = 2.7 +Output: 3 +Explanation: At speed 3: +- The first train ride takes 1/3 = 0.33333 hours. +- Since we are not at an integer hour, we wait until the 1 hour mark to depart. The second train ride takes 3/3 = 1 hour. +- Since we are already at an integer hour, we depart immediately at the 2 hour mark. The third train takes 2/3 = 0.66667 hours. +- You will arrive at the 2.66667 hour mark. +``` +Example 3: +``` +Input: dist = [1,3,2], hour = 1.9 +Output: -1 +Explanation: It is impossible because the earliest the third train can depart is at the 2 hour mark. +``` + +### Constraints: + +n == dist.length + +1 <= n <= 105 + +1 <= dist[i] <= 105 + +1 <= hour <= 109 + +There will be at most two digits after the decimal point in hour. \ No newline at end of file diff --git a/DataStractures/Array101/1870._MinimumSpeedtoArriveonTime/solution.py b/DataStractures/Array101/1870._MinimumSpeedtoArriveonTime/solution.py new file mode 100644 index 0000000..f202037 --- /dev/null +++ b/DataStractures/Array101/1870._MinimumSpeedtoArriveonTime/solution.py @@ -0,0 +1,21 @@ +from ast import List +from math import ceil + + +class Solution: + def minSpeedOnTime(self, dist: List[int], hour: float) -> int: + if len(dist) > ceil(hour): return -1 + + def isEnoughSpeed(s): + return sum(ceil(d/s) if i != L else d/s for i, d in enumerate(dist)) <= hour + + l, r, L = 1, 10**7, len(dist)-1 + + while l < r: + speed = (l+r)//2 + if isEnoughSpeed(speed): + r = speed + else: + l = speed + 1 + + return l \ No newline at end of file diff --git a/DataStractures/Array101/1_TwoSum/description.md b/DataStractures/Array101/1_TwoSum/description.md new file mode 100644 index 0000000..c998a31 --- /dev/null +++ b/DataStractures/Array101/1_TwoSum/description.md @@ -0,0 +1,40 @@ +### 1. Two Sum +|Easy + +Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. + +You may assume that each input would have exactly one solution, and you may not use the same element twice. + +You can return the answer in any order. + + + +Example 1: +``` +Input: nums = [2,7,11,15], target = 9 +Output: [0,1] +Explanation: Because nums[0] + nums[1] == 9, we return [0, 1]. +``` +Example 2: +``` +Input: nums = [3,2,4], target = 6 +Output: [1,2] +``` +Example 3: +``` +Input: nums = [3,3], target = 6 +Output: [0,1] +``` + +### Constraints: + +2 <= nums.length <= 104 + +-109 <= nums[i] <= 109 + +-109 <= target <= 109 + +Only one valid answer exists. + + +### Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? \ No newline at end of file diff --git a/DataStractures/Array101/1_TwoSum/solution.py b/DataStractures/Array101/1_TwoSum/solution.py new file mode 100644 index 0000000..9cf5f69 --- /dev/null +++ b/DataStractures/Array101/1_TwoSum/solution.py @@ -0,0 +1,15 @@ +class Solution: + def twoSum(self, nums: list[int], target: int) -> list[int]: + for i in range(len(nums)): + for j in range(i+1, len(nums)): + if nums[j]+nums[i]==target: + return[i,j] + + #approach 02 + # seen ={} + # for i in range(len(nums)): + # diff = target - nums[i] + # if diff in seen: + # return[seen[diff], i] + # else: + # seen[nums[i]] = i diff --git a/DataStractures/Array101/209_MinimumSizeSubarraySum/description.md b/DataStractures/Array101/209_MinimumSizeSubarraySum/description.md new file mode 100644 index 0000000..65c85fc --- /dev/null +++ b/DataStractures/Array101/209_MinimumSizeSubarraySum/description.md @@ -0,0 +1,36 @@ +### 209. Minimum Size Subarray Sum +|Medium + +Given an array of positive integers nums and a positive integer target, return the minimal length of a +subarray + whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. + + + +Example 1: +``` +Input: target = 7, nums = [2,3,1,2,4,3] +Output: 2 +Explanation: The subarray [4,3] has the minimal length under the problem constraint. +``` +Example 2: +``` +Input: target = 4, nums = [1,4,4] +Output: 1 +``` +Example 3: +``` +Input: target = 11, nums = [1,1,1,1,1,1,1,1] +Output: 0 +``` + +### Constraints: + +1 <= target <= 109 + +1 <= nums.length <= 105 + +1 <= nums[i] <= 104 + + +### 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)). \ No newline at end of file diff --git a/DataStractures/Array101/209_MinimumSizeSubarraySum/solution.py b/DataStractures/Array101/209_MinimumSizeSubarraySum/solution.py new file mode 100644 index 0000000..e2c47f7 --- /dev/null +++ b/DataStractures/Array101/209_MinimumSizeSubarraySum/solution.py @@ -0,0 +1,30 @@ +from itertools import permutations +class Solution: + def findEvenNumbers(self, digits: list[int]) -> list[int]: + #approach 01 + return sorted(list({ i*100+j*10+p for i,j,p in permutations(digits,3)if i!=0 and p%2==0})) + + #approach 02 + # res, cnt = [], Counter(digits) + # for i in range(1, 10): + # for j in range(0, 10): + # for k in range(0, 10, 2): + # if cnt[i] > 0 and cnt[j] > (i == j) and cnt[k] > (k == i) + (k == j): + # res.append(i * 100 + j * 10 + k) + # return res + + #approach 03 + # hmap, res = defaultdict(int), [] + # for num in digits: + # hmap[num] += 1 #counting frequency of digits of digits array + + # for num in range(100, 999, 2): #step 2 because we need even numbers + # checker = defaultdict(int) + # for digit in str(num): + # checker[int(digit)] += 1 #counting frequency of digits of num + + # #check if every digit in num is in digits array and its frequency is less than or equal to its frequency in digits array + # if all(map(lambda x: x in hmap and checker[x] <= hmap[x], checker)): + # res.append(num) + + # return res diff --git a/DataStractures/Array101/2141_MaximumRunningTimeofNComputers/description.md b/DataStractures/Array101/2141_MaximumRunningTimeofNComputers/description.md new file mode 100644 index 0000000..d15ae2c --- /dev/null +++ b/DataStractures/Array101/2141_MaximumRunningTimeofNComputers/description.md @@ -0,0 +1,40 @@ +### 2141. Maximum Running Time of N Computers +|Hard + +You have n computers. You are given the integer n and a 0-indexed integer array batteries where the ith battery can run a computer for batteries[i] minutes. You are interested in running all n computers simultaneously using the given batteries. + +Initially, you can insert at most one battery into each computer. After that and at any integer time moment, you can remove a battery from a computer and insert another battery any number of times. The inserted battery can be a totally new battery or a battery from another computer. You may assume that the removing and inserting processes take no time. + +Note that the batteries cannot be recharged. + +Return the maximum number of minutes you can run all the n computers simultaneously. + + + +Example 1: +``` +Input: n = 2, batteries = [3,3,3] +Output: 4 +Explanation: +Initially, insert battery 0 into the first computer and battery 1 into the second computer. +After two minutes, remove battery 1 from the second computer and insert battery 2 instead. Note that battery 1 can still run for one minute. +At the end of the third minute, battery 0 is drained, and you need to remove it from the first computer and insert battery 1 instead. +By the end of the fourth minute, battery 1 is also drained, and the first computer is no longer running. +We can run the two computers simultaneously for at most 4 minutes, so we return 4. +``` +Example 2: +``` +Input: n = 2, batteries = [1,1,1,1] +Output: 2 +Explanation: +Initially, insert battery 0 into the first computer and battery 2 into the second computer. +After one minute, battery 0 and battery 2 are drained so you need to remove them and insert battery 1 into the first computer and battery 3 into the second computer. +After another minute, battery 1 and battery 3 are also drained so the first and second computers are no longer running. +We can run the two computers simultaneously for at most 2 minutes, so we return 2. +``` + +### Constraints: + +1 <= n <= batteries.length <= 105 + +1 <= batteries[i] <= 109 \ No newline at end of file diff --git a/DataStractures/Array101/2141_MaximumRunningTimeofNComputers/solution.py b/DataStractures/Array101/2141_MaximumRunningTimeofNComputers/solution.py new file mode 100644 index 0000000..298cfeb --- /dev/null +++ b/DataStractures/Array101/2141_MaximumRunningTimeofNComputers/solution.py @@ -0,0 +1,14 @@ +from ast import List + + +class Solution: + def maxRunTime(self, n: int, batteries: List[int]) -> int: + batteries.sort() + extra = sum(batteries[:-n]) + batteries = batteries[-n:] + + ans = prefix = 0 + for i, x in enumerate(batteries): + prefix += x + if i+1 < len(batteries) and batteries[i+1]*(i+1) - prefix > extra: return (prefix + extra) // (i+1) + return (prefix + extra) // n \ No newline at end of file diff --git a/DataStractures/Array101/2154_KeepMultiplyingFoundValuesbyTwo/description.md b/DataStractures/Array101/2154_KeepMultiplyingFoundValuesbyTwo/description.md new file mode 100644 index 0000000..e21e43a --- /dev/null +++ b/DataStractures/Array101/2154_KeepMultiplyingFoundValuesbyTwo/description.md @@ -0,0 +1,37 @@ +### 2154. Keep Multiplying Found Values by Two +|Easy + +You are given an array of integers nums. You are also given an integer original which is the first number that needs to be searched for in nums. + +You then do the following steps: + +If original is found in nums, multiply it by two (i.e., set original = 2 * original). +Otherwise, stop the process. +Repeat this process with the new number as long as you keep finding the number. +Return the final value of original. + + + +Example 1: +``` +Input: nums = [5,3,6,1,12], original = 3 +Output: 24 +Explanation: +- 3 is found in nums. 3 is multiplied by 2 to obtain 6. +- 6 is found in nums. 6 is multiplied by 2 to obtain 12. +- 12 is found in nums. 12 is multiplied by 2 to obtain 24. +- 24 is not found in nums. Thus, 24 is returned. +``` +Example 2: +``` +Input: nums = [2,7,9], original = 4 +Output: 4 +Explanation: +- 4 is not found in nums. Thus, 4 is returned. +``` + +### Constraints: + +1 <= nums.length <= 1000 + +1 <= nums[i], original <= 1000 diff --git a/DataStractures/Array101/2154_KeepMultiplyingFoundValuesbyTwo/solution.py b/DataStractures/Array101/2154_KeepMultiplyingFoundValuesbyTwo/solution.py new file mode 100644 index 0000000..5d8949b --- /dev/null +++ b/DataStractures/Array101/2154_KeepMultiplyingFoundValuesbyTwo/solution.py @@ -0,0 +1,10 @@ +from ast import List + + +class Solution: + def findFinalValue(self, nums: List[int], original: int) -> int: + while original in nums: + original = original*2 + else: + return original + #2154 diff --git a/DataStractures/Array101/2164_SortEvenandOddIndicesIndependently/description.md b/DataStractures/Array101/2164_SortEvenandOddIndicesIndependently/description.md new file mode 100644 index 0000000..eb79b05 --- /dev/null +++ b/DataStractures/Array101/2164_SortEvenandOddIndicesIndependently/description.md @@ -0,0 +1,38 @@ +### 2164. Sort Even and Odd Indices Independently +|Easy + +You are given a 0-indexed integer array nums. Rearrange the values of nums according to the following rules: + +Sort the values at odd indices of nums in non-increasing order. +For example, if nums = [4,1,2,3] before this step, it becomes [4,3,2,1] after. The values at odd indices 1 and 3 are sorted in non-increasing order. +Sort the values at even indices of nums in non-decreasing order. +For example, if nums = [4,1,2,3] before this step, it becomes [2,1,4,3] after. The values at even indices 0 and 2 are sorted in non-decreasing order. +Return the array formed after rearranging the values of nums. + + + +Example 1: +``` +Input: nums = [4,1,2,3] +Output: [2,3,4,1] +Explanation: +First, we sort the values present at odd indices (1 and 3) in non-increasing order. +So, nums changes from [4,1,2,3] to [4,3,2,1]. +Next, we sort the values present at even indices (0 and 2) in non-decreasing order. +So, nums changes from [4,1,2,3] to [2,3,4,1]. +Thus, the array formed after rearranging the values is [2,3,4,1]. +``` +Example 2: +``` +Input: nums = [2,1] +Output: [2,1] +Explanation: +Since there is exactly one odd index and one even index, no rearrangement of values takes place. +The resultant array formed is [2,1], which is the same as the initial array. +``` + +### Constraints: + +1 <= nums.length <= 100 + +1 <= nums[i] <= 100 diff --git a/DataStractures/Array101/2164_SortEvenandOddIndicesIndependently/solution.py b/DataStractures/Array101/2164_SortEvenandOddIndicesIndependently/solution.py new file mode 100644 index 0000000..63a27ce --- /dev/null +++ b/DataStractures/Array101/2164_SortEvenandOddIndicesIndependently/solution.py @@ -0,0 +1,39 @@ +from ast import List +from audioop import add +from functools import reduce +from itertools import zip_longest + + +class Solution: + def sortEvenOdd(self, nums: List[int]) -> List[int]: + # odds=[] + # evens=[] + # answer=[] + # for i in range(len(nums)): + # if i%2 == 0: + # evens.append(nums[i]) + # else: + # odds.append(nums[i]) + # evens.sort() + # odds.sort() + # odds=odds[::-1] + # odd_idx , even_idx = 0 , 0 + + # for i in range(len(nums)): + + # if i %2 ==0: + # answer.insert(i,evens[even_idx]) + # even_idx +=1 + # else: + # answer.insert(i,odds[odd_idx]) + # odd_idx +=1 + # return answer + + #Approach 02 + return reduce(add, zip_longest(sorted(nums[::2]), sorted(nums[1::2], reverse=True)))[:-1 if len(nums) % 2 else None] + #Explain: + # evens = sorted(nums[::2]) + # odds = sorted(nums[1::2], reverse=True) + # # \U0001f813 Made flat zip(), see stackoverflow.com/questions/61943924/python-flat-zip + # total = [num for num in chain.from_iterable(itertools.zip_longest(evens, odds)) if num is not None] + # diff --git a/DataStractures/Array101/2215_FindtheDifferenceofTwoArrays/description.md b/DataStractures/Array101/2215_FindtheDifferenceofTwoArrays/description.md new file mode 100644 index 0000000..7e651e0 --- /dev/null +++ b/DataStractures/Array101/2215_FindtheDifferenceofTwoArrays/description.md @@ -0,0 +1,33 @@ +### 2215. Find the Difference of Two Arrays +|Easy + +Given two 0-indexed integer arrays nums1 and nums2, return a list answer of size 2 where: + +answer[0] is a list of all distinct integers in nums1 which are not present in nums2. +answer[1] is a list of all distinct integers in nums2 which are not present in nums1. +Note that the integers in the lists may be returned in any order. + + + +Example 1: +``` +Input: nums1 = [1,2,3], nums2 = [2,4,6] +Output: [[1,3],[4,6]] +Explanation: +For nums1, nums1[1] = 2 is present at index 0 of nums2, whereas nums1[0] = 1 and nums1[2] = 3 are not present in nums2. Therefore, answer[0] = [1,3]. +For nums2, nums2[0] = 2 is present at index 1 of nums1, whereas nums2[1] = 4 and nums2[2] = 6 are not present in nums2. Therefore, answer[1] = [4,6]. +``` +Example 2: +``` +Input: nums1 = [1,2,3,3], nums2 = [1,1,2,2] +Output: [[3],[]] +Explanation: +For nums1, nums1[2] and nums1[3] are not present in nums2. Since nums1[2] == nums1[3], their value is only included once and answer[0] = [3]. +Every integer in nums2 is present in nums1. Therefore, answer[1] = []. +``` + +### Constraints: + +1 <= nums1.length, nums2.length <= 1000 + +-1000 <= nums1[i], nums2[i] <= 1000 diff --git a/DataStractures/Array101/2215_FindtheDifferenceofTwoArrays/solution.py b/DataStractures/Array101/2215_FindtheDifferenceofTwoArrays/solution.py new file mode 100644 index 0000000..7e28403 --- /dev/null +++ b/DataStractures/Array101/2215_FindtheDifferenceofTwoArrays/solution.py @@ -0,0 +1,22 @@ +from ast import List + + +class Solution: + def findDifference(self, nums1: List[int], nums2: List[int]) -> List[List[int]]: + # ans=[] + # temp = [] + # temp_2 = [] + + # for n in nums1: + # if n not in nums2 and n not in temp: + + # temp.append(n) + + # for m in nums2: + # if m not in nums1 and m not in temp_2 : + # temp_2.append(m) + # ans.append(temp) + # ans.append(temp_2) + # return ans + #approach 02 + return [set(nums1)-set(nums2),set(nums2)-set(nums1)] diff --git a/DataStractures/Array101/2231_LargestNumberAfterDigitSwapsbyParity/description.md b/DataStractures/Array101/2231_LargestNumberAfterDigitSwapsbyParity/description.md new file mode 100644 index 0000000..913c4aa --- /dev/null +++ b/DataStractures/Array101/2231_LargestNumberAfterDigitSwapsbyParity/description.md @@ -0,0 +1,30 @@ +### 2231. Largest Number After Digit Swaps by Parity +|Easy + +You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits). + +Return the largest possible value of num after any number of swaps. + + + +Example 1: +``` +Input: num = 1234 +Output: 3412 +Explanation: Swap the digit 3 with the digit 1, this results in the number 3214. +Swap the digit 2 with the digit 4, this results in the number 3412. +Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number. +Also note that we may not swap the digit 4 with the digit 1 since they are of different parities. +``` +Example 2: +``` +Input: num = 65875 +Output: 87655 +Explanation: Swap the digit 8 with the digit 6, this results in the number 85675. +Swap the first digit 5 with the digit 7, this results in the number 87655. +Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number. +``` + +### Constraints: + +1 <= num <= 109 \ No newline at end of file diff --git a/DataStractures/Array101/2231_LargestNumberAfterDigitSwapsbyParity/solution.py b/DataStractures/Array101/2231_LargestNumberAfterDigitSwapsbyParity/solution.py new file mode 100644 index 0000000..0cbdf29 --- /dev/null +++ b/DataStractures/Array101/2231_LargestNumberAfterDigitSwapsbyParity/solution.py @@ -0,0 +1,19 @@ +class Solution: + def largestInteger(self, num: int) -> int: + n = len(str(num)) + digit_list = [int(i) for i in str(num)] + + odds=[] + evens=[] + + for i in digit_list: + if i%2 == 0: + evens.append(i) + else: + odds.append(i) + + odds.sort() + evens.sort() + + ans = [odds.pop() if digit_list[d]%2 else evens.pop() for d in range(n)] + return (sum([d*10**(len(ans)-i-1) for i,d in enumerate(ans)])) diff --git a/DataStractures/Array101/2441_LargestPositiveIntegerThatExistsWithItsNegative/description.md b/DataStractures/Array101/2441_LargestPositiveIntegerThatExistsWithItsNegative/description.md new file mode 100644 index 0000000..b37758c --- /dev/null +++ b/DataStractures/Array101/2441_LargestPositiveIntegerThatExistsWithItsNegative/description.md @@ -0,0 +1,35 @@ +### 2441. Largest Positive Integer That Exists With Its Negative +Easy + +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 \ No newline at end of file diff --git a/DataStractures/Array101/2441_LargestPositiveIntegerThatExistsWithItsNegative/solution.py b/DataStractures/Array101/2441_LargestPositiveIntegerThatExistsWithItsNegative/solution.py new file mode 100644 index 0000000..accf385 --- /dev/null +++ b/DataStractures/Array101/2441_LargestPositiveIntegerThatExistsWithItsNegative/solution.py @@ -0,0 +1,26 @@ +from ast import List + + +class Solution: + def findMaxK(self, nums: List[int]) -> int: + #Approach 01 + # max_init = -1 + # for i in range(len(nums)): + # if -nums[i] in (nums): + # max_init = max(max_init, abs(nums[i])) + # return max_init + #Approach 02 + dict1 = {} + res = [] + for i in nums : + if abs(i) in dict1.keys() : + if dict1[abs(i)] + i == 0 : + res.append(abs(i)) + else: + dict1.update({abs(i) : i}) + if res : + return max(res) + else : + return -1 + #Approach 03 + # return max([-1] + [x for x in nums if x > 0 and -x in nums]) diff --git a/DataStractures/Array101/2460_ApplyOperationstoanArray/description.md b/DataStractures/Array101/2460_ApplyOperationstoanArray/description.md new file mode 100644 index 0000000..24fad54 --- /dev/null +++ b/DataStractures/Array101/2460_ApplyOperationstoanArray/description.md @@ -0,0 +1,42 @@ +### 2460. Apply Operations to an Array +|Easy + +You are given a 0-indexed array nums of size n consisting of non-negative integers. + +You need to apply n - 1 operations to this array where, in the ith operation (0-indexed), you will apply the following on the ith element of nums: + +If nums[i] == nums[i + 1], then multiply nums[i] by 2 and set nums[i + 1] to 0. Otherwise, you skip this operation. +After performing all the operations, shift all the 0's to the end of the array. + +For example, the array [1,0,2,0,0,1] after shifting all its 0's to the end, is [1,2,1,0,0,0]. +Return the resulting array. + +Note that the operations are applied sequentially, not all at once. + + + +Example 1: +``` +Input: nums = [1,2,2,1,1,0] +Output: [1,4,2,0,0,0] +Explanation: We do the following operations: +- i = 0: nums[0] and nums[1] are not equal, so we skip this operation. +- i = 1: nums[1] and nums[2] are equal, we multiply nums[1] by 2 and change nums[2] to 0. The array becomes [1,4,0,1,1,0]. +- i = 2: nums[2] and nums[3] are not equal, so we skip this operation. +- i = 3: nums[3] and nums[4] are equal, we multiply nums[3] by 2 and change nums[4] to 0. The array becomes [1,4,0,2,0,0]. +- i = 4: nums[4] and nums[5] are equal, we multiply nums[4] by 2 and change nums[5] to 0. The array becomes [1,4,0,2,0,0]. + +After that, we shift the 0's to the end, which gives the array [1,4,2,0,0,0]. +``` +Example 2: +``` +Input: nums = [0,1] +Output: [1,0] +Explanation: No operation can be applied, we just shift the 0 to the end. +``` + +### Constraints: + +2 <= nums.length <= 2000 + +0 <= nums[i] <= 1000 \ No newline at end of file diff --git a/DataStractures/Array101/2460_ApplyOperationstoanArray/solution.py b/DataStractures/Array101/2460_ApplyOperationstoanArray/solution.py new file mode 100644 index 0000000..b506495 --- /dev/null +++ b/DataStractures/Array101/2460_ApplyOperationstoanArray/solution.py @@ -0,0 +1,15 @@ +class Solution: + def applyOperations(self, nums: list[int]) -> list[int]: + + for i in range(len(nums)-1): + if nums[i]==nums[i+1]: + nums[i]=2*nums[i] + nums[i+1]=0 + else: + continue + + for i in range(len(nums)): + if nums[i]==0: + nums.remove(0) + nums.append( 0) + return nums diff --git a/DataStractures/Array101/2516_TakeKofEachCharacterFromLeftandRight/description.md b/DataStractures/Array101/2516_TakeKofEachCharacterFromLeftandRight/description.md new file mode 100644 index 0000000..9baafe4 --- /dev/null +++ b/DataStractures/Array101/2516_TakeKofEachCharacterFromLeftandRight/description.md @@ -0,0 +1,33 @@ +### 2516. Take K of Each Character From Left and Right +|Medium + +You are given a string s consisting of the characters 'a', 'b', and 'c' and a non-negative integer k. Each minute, you may take either the leftmost character of s, or the rightmost character of s. + +Return the minimum number of minutes needed for you to take at least k of each character, or return -1 if it is not possible to take k of each character. + + + +Example 1: +``` +Input: s = "aabaaaacaabc", k = 2 +Output: 8 +Explanation: +Take three characters from the left of s. You now have two 'a' characters, and one 'b' character. +Take five characters from the right of s. You now have four 'a' characters, two 'b' characters, and two 'c' characters. +A total of 3 + 5 = 8 minutes is needed. +It can be proven that 8 is the minimum number of minutes needed. +``` +Example 2: +``` +Input: s = "a", k = 1 +Output: -1 +Explanation: It is not possible to take one 'b' or 'c' so return -1. +``` + +### Constraints: + +1 <= s.length <= 105 + +s consists of only the letters 'a', 'b', and 'c'. + +0 <= k <= s.length diff --git a/DataStractures/Array101/2516_TakeKofEachCharacterFromLeftandRight/solution.py b/DataStractures/Array101/2516_TakeKofEachCharacterFromLeftandRight/solution.py new file mode 100644 index 0000000..4ea1bf5 --- /dev/null +++ b/DataStractures/Array101/2516_TakeKofEachCharacterFromLeftandRight/solution.py @@ -0,0 +1,41 @@ +import collections + +class Solution: + def takeCharacters(self, s: str, k: int) -> int: + #Approach01 + # create count dic + count = collections.Counter(s) + + # any char is not enough + if count['a'] < k or count['b'] < k or count['c'] < k: + return -1 + + # sliding window + res = len(s) + l = 0 + for r in range(len(s)): + # update count + count[s[r]] -= 1 + # if freq not enough for the remaining string + while l <= r and (count['a'] < k or count['b'] < k or count['c'] < k): + count[s[l]] += 1 + l += 1 + # update valid res + res = min(res, count['a'] + count['b'] + count['c']) + return res + + #Approach 02 + # limits = {c: s.count(c) - k for c in 'abc'} + # if any(x < 0 for x in limits.values()): + # return -1 + + # cnts = {c: 0 for c in 'abc'} + # ans = l = 0 + # for r, c in enumerate(s): + # cnts[c] += 1 + # while cnts[c] > limits[c]: + # cnts[s[l]] -= 1 + # l += 1 + # ans = max(ans, r - l + 1) + + # return len(s) - ans diff --git a/DataStractures/Array101/2615_SumofDistances/description.md b/DataStractures/Array101/2615_SumofDistances/description.md new file mode 100644 index 0000000..1b59bda --- /dev/null +++ b/DataStractures/Array101/2615_SumofDistances/description.md @@ -0,0 +1,32 @@ +### 2615. Sum of Distances +|Medium + +You are given a 0-indexed integer array nums. There exists an array arr of length nums.length, where arr[i] is the sum of |i - j| over all j such that nums[j] == nums[i] and j != i. If there is no such j, set arr[i] to be 0. + +Return the array arr. + + + +Example 1: +``` +Input: nums = [1,3,1,1,2] +Output: [5,0,3,4,0] +Explanation: +When i = 0, nums[0] == nums[2] and nums[0] == nums[3]. Therefore, arr[0] = |0 - 2| + |0 - 3| = 5. +When i = 1, arr[1] = 0 because there is no other index with value 3. +When i = 2, nums[2] == nums[0] and nums[2] == nums[3]. Therefore, arr[2] = |2 - 0| + |2 - 3| = 3. +When i = 3, nums[3] == nums[0] and nums[3] == nums[2]. Therefore, arr[3] = |3 - 0| + |3 - 2| = 4. +When i = 4, arr[4] = 0 because there is no other index with value 2. +``` +Example 2: +``` +Input: nums = [0,5,3] +Output: [0,0,0] +Explanation: Since each element in nums is distinct, arr[i] = 0 for all i. +``` + +### Constraints: + +1 <= nums.length <= 105 + +0 <= nums[i] <= 109 \ No newline at end of file diff --git a/DataStractures/Array101/2615_SumofDistances/solution.py b/DataStractures/Array101/2615_SumofDistances/solution.py new file mode 100644 index 0000000..a15ea97 --- /dev/null +++ b/DataStractures/Array101/2615_SumofDistances/solution.py @@ -0,0 +1,23 @@ +from collections import defaultdict + + +class Solution: + def distance(self, nums: list[int]) -> list[int]: + + mp=defaultdict(list) + for i,j in enumerate(nums): + mp[j].append(i) + + ans=[0]*len(nums) + for k,v in mp.items(): + perfix_sum=0 + perfix_len=0 + suffix_sum=sum(v) + suffix_len=len(v) + for i in v : + perfix_sum+=i + perfix_len+=1 + suffix_sum-=i + suffix_len-=1 + ans[i]=(-perfix_sum+perfix_len*i-suffix_len*i+suffix_sum) + return ans diff --git a/DataStractures/Array101/26_RemoveDuplicatesfromSortedArray/description.md b/DataStractures/Array101/26_RemoveDuplicatesfromSortedArray/description.md new file mode 100644 index 0000000..71ce6fe --- /dev/null +++ b/DataStractures/Array101/26_RemoveDuplicatesfromSortedArray/description.md @@ -0,0 +1,48 @@ +### 26. Remove Duplicates from Sorted Array +|Easy + +Given an integer array nums sorted in non-decreasing order, remove the duplicates in-place such that each unique element appears only once. The relative order of the elements should be kept the same. Then return the number of unique elements in nums. + +Consider the number of unique elements of nums to be k, to get accepted, you need to do the following things: + +Change the array nums such that the first k elements of nums contain the unique elements in the order they were present in nums initially. The remaining elements of nums are not important as well as the size of nums. +Return k. +Custom Judge: + +The judge will test your solution with the following code: +``` +int[] nums = [...]; // Input array +int[] expectedNums = [...]; // The expected answer with correct length + +int k = removeDuplicates(nums); // Calls your implementation + +assert k == expectedNums.length; +for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; +} +If all assertions pass, then your solution will be accepted. +``` + + +Example 1: +```` +Input: nums = [1,1,2] +Output: 2, nums = [1,2,_] +Explanation: Your function should return k = 2, with the first two elements of nums being 1 and 2 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). +``` +Example 2: +``` +Input: nums = [0,0,1,1,1,2,2,3,3,4] +Output: 5, nums = [0,1,2,3,4,_,_,_,_,_] +Explanation: Your function should return k = 5, with the first five elements of nums being 0, 1, 2, 3, and 4 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). +``` + +### Constraints: + +1 <= nums.length <= 3 * 104 + +-100 <= nums[i] <= 100 + +nums is sorted in non-decreasing order. \ No newline at end of file diff --git a/DataStractures/Array101/26_RemoveDuplicatesfromSortedArray/solution.py b/DataStractures/Array101/26_RemoveDuplicatesfromSortedArray/solution.py new file mode 100644 index 0000000..50f58bf --- /dev/null +++ b/DataStractures/Array101/26_RemoveDuplicatesfromSortedArray/solution.py @@ -0,0 +1,10 @@ +class Solution: + + def removeDuplicates(self, nums: list[int]) -> int: + + unique_count = 1 + for i in range(1, len(nums)): + if nums[i-1] != nums[i]: + nums[unique_count] = nums[i] + unique_count += 1 + return unique_count \ No newline at end of file diff --git a/DataStractures/Array101/2733_NeitherMinimumnorMaximum/description.md b/DataStractures/Array101/2733_NeitherMinimumnorMaximum/description.md new file mode 100644 index 0000000..27ba0da --- /dev/null +++ b/DataStractures/Array101/2733_NeitherMinimumnorMaximum/description.md @@ -0,0 +1,35 @@ +### 2733. Neither Minimum nor Maximum +|Easy + +Given an integer array nums containing distinct positive integers, find and return any number from the array that is neither the minimum nor the maximum value in the array, or -1 if there is no such number. + +Return the selected integer. + + + +Example 1: +``` +Input: nums = [3,2,1,4] +Output: 2 +Explanation: In this example, the minimum value is 1 and the maximum value is 4. Therefore, either 2 or 3 can be valid answers. +``` +Example 2: +``` +Input: nums = [1,2] +Output: -1 +Explanation: Since there is no number in nums that is neither the maximum nor the minimum, we cannot select a number that satisfies the given condition. Therefore, there is no answer. +``` +Example 3: +``` +Input: nums = [2,1,3] +Output: 2 +Explanation: Since 2 is neither the maximum nor the minimum value in nums, it is the only valid answer. +``` + +### Constraints: + +1 <= nums.length <= 100 + +1 <= nums[i] <= 100 + +All values in nums are distinct \ No newline at end of file diff --git a/DataStractures/Array101/2733_NeitherMinimumnorMaximum/solution.py b/DataStractures/Array101/2733_NeitherMinimumnorMaximum/solution.py new file mode 100644 index 0000000..96b345c --- /dev/null +++ b/DataStractures/Array101/2733_NeitherMinimumnorMaximum/solution.py @@ -0,0 +1,11 @@ +from ast import List + + +class Solution: + def findNonMinOrMax(self, nums: List[int]) -> int: + # if len(nums)<3: + # return -1 + # nums.remove(max(nums)) + # nums.remove(min(nums)) + # return(nums[0]) + return -1 if len(nums) < 3 else sum(nums[:3]) - min(nums[:3]) - max(nums[:3]) diff --git a/DataStractures/Array101/27_RemoveElement/description.md b/DataStractures/Array101/27_RemoveElement/description.md new file mode 100644 index 0000000..d47a127 --- /dev/null +++ b/DataStractures/Array101/27_RemoveElement/description.md @@ -0,0 +1,54 @@ +### 27. Remove Element +|Easy + +Given an integer array nums and an integer val, remove all occurrences of val in nums in-place. The order of the elements may be changed. Then return the number of elements in nums which are not equal to val. + +Consider the number of elements in nums which are not equal to val be k, to get accepted, you need to do the following things: + +Change the array nums such that the first k elements of nums contain the elements which are not equal to val. The remaining elements of nums are not important as well as the size of nums. +Return k. +Custom Judge: + +The judge will test your solution with the following code: +``` +int[] nums = [...]; // Input array +int val = ...; // Value to remove +int[] expectedNums = [...]; // The expected answer with correct length. + // It is sorted with no values equaling val. + +int k = removeElement(nums, val); // Calls your implementation + +assert k == expectedNums.length; +sort(nums, 0, k); // Sort the first k elements of nums +for (int i = 0; i < actualLength; i++) { + assert nums[i] == expectedNums[i]; +} +If all assertions pass, then your solution will be accepted. +``` + + +Example 1: +``` +Input: nums = [3,2,2,3], val = 3 +Output: 2, nums = [2,2,_,_] +Explanation: Your function should return k = 2, with the first two elements of nums being 2. +It does not matter what you leave beyond the returned k (hence they are underscores). +``` +Example 2: +``` +Input: nums = [0,1,2,2,3,0,4,2], val = 2 +Output: 5, nums = [0,1,4,0,3,_,_,_] +Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4. +Note that the five elements can be returned in any order. +It does not matter what you leave beyond the returned k (hence they are underscores). +``` + +### Constraints: + +0 <= nums.length <= 100 + +0 <= nums[i] <= 50 + +0 <= val <= 100 + + \ No newline at end of file diff --git a/DataStractures/Array101/27_RemoveElement/solution.py b/DataStractures/Array101/27_RemoveElement/solution.py new file mode 100644 index 0000000..202fbef --- /dev/null +++ b/DataStractures/Array101/27_RemoveElement/solution.py @@ -0,0 +1,18 @@ +class Solution: + def removeElement(self, nums: list[int], val: int) -> int: + #approach 01 +# while val in nums: +# nums.pop(nums.index(val)) + +# return(len(nums)) + + #approach 02 + # while val in nums: nums.remove(val) + + #approach 03 + i = 0 + for x in nums: + if x != val: + nums[i] = x + i += 1 + return i diff --git a/DataStractures/Array101/283_MoveZeroes/description.md b/DataStractures/Array101/283_MoveZeroes/description.md new file mode 100644 index 0000000..48be8d9 --- /dev/null +++ b/DataStractures/Array101/283_MoveZeroes/description.md @@ -0,0 +1,28 @@ +### 283. Move Zeroes +|Easy + +Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. + +Note that you must do this in-place without making a copy of the array. + + + +Example 1: +``` +Input: nums = [0,1,0,3,12] +Output: [1,3,12,0,0] +``` +Example 2: +``` +Input: nums = [0] +Output: [0] +``` + +### Constraints: + +1 <= nums.length <= 104 + +-231 <= nums[i] <= 231 - 1 + + +### Follow up: Could you minimize the total number of operations done? \ No newline at end of file diff --git a/DataStractures/Array101/283_MoveZeroes/solution.py b/DataStractures/Array101/283_MoveZeroes/solution.py new file mode 100644 index 0000000..5840481 --- /dev/null +++ b/DataStractures/Array101/283_MoveZeroes/solution.py @@ -0,0 +1,20 @@ +class Solution: + def moveZeroes(self, nums: list[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + + +# nums_zeros = nums.count(0) +# for i in range(nums_zeros): +# nums.remove(0) +# nums.append(0) + + + n = len(nums) + i = 0 + for j in range(n): + if (nums[j] != 0): + nums[i], nums[j] = nums[j], nums[i] + i += 1 + \ No newline at end of file diff --git a/DataStractures/Array101/3_LongestSubstringWithoutRepeatingCharacters/description.md b/DataStractures/Array101/3_LongestSubstringWithoutRepeatingCharacters/description.md new file mode 100644 index 0000000..85c6c5c --- /dev/null +++ b/DataStractures/Array101/3_LongestSubstringWithoutRepeatingCharacters/description.md @@ -0,0 +1,32 @@ +### 3. Longest Substring Without Repeating Characters +|Medium + +Given a string s, find the length of the longest substring without repeating characters. + + + +Example 1: +``` +Input: s = "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3. +``` +Example 2: +``` +Input: s = "bbbbb" +Output: 1 +Explanation: The answer is "b", with the length of 1. +``` +Example 3: +``` +Input: s = "pwwkew" +Output: 3 +Explanation: The answer is "wke", with the length of 3. +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. +``` + +### Constraints: + +0 <= s.length <= 5 * 104 + +s consists of English letters, digits, symbols and spaces. \ No newline at end of file diff --git a/DataStractures/Array101/3_LongestSubstringWithoutRepeatingCharacters/solution.py b/DataStractures/Array101/3_LongestSubstringWithoutRepeatingCharacters/solution.py new file mode 100644 index 0000000..639f532 --- /dev/null +++ b/DataStractures/Array101/3_LongestSubstringWithoutRepeatingCharacters/solution.py @@ -0,0 +1,18 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ans = "" + i=0 + count = 0 + + if len(s)==1: + return 1 + else: + while i < len(s): + if s[i] not in ans: + ans += s[i] + else: + ans = ans[(ans.index(s[i])+1):]+ s[i] + i +=1 + count = max(count, len(ans)) + return(count) + #3 diff --git a/DataStractures/Array101/414_ThirdMaximumNumber/description.md b/DataStractures/Array101/414_ThirdMaximumNumber/description.md new file mode 100644 index 0000000..9a564b3 --- /dev/null +++ b/DataStractures/Array101/414_ThirdMaximumNumber/description.md @@ -0,0 +1,40 @@ +### 414. Third Maximum Number +|Easy + +Given an integer array nums, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. + + + +Example 1: +``` +Input: nums = [3,2,1] +Output: 1 +Explanation: +The first distinct maximum is 3. +The second distinct maximum is 2. +The third distinct maximum is 1. +``` +Example 2: +``` +Input: nums = [1,2] +Output: 2 +Explanation: +The first distinct maximum is 2. +The second distinct maximum is 1. +The third distinct maximum does not exist, so the maximum (2) is returned instead. +``` +Example 3: +``` +Input: nums = [2,2,3,1] +Output: 1 +Explanation: +The first distinct maximum is 3. +The second distinct maximum is 2 (both 2's are counted together since they have the same value). +The third distinct maximum is 1. + ``` + +### Constraints: + +1 <= nums.length <= 104 + +-231 <= nums[i] <= 231 - 1 \ No newline at end of file diff --git a/DataStractures/Array101/414_ThirdMaximumNumber/solution.py b/DataStractures/Array101/414_ThirdMaximumNumber/solution.py new file mode 100644 index 0000000..75a2406 --- /dev/null +++ b/DataStractures/Array101/414_ThirdMaximumNumber/solution.py @@ -0,0 +1,11 @@ +class Solution: + def thirdMax(self, nums: list[int]) -> int: + + nums2= set(nums) + nums2= sorted(nums2) + + if len(nums2)>=3: + return nums2[-3] + else: + return max(nums) + \ No newline at end of file diff --git a/DataStractures/Array101/448_FindAllNumbersDisappearedinanArray/description.md b/DataStractures/Array101/448_FindAllNumbersDisappearedinanArray/description.md new file mode 100644 index 0000000..9939911 --- /dev/null +++ b/DataStractures/Array101/448_FindAllNumbersDisappearedinanArray/description.md @@ -0,0 +1,28 @@ +### 448. Find All Numbers Disappeared in an Array +|Easy + +Given an array nums of n integers where nums[i] is in the range [1, n], return an array of all the integers in the range [1, n] that do not appear in nums. + + + +Example 1: +``` +Input: nums = [4,3,2,7,8,2,3,1] +Output: [5,6] +``` +Example 2: +``` +Input: nums = [1,1] +Output: [2] +``` + +### Constraints: + +n == nums.length + +1 <= n <= 105 + +1 <= nums[i] <= n + + +### Follow up: Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space. \ No newline at end of file diff --git a/DataStractures/Array101/448_FindAllNumbersDisappearedinanArray/solution.py b/DataStractures/Array101/448_FindAllNumbersDisappearedinanArray/solution.py new file mode 100644 index 0000000..bf47b45 --- /dev/null +++ b/DataStractures/Array101/448_FindAllNumbersDisappearedinanArray/solution.py @@ -0,0 +1,11 @@ +class Solution: + def findDisappearedNumbers(self, nums: list[int]) -> list[int]: + +# n=len(nums) +# return [i for i in range(1,n+1) if i not in nums] +#Time Complexity O(n**2) + + s= set(nums) + return[i for i in range(1,len(nums)+1) if i not in s] +#Time Complexity O(n) + \ No newline at end of file diff --git a/DataStractures/Array101/452_MinimumNumberofArrowstoBurstBalloons/description.md b/DataStractures/Array101/452_MinimumNumberofArrowstoBurstBalloons/description.md new file mode 100644 index 0000000..e669cca --- /dev/null +++ b/DataStractures/Array101/452_MinimumNumberofArrowstoBurstBalloons/description.md @@ -0,0 +1,41 @@ +### 452. Minimum Number of Arrows to Burst Balloons +|Medium + +There are some spherical balloons taped onto a flat wall that represents the XY-plane. The balloons are represented as a 2D integer array points where points[i] = [xstart, xend] denotes a balloon whose horizontal diameter stretches between xstart and xend. You do not know the exact y-coordinates of the balloons. + +Arrows can be shot up directly vertically (in the positive y-direction) from different points along the x-axis. A balloon with xstart and xend is burst by an arrow shot at x if xstart <= x <= xend. There is no limit to the number of arrows that can be shot. A shot arrow keeps traveling up infinitely, bursting any balloons in its path. + +Given the array points, return the minimum number of arrows that must be shot to burst all balloons. + + + +Example 1: +``` +Input: points = [[10,16],[2,8],[1,6],[7,12]] +Output: 2 +Explanation: The balloons can be burst by 2 arrows: +- Shoot an arrow at x = 6, bursting the balloons [2,8] and [1,6]. +- Shoot an arrow at x = 11, bursting the balloons [10,16] and [7,12]. +``` +Example 2: +``` +Input: points = [[1,2],[3,4],[5,6],[7,8]] +Output: 4 +Explanation: One arrow needs to be shot for each balloon for a total of 4 arrows. +``` +Example 3: +``` +Input: points = [[1,2],[2,3],[3,4],[4,5]] +Output: 2 +Explanation: The balloons can be burst by 2 arrows: +- Shoot an arrow at x = 2, bursting the balloons [1,2] and [2,3]. +- Shoot an arrow at x = 4, bursting the balloons [3,4] and [4,5]. +``` + +#### Constraints: + +1 <= points.length <= 105 + +points[i].length == 2 + +-231 <= xstart < xend <= 231 - 1 \ No newline at end of file diff --git a/DataStractures/Array101/452_MinimumNumberofArrowstoBurstBalloons/solution.py b/DataStractures/Array101/452_MinimumNumberofArrowstoBurstBalloons/solution.py new file mode 100644 index 0000000..64add17 --- /dev/null +++ b/DataStractures/Array101/452_MinimumNumberofArrowstoBurstBalloons/solution.py @@ -0,0 +1,15 @@ +from ast import List + + +class Solution: + def findMinArrowShots(self, points: List[List[int]]) -> int: + points.sort(key = lambda x: x[1]) # Example: points = [[2,4],[1,6],[1,3],[7,8]] + # points.sort = [[1,3],[2,4],[1,6],[7,8]] + tally, bow = 1, points[0][1] + # ––––––– [7,9] + for start, end in points: # –––––––––––––––– [1,6] + if bow < start: # ––––––– [2,4] + bow = end # ––––––– [1,3] + tally += 1 # 1 2 3 4 5 6 7 8 9 + # | | + return tally # tally = 1 tally = 2 diff --git a/DataStractures/Array101/485_MaxConsecutiveOnes/description.md b/DataStractures/Array101/485_MaxConsecutiveOnes/description.md new file mode 100644 index 0000000..2cc4240 --- /dev/null +++ b/DataStractures/Array101/485_MaxConsecutiveOnes/description.md @@ -0,0 +1,25 @@ +### 485. Max Consecutive Ones +|Easy + +Companies +Given a binary array nums, return the maximum number of consecutive 1's in the array. + + + +Example 1: +``` +Input: nums = [1,1,0,1,1,1] +Output: 3 +Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3. +``` +Example 2: +``` +Input: nums = [1,0,1,1,0,1] +Output: 2 +``` + +### Constraints: + +1 <= nums.length <= 105 + +nums[i] is either 0 or 1. \ No newline at end of file diff --git a/DataStractures/Array101/485_MaxConsecutiveOnes/solution.py b/DataStractures/Array101/485_MaxConsecutiveOnes/solution.py new file mode 100644 index 0000000..5de90af --- /dev/null +++ b/DataStractures/Array101/485_MaxConsecutiveOnes/solution.py @@ -0,0 +1,52 @@ +class Solution: + def findMaxConsecutiveOnes(self, nums: list[int]) -> int: + + + #Solution 01 + # countGlobal=0 + # countCurrent=0 + + # for i in range (len(nums)): + + # if nums[i]==1: + # countCurrent +=1 + # countGlobal=max(countGlobal, countCurrent) + + # else: + + # countCurrent=0 + + # return countGlobal + + # return len(max("".join(map(str, nums)).split("0"))) + + + #Solution 02 + c = 0 + a = [] + for i in range(len(nums)): + if nums[i] == 1: + c += 1 + + else: + a.append(c) + c = 0 + a.append(c) + return max(a) + + ##Solution 03 + # consecutive = result = 0 + # for n in nums: + # consecutive = consecutive*n+n + # result = max(result, consecutive) + # return result + + #Solution 04 + # cons_cnt=0 + # one_counter=0 + # for i in nums: + # if i ==1: + # one_counter += 1 + # cons_cnt = max(cons_cnt, one_counter) + # else: one_counter = 0 + # return cons_cnt diff --git a/DataStractures/Array101/486_PredicttheWinner/description.md b/DataStractures/Array101/486_PredicttheWinner/description.md new file mode 100644 index 0000000..3533a00 --- /dev/null +++ b/DataStractures/Array101/486_PredicttheWinner/description.md @@ -0,0 +1,33 @@ +### 486. Predict the Winner +|Medium + +You are given an integer array nums. Two players are playing a game with this array: player 1 and player 2. + +Player 1 and player 2 take turns, with player 1 starting first. Both players start the game with a score of 0. At each turn, the player takes one of the numbers from either end of the array (i.e., nums[0] or nums[nums.length - 1]) which reduces the size of the array by 1. The player adds the chosen number to their score. The game ends when there are no more elements in the array. + +Return true if Player 1 can win the game. If the scores of both players are equal, then player 1 is still the winner, and you should also return true. You may assume that both players are playing optimally. + + + +Example 1: +``` +Input: nums = [1,5,2] +Output: false +Explanation: Initially, player 1 can choose between 1 and 2. +If he chooses 2 (or 1), then player 2 can choose from 1 (or 2) and 5. If player 2 chooses 5, then player 1 will be left with 1 (or 2). +So, final score of player 1 is 1 + 2 = 3, and player 2 is 5. +Hence, player 1 will never be the winner and you need to return false. +``` +Example 2: +``` +Input: nums = [1,5,233,7] +Output: true +Explanation: Player 1 first chooses 1. Then player 2 has to choose between 5 and 7. No matter which number player 2 choose, player 1 can choose 233. +Finally, player 1 has more score (234) than player 2 (12), so you need to return True representing player1 can win. +``` + +### Constraints: + +1 <= nums.length <= 20 + +0 <= nums[i] <= 107 \ No newline at end of file diff --git a/DataStractures/Array101/486_PredicttheWinner/solution.py b/DataStractures/Array101/486_PredicttheWinner/solution.py new file mode 100644 index 0000000..c9fa016 --- /dev/null +++ b/DataStractures/Array101/486_PredicttheWinner/solution.py @@ -0,0 +1,19 @@ +from ast import List + + +class Solution: + def PredictTheWinner(self, A: List[int]) -> bool: + memo = {} + def maxscore(i,j): + if (i,j) in memo: + return memo[i,j] + if i>j: + return 0 + # + sA = A[i] + min( maxscore(i+1,j-1), maxscore(i+2,j ) ) # pick A[i] + min of the 2 possible upcoming turns (player 2 is smart) + sB = A[j] + min( maxscore(i ,j-2), maxscore(i+1,j-1) ) + score = max(sA,sB) + memo[i,j] = score + return score + p1 = maxscore(0,len(A)-1) # Score Player 1 + return p1>=(sum(A)-p1) # p1 >= p2 \ No newline at end of file diff --git a/DataStractures/Array101/48_RotateImage/description.md b/DataStractures/Array101/48_RotateImage/description.md new file mode 100644 index 0000000..73573c7 --- /dev/null +++ b/DataStractures/Array101/48_RotateImage/description.md @@ -0,0 +1,27 @@ +### 48. Rotate Image +|Medium + +You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise). + +You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation. + + + +Example 1: +``` +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [[7,4,1],[8,5,2],[9,6,3]] +``` +Example 2: +``` +Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]] +Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]] +``` + +### Constraints: + +n == matrix.length == matrix[i].length + +1 <= n <= 20 + +-1000 <= matrix[i][j] <= 1000 \ No newline at end of file diff --git a/DataStractures/Array101/48_RotateImage/solution.py b/DataStractures/Array101/48_RotateImage/solution.py new file mode 100644 index 0000000..bb70734 --- /dev/null +++ b/DataStractures/Array101/48_RotateImage/solution.py @@ -0,0 +1,15 @@ +from ast import List + + +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + """ + Do not return anything, modify matrix in-place instead. + + """ + n = len(matrix) + for i in range(n): + for j in range(i,n): + matrix[i][j] , matrix[j][i] = matrix[j][i] , matrix[i][j] + for i in range(n): + matrix[i].reverse() \ No newline at end of file diff --git a/DataStractures/Array101/523_ContinuousSubarraySum/523_continuous_subarray_sum.md b/DataStractures/Array101/523_ContinuousSubarraySum/523_continuous_subarray_sum.md new file mode 100644 index 0000000..f0e7681 --- /dev/null +++ b/DataStractures/Array101/523_ContinuousSubarraySum/523_continuous_subarray_sum.md @@ -0,0 +1,43 @@ +### 523. Continuous Subarray Sum +|Medium + +Given an integer array nums and an integer k, return true if nums has a good subarray or false otherwise. + +A good subarray is a subarray where: + +its length is at least two, and +the sum of the elements of the subarray is a multiple of k. +Note that: + +A subarray is a contiguous part of the array. +An integer x is a multiple of k if there exists an integer n such that x = n * k. 0 is always a multiple of k. + + +Example 1: +``` +Input: nums = [23,2,4,6,7], k = 6 +Output: true +Explanation: [2, 4] is a continuous subarray of size 2 whose elements sum up to 6. +``` +Example 2: +``` +Input: nums = [23,2,6,4,7], k = 6 +Output: true +Explanation: [23, 2, 6, 4, 7] is an continuous subarray of size 5 whose elements sum up to 42. +42 is a multiple of 6 because 42 = 7 * 6 and 7 is an integer. +``` +Example 3: +``` +Input: nums = [23,2,6,4,7], k = 13 +Output: false +``` + +### Constraints: + +1 <= nums.length <= 105 + +0 <= nums[i] <= 109 + +0 <= sum(nums[i]) <= 231 - 1 + +1 <= k <= 231 - 1 \ No newline at end of file diff --git a/DataStractures/Array101/523_ContinuousSubarraySum/solution.py b/DataStractures/Array101/523_ContinuousSubarraySum/solution.py new file mode 100644 index 0000000..9b8f208 --- /dev/null +++ b/DataStractures/Array101/523_ContinuousSubarraySum/solution.py @@ -0,0 +1,40 @@ +from ast import List + + +class Solution: + def checkSubarraySum(self, nums: List[int], k: int) -> bool: + # sum_dict={0:-1} + # total=0 + # for i,val in enumerate(nums): + # total+=val + # remain=total % k + # if remain not in sum_dict: + # sum_dict[remain]=i + # elif i - sum_dict[remain]>1: + # print (remain) + # return True + # return False + + # #approach 02 + # if len(nums) < 2: + # return False + + # 0: -1 is for edge case that current sum mod k == 0 + # for when the current running sum is cleanly divisible by k + # e.g: nums = [4, 2], k = 3 + sums = {0: -1} # 0 + cumulative_sum = 0 + for idx, num in enumerate(nums): + cumulative_sum += num + remainder = cumulative_sum % k + + # if current_sum mod k is in dict and index idx - sums[remainder] > 1, we got the Subarray! + # we use 2 not 1 because the element at sums[remainder] is not in the subarray we are talking about + if remainder in sums and idx - sums[remainder] >= 2: + return True + + # if current sum mod k not in dict, store it so as to ensure the further values stay + if remainder not in sums: + sums[remainder] = idx + +# space can be easily improved to O(k) be only storing k elements in sums diff --git a/DataStractures/Array101/704_BinarySearch/description.md b/DataStractures/Array101/704_BinarySearch/description.md new file mode 100644 index 0000000..9f80ddc --- /dev/null +++ b/DataStractures/Array101/704_BinarySearch/description.md @@ -0,0 +1,32 @@ +### 704. Binary Search +|Easy + +Companies +Given an array of integers nums which is sorted in ascending order, and an integer target, write a function to search target in nums. If target exists, then return its index. Otherwise, return -1. + +You must write an algorithm with O(log n) runtime complexity. + + + +Example 1: +``` +Input: nums = [-1,0,3,5,9,12], target = 9 +Output: 4 +Explanation: 9 exists in nums and its index is 4 +``` +Example 2: +``` +Input: nums = [-1,0,3,5,9,12], target = 2 +Output: -1 +Explanation: 2 does not exist in nums so return -1 +``` + +### Constraints: + +1 <= nums.length <= 104 + +-104 < nums[i], target < 104 + +All the integers in nums are unique. + +nums is sorted in ascending order. \ No newline at end of file diff --git a/DataStractures/Array101/704_BinarySearch/solution.py b/DataStractures/Array101/704_BinarySearch/solution.py new file mode 100644 index 0000000..4b79c87 --- /dev/null +++ b/DataStractures/Array101/704_BinarySearch/solution.py @@ -0,0 +1,18 @@ +class Solution: + def search(self, nums: list[int], target: int) -> int: + + + low = 0 + high = len(nums)-1 + + while low <= high: + mid = (low + high) // 2 + + if nums[mid] == target: + return mid + if target > nums[mid]: + low = mid + 1 + else: + high = mid - 1 + + return -1 \ No newline at end of file diff --git a/DataStractures/Array101/80_RemoveDuplicatesfromSortedArrayII/80_remove_duplicates_from_sorted_arrayII.md b/DataStractures/Array101/80_RemoveDuplicatesfromSortedArrayII/80_remove_duplicates_from_sorted_arrayII.md new file mode 100644 index 0000000..4cc6b45 --- /dev/null +++ b/DataStractures/Array101/80_RemoveDuplicatesfromSortedArrayII/80_remove_duplicates_from_sorted_arrayII.md @@ -0,0 +1,50 @@ +### 80. Remove Duplicates from Sorted Array II +|Medium + +Given an integer array nums sorted in non-decreasing order, remove some duplicates in-place such that each unique element appears at most twice. The relative order of the elements should be kept the same. + +Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums. More formally, if there are k elements after removing the duplicates, then the first k elements of nums should hold the final result. It does not matter what you leave beyond the first k elements. + +Return k after placing the final result in the first k slots of nums. + +Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory. + +Custom Judge: + +The judge will test your solution with the following code: +``` +int[] nums = [...]; // Input array +int[] expectedNums = [...]; // The expected answer with correct length + +int k = removeDuplicates(nums); // Calls your implementation + +assert k == expectedNums.length; +for (int i = 0; i < k; i++) { + assert nums[i] == expectedNums[i]; +} +If all assertions pass, then your solution will be accepted. +``` + + +Example 1: +``` +Input: nums = [1,1,1,2,2,3] +Output: 5, nums = [1,1,2,2,3,_] +Explanation: Your function should return k = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). +``` +Example 2: +``` +Input: nums = [0,0,1,1,1,1,2,3,3] +Output: 7, nums = [0,0,1,1,2,3,3,_,_] +Explanation: Your function should return k = 7, with the first seven elements of nums being 0, 0, 1, 1, 2, 3 and 3 respectively. +It does not matter what you leave beyond the returned k (hence they are underscores). +``` + +### Constraints: + +1 <= nums.length <= 3 * 104 + +-104 <= nums[i] <= 104 + +nums is sorted in non-decreasing order. \ No newline at end of file diff --git a/DataStractures/Array101/80_RemoveDuplicatesfromSortedArrayII/solution.py b/DataStractures/Array101/80_RemoveDuplicatesfromSortedArrayII/solution.py new file mode 100644 index 0000000..a8965b3 --- /dev/null +++ b/DataStractures/Array101/80_RemoveDuplicatesfromSortedArrayII/solution.py @@ -0,0 +1,21 @@ +class Solution: + def removeDuplicates(self, nums: list[int]) -> int: + #Approch 01 + # nums_count={c: nums.count(c) for c in nums} + # nums.clear() + # for k, v in nums_count.items(): + # if v>=2: + # nums.append(k) + # nums.append(k) + # else: + # nums.append(k) + # return(len(nums)) + + #Approach 02 + i = 1 + while (i None: + + """ + Do not return anything, modify nums1 in-place instead. + + """ + i, j, k = m-1, n-1, m+n-1 + + while j >= 0: + if i >= 0 and nums1[i] > nums2[j]: + nums1[k] = nums1[i] + i -= 1 + k -= 1 + else: + nums1[k] = nums2[j] + j -= 1 + k -= 1 + \ No newline at end of file diff --git a/DataStractures/Array101/905_SortArrayByParity/description.md b/DataStractures/Array101/905_SortArrayByParity/description.md new file mode 100644 index 0000000..a84ad41 --- /dev/null +++ b/DataStractures/Array101/905_SortArrayByParity/description.md @@ -0,0 +1,26 @@ +### 905. Sort Array By Parity +|Easy + +Given an integer array nums, move all the even integers at the beginning of the array followed by all the odd integers. + +Return any array that satisfies this condition. + + + +Example 1: +``` +Input: nums = [3,1,2,4] +Output: [2,4,3,1] +Explanation: The outputs [4,2,3,1], [2,4,1,3], and [4,2,1,3] would also be accepted. +``` +Example 2: +``` +Input: nums = [0] +Output: [0] +``` + +### Constraints: + +1 <= nums.length <= 5000 + +0 <= nums[i] <= 5000 \ No newline at end of file diff --git a/DataStractures/Array101/905_SortArrayByParity/solution.py b/DataStractures/Array101/905_SortArrayByParity/solution.py new file mode 100644 index 0000000..975dc76 --- /dev/null +++ b/DataStractures/Array101/905_SortArrayByParity/solution.py @@ -0,0 +1,15 @@ +class Solution: + def sortArrayByParity(self, nums: list[int]) -> list[int]: + + if len(nums)==1: + return nums + + else: + n=0 + for i in range(len(nums)): + if nums[i]%2==0: + nums[n], nums[i]=nums[i], nums[n] + n +=1 + return nums + + \ No newline at end of file diff --git a/DataStractures/Array101/941_Valid Mountain Array/description.md b/DataStractures/Array101/941_Valid Mountain Array/description.md new file mode 100644 index 0000000..fc27d88 --- /dev/null +++ b/DataStractures/Array101/941_Valid Mountain Array/description.md @@ -0,0 +1,35 @@ +### 941. Valid Mountain Array +|Easy + +Given an array of integers arr, return true if and only if it is a valid mountain array. + +Recall that arr is a mountain array if and only if: +``` +arr.length >= 3 +There exists some i with 0 < i < arr.length - 1 such that: +arr[0] < arr[1] < ... < arr[i - 1] < arr[i] +arr[i] > arr[i + 1] > ... > arr[arr.length - 1] +``` + + +Example 1: +``` +Input: arr = [2,1] +Output: false +``` +xample 2: +``` +Input: arr = [3,5,5] +Output: false +``` +Example 3: +``` +Input: arr = [0,3,2,1] +Output: true +``` + +### Constraints: + +1 <= arr.length <= 104 + +0 <= arr[i] <= 104 \ No newline at end of file diff --git a/DataStractures/Array101/941_Valid Mountain Array/solution.py b/DataStractures/Array101/941_Valid Mountain Array/solution.py new file mode 100644 index 0000000..e365715 --- /dev/null +++ b/DataStractures/Array101/941_Valid Mountain Array/solution.py @@ -0,0 +1,28 @@ +class Solution: + def validMountainArray(self, arr: list[int]) -> bool: + + if len(arr)<3: + return False + + peak=arr.index(max(arr)) + + if peak == 0 or peak == len(arr) - 1: + return False + else: + result = True + for i in range(0, peak): + if arr[i] >= arr[i + 1]: + result = False + break + + + if result: + for k in range(peak+1, len(arr)): + + if arr[k - 1] <= arr[k]: + return False + + else: + return False + + return True \ No newline at end of file diff --git a/DataStractures/Array101/977_SquaresofaSortedArray/description.md b/DataStractures/Array101/977_SquaresofaSortedArray/description.md new file mode 100644 index 0000000..8316893 --- /dev/null +++ b/DataStractures/Array101/977_SquaresofaSortedArray/description.md @@ -0,0 +1,27 @@ +### 977. Squares of a Sorted Array +|Easy + +Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. + + + +Example 1: +``` +Input: nums = [-4,-1,0,3,10] +Output: [0,1,9,16,100] +Explanation: After squaring, the array becomes [16,1,0,9,100]. +After sorting, it becomes [0,1,9,16,100]. +``` +Example 2: +``` +Input: nums = [-7,-3,2,3,11] +Output: [4,9,9,49,121] +``` + +### Constraints: + +1 <= nums.length <= 104 + +-104 <= nums[i] <= 104 + +nums is sorted in non-decreasing order. \ No newline at end of file diff --git a/DataStractures/Array101/977_SquaresofaSortedArray/solution.py b/DataStractures/Array101/977_SquaresofaSortedArray/solution.py new file mode 100644 index 0000000..7629a1d --- /dev/null +++ b/DataStractures/Array101/977_SquaresofaSortedArray/solution.py @@ -0,0 +1,6 @@ +class Solution: + def sortedSquares(self, nums: list[int]) -> list[int]: + for i in range(len(nums)): + nums[i] = ((nums[i]) ** 2) + + return (sorted(nums)) diff --git a/DataStractures/Array101/986_IntervalListIntersections/description.md b/DataStractures/Array101/986_IntervalListIntersections/description.md new file mode 100644 index 0000000..aefd435 --- /dev/null +++ b/DataStractures/Array101/986_IntervalListIntersections/description.md @@ -0,0 +1,38 @@ +### 986. Interval List Intersections +|Medium + +You are given two lists of closed intervals, firstList and secondList, where firstList[i] = [starti, endi] and secondList[j] = [startj, endj]. Each list of intervals is pairwise disjoint and in sorted order. + +Return the intersection of these two interval lists. + +A closed interval [a, b] (with a <= b) denotes the set of real numbers x with a <= x <= b. + +The intersection of two closed intervals is a set of real numbers that are either empty or represented as a closed interval. For example, the intersection of [1, 3] and [2, 4] is [2, 3]. + + + +Example 1: + +``` +Input: firstList = [[0,2],[5,10],[13,23],[24,25]], secondList = [[1,5],[8,12],[15,24],[25,26]] +Output: [[1,2],[5,5],[8,10],[15,23],[24,24],[25,25]] +``` +Example 2: +``` +Input: firstList = [[1,3],[5,9]], secondList = [] +Output: [] +``` + +### Constraints: + +0 <= firstList.length, secondList.length <= 1000 + +firstList.length + secondList.length >= 1 + +0 <= starti < endi <= 109 + +endi < starti+1 + +0 <= startj < endj <= 109 + +endj < startj+1 \ No newline at end of file diff --git a/DataStractures/Array101/986_IntervalListIntersections/solution.py b/DataStractures/Array101/986_IntervalListIntersections/solution.py new file mode 100644 index 0000000..237cc1d --- /dev/null +++ b/DataStractures/Array101/986_IntervalListIntersections/solution.py @@ -0,0 +1,36 @@ +class Solution: + def intervalIntersection(self, firstList: list[list[int]], secondList: list[list[int]]) -> list[list[int]]: + #Approach 01 + ans =[] + if firstList is None or secondList is None: + return ans + else: + for i in range(len(firstList)): + for j in range(len(secondList)): + max_start = max(firstList[i][0], secondList[j][0]) + min_finish = min(firstList[i][1], secondList[j][1]) + if max_start>min_finish: + continue + else: + ans.append([max_start, min_finish]) + return ans + + + #Approach 02 + # index1 = index2 = 0 + # start, end = 0, 1 + # merged_list = [] + # while index1 < len(firstList) and index2 < len(secondList): + # overlap1 = firstList[index1][start] <= secondList[index2][end] \ + # and firstList[index1][start] >= secondList[index2][start] + + # overlap2 = secondList[index2][start] <= firstList[index1][end] \ + # and secondList[index2][start] >= firstList[index1][start] + + # if overlap1 or overlap2: + # merged_list.append([max(firstList[index1][start], secondList[index2][start]), min(firstList[index1][end], secondList[index2][end])]) + # if firstList[index1][end] < secondList[index2][end]: + # index1 += 1 + # else: + # index2 += 1 + # return merged_list diff --git a/DataStractures/Array_and_String/1108_DefanginganIPAddress/description.md b/DataStractures/Array_and_String/1108_DefanginganIPAddress/description.md new file mode 100644 index 0000000..040cfb3 --- /dev/null +++ b/DataStractures/Array_and_String/1108_DefanginganIPAddress/description.md @@ -0,0 +1,23 @@ +### 1108. Defanging an IP Address +|Easy + +Given a valid (IPv4) IP address, return a defanged version of that IP address. + +A defanged IP address replaces every period "." with "[.]". + + + +Example 1: +``` +Input: address = "1.1.1.1" +Output: "1[.]1[.]1[.]1" +``` +Example 2: +``` +Input: address = "255.100.50.0" +Output: "255[.]100[.]50[.]0" +``` + +### Constraints: + +The given address is a valid IPv4 address. \ No newline at end of file diff --git a/DataStractures/Array_and_String/1108_DefanginganIPAddress/solution.py b/DataStractures/Array_and_String/1108_DefanginganIPAddress/solution.py new file mode 100644 index 0000000..b430bd7 --- /dev/null +++ b/DataStractures/Array_and_String/1108_DefanginganIPAddress/solution.py @@ -0,0 +1,5 @@ +class Solution: + def defangIPaddr(self, address: str) -> str: + if "." in address: + n_address = address.replace(".", "[.]") + return n_address \ No newline at end of file diff --git a/DataStractures/Array_and_String/118_Pascal'sTriangle/description.md b/DataStractures/Array_and_String/118_Pascal'sTriangle/description.md new file mode 100644 index 0000000..77cb35e --- /dev/null +++ b/DataStractures/Array_and_String/118_Pascal'sTriangle/description.md @@ -0,0 +1,24 @@ +### 118. Pascal's Triangle +|Easy + +Given an integer numRows, return the first numRows of Pascal's triangle. + +In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: + + + + +Example 1: +``` +Input: numRows = 5 +Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]] +``` +Example 2: +``` +Input: numRows = 1 +Output: [[1]] +``` + +### Constraints: + +1 <= numRows <= 30 \ No newline at end of file diff --git a/DataStractures/Array_and_String/118_Pascal'sTriangle/solution.py b/DataStractures/Array_and_String/118_Pascal'sTriangle/solution.py new file mode 100644 index 0000000..f68bf99 --- /dev/null +++ b/DataStractures/Array_and_String/118_Pascal'sTriangle/solution.py @@ -0,0 +1,13 @@ +class Solution: + def generate(self, numRows: int) -> list[list[int]]: + res=[] + intermedate=[] + res.append([1]) + for i in range (numRows-1): + intermedate=[1] + for j in range (i): + intermedate.append(res[i][j]+res[i][j+1]) + intermedate.append(1) + res.append(intermedate) + return res + #118 \ No newline at end of file diff --git a/DataStractures/Array_and_String/119_Pascal'sTriangleII/description.md b/DataStractures/Array_and_String/119_Pascal'sTriangleII/description.md new file mode 100644 index 0000000..f989639 --- /dev/null +++ b/DataStractures/Array_and_String/119_Pascal'sTriangleII/description.md @@ -0,0 +1,29 @@ +### 119. Pascal's Triangle II +|Easy + +Given an integer rowIndex, return the rowIndexth (0-indexed) row of the Pascal's triangle. + +In Pascal's triangle, each number is the sum of the two numbers directly above it as shown: + + + + +Example 1: +``` +Input: rowIndex = 3 +Output: [1,3,3,1] +``` +Example 2: +``` +Input: rowIndex = 0 +Output: [1] +``` +Example 3: +``` +Input: rowIndex = 1 +Output: [1,1] +``` + +### Constraints: + +0 <= rowIndex <= 33 \ No newline at end of file diff --git a/DataStractures/Array_and_String/119_Pascal'sTriangleII/solution.py b/DataStractures/Array_and_String/119_Pascal'sTriangleII/solution.py new file mode 100644 index 0000000..5d11c19 --- /dev/null +++ b/DataStractures/Array_and_String/119_Pascal'sTriangleII/solution.py @@ -0,0 +1,11 @@ +from ast import List + + +class Solution: + def getRow(self, rowIndex: int) -> List[int]: + r = [1] + for i in range(1,rowIndex+1): + r.append( int(r[-1]*(rowIndex-i+1)/i) ) + return r + + #119 diff --git a/DataStractures/Array_and_String/125_ValidPalindrome/description.md b/DataStractures/Array_and_String/125_ValidPalindrome/description.md new file mode 100644 index 0000000..567996d --- /dev/null +++ b/DataStractures/Array_and_String/125_ValidPalindrome/description.md @@ -0,0 +1,34 @@ +### 125. Valid Palindrome +|Easy + +A phrase is a palindrome if, after converting all uppercase letters into lowercase letters and removing all non-alphanumeric characters, it reads the same forward and backward. Alphanumeric characters include letters and numbers. + +Given a string s, return true if it is a palindrome, or false otherwise. + + + +Example 1: +``` +Input: s = "A man, a plan, a canal: Panama" +Output: true +Explanation: "amanaplanacanalpanama" is a palindrome. +``` +Example 2: +``` +Input: s = "race a car" +Output: false +Explanation: "raceacar" is not a palindrome. +``` +Example 3: +``` +Input: s = " " +Output: true +Explanation: s is an empty string "" after removing non-alphanumeric characters. +Since an empty string reads the same forward and backward, it is a palindrome. +``` + +### Constraints: + +1 <= s.length <= 2 * 105 + +s consists only of printable ASCII characters. \ No newline at end of file diff --git a/DataStractures/Array_and_String/125_ValidPalindrome/solution.py b/DataStractures/Array_and_String/125_ValidPalindrome/solution.py new file mode 100644 index 0000000..2a9e941 --- /dev/null +++ b/DataStractures/Array_and_String/125_ValidPalindrome/solution.py @@ -0,0 +1,12 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + l, r = 0, len(s)-1 + while l < r: + while l < r and not s[l].isalnum(): + l += 1 + while l str: + ans="" + v=sorted(strs) + first=v[0] + last=v[-1] + for i in range(min(len(first),len(last))): + if(first[i]!=last[i]): + return ans + ans+=first[i] + return ans + #14 diff --git a/DataStractures/Array_and_String/167_TwoSumIIInputArrayIsSorted/description.md b/DataStractures/Array_and_String/167_TwoSumIIInputArrayIsSorted/description.md new file mode 100644 index 0000000..a02bb39 --- /dev/null +++ b/DataStractures/Array_and_String/167_TwoSumIIInputArrayIsSorted/description.md @@ -0,0 +1,43 @@ +### 167. Two Sum II - Input Array Is Sorted +|Medium + +Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= index1 < index2 < numbers.length. + +Return the indices of the two numbers, index1 and index2, added by one as an integer array [index1, index2] of length 2. + +The tests are generated such that there is exactly one solution. You may not use the same element twice. + +Your solution must use only constant extra space. + + + +Example 1: +``` +Input: numbers = [2,7,11,15], target = 9 +Output: [1,2] +Explanation: The sum of 2 and 7 is 9. Therefore, index1 = 1, index2 = 2. We return [1, 2]. +``` +Example 2: +``` +Input: numbers = [2,3,4], target = 6 +Output: [1,3] +Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3. We return [1, 3]. +``` +Example 3: +``` +Input: numbers = [-1,0], target = -1 +Output: [1,2] +Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2. We return [1, 2]. +``` + +### Constraints: + +2 <= numbers.length <= 3 * 104 + +-1000 <= numbers[i] <= 1000 + +numbers is sorted in non-decreasing order. + +-1000 <= target <= 1000 + +The tests are generated such that there is exactly one solution. \ No newline at end of file diff --git a/DataStractures/Array_and_String/167_TwoSumIIInputArrayIsSorted/solution.py b/DataStractures/Array_and_String/167_TwoSumIIInputArrayIsSorted/solution.py new file mode 100644 index 0000000..d384d42 --- /dev/null +++ b/DataStractures/Array_and_String/167_TwoSumIIInputArrayIsSorted/solution.py @@ -0,0 +1,17 @@ +from ast import List + + +class Solution: + def twoSum(self, nums: List[int], target: int) -> List[int]: + l,r = 0, len(nums)-1 + target_sum=0 + while l < r: + target_sum = (nums[l]+nums[r]) + if target_sum==target: + return (l+1,r+1) + elif target_sum int: + return int(max(n)) \ No newline at end of file diff --git a/DataStractures/Array_and_String/1784_CheckIfBinaryStringHasatMostOneSegmentofOnes/description.md b/DataStractures/Array_and_String/1784_CheckIfBinaryStringHasatMostOneSegmentofOnes/description.md new file mode 100644 index 0000000..71479cc --- /dev/null +++ b/DataStractures/Array_and_String/1784_CheckIfBinaryStringHasatMostOneSegmentofOnes/description.md @@ -0,0 +1,26 @@ +### 1784. Check if Binary String Has at Most One Segment of Ones +|Easy + +Given a binary string s ​​​​​without leading zeros, return true​​​ if s contains at most one contiguous segment of ones. Otherwise, return false. + + + +Example 1: +``` +Input: s = "1001" +Output: false +Explanation: The ones do not form a contiguous segment. +``` +Example 2: +``` +Input: s = "110" +Output: true +``` + +### Constraints: + +1 <= s.length <= 100 + +s[i]​​​​ is either '0' or '1'. + +s[0] is '1'. \ No newline at end of file diff --git a/DataStractures/Array_and_String/1784_CheckIfBinaryStringHasatMostOneSegmentofOnes/solution.py b/DataStractures/Array_and_String/1784_CheckIfBinaryStringHasatMostOneSegmentofOnes/solution.py new file mode 100644 index 0000000..4c5097b --- /dev/null +++ b/DataStractures/Array_and_String/1784_CheckIfBinaryStringHasatMostOneSegmentofOnes/solution.py @@ -0,0 +1,3 @@ +class Solution: + def checkOnesSegment(self, s: str) -> bool: + return not "01" in s \ No newline at end of file diff --git a/DataStractures/Array_and_String/209_MinimumSizeSubarray/description.md b/DataStractures/Array_and_String/209_MinimumSizeSubarray/description.md new file mode 100644 index 0000000..05e71f3 --- /dev/null +++ b/DataStractures/Array_and_String/209_MinimumSizeSubarray/description.md @@ -0,0 +1,33 @@ +### 209. Minimum Size Subarray Sum +|Medium + +Given an array of positive integers nums and a positive integer target, return the minimal length of a +subarray + whose sum is greater than or equal to target. If there is no such subarray, return 0 instead. + + + +Example 1: +``` +Input: target = 7, nums = [2,3,1,2,4,3] +Output: 2 +Explanation: The subarray [4,3] has the minimal length under the problem constraint. +``` +Example 2: +``` +Input: target = 4, nums = [1,4,4] +Output: 1 +``` +Example 3: +``` +Input: target = 11, nums = [1,1,1,1,1,1,1,1] +Output: 0 +``` + +### Constraints: + +1 <= target <= 109 + +1 <= nums.length <= 105 + +1 <= nums[i] <= 104 \ No newline at end of file diff --git a/DataStractures/Array_and_String/209_MinimumSizeSubarray/solution.py b/DataStractures/Array_and_String/209_MinimumSizeSubarray/solution.py new file mode 100644 index 0000000..d899496 --- /dev/null +++ b/DataStractures/Array_and_String/209_MinimumSizeSubarray/solution.py @@ -0,0 +1,21 @@ +from ast import List + + +class Solution: + def minSubArrayLen(self, target: int, nums: List[int]) -> int: + left = 0 + right = 0 + sumOfCurrentWindow = 0 + res = float('inf') + + for right in range(0, len(nums)): + sumOfCurrentWindow += nums[right] + + while sumOfCurrentWindow >= target: + res = min(res, right - left + 1) + sumOfCurrentWindow -= nums[left] + left += 1 + + return res if res != float('inf') else 0 + #209 + diff --git a/DataStractures/Array_and_String/242_ValidAnagram/description.md b/DataStractures/Array_and_String/242_ValidAnagram/description.md new file mode 100644 index 0000000..f098a2a --- /dev/null +++ b/DataStractures/Array_and_String/242_ValidAnagram/description.md @@ -0,0 +1,29 @@ +### 242. Valid Anagram +|Easy + +Given two strings s and t, return true if t is an anagram of s, and false otherwise. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + + + +Example 1: +`````` +Input: s = "anagram", t = "nagaram" +Output: true +``` +Example 2: +``` +Input: s = "rat", t = "car" +Output: false +``` + +### Constraints: + +1 <= s.length, t.length <= 5 * 104 + +s and t consist of lowercase English letters. + + +### Follow up: +What if the inputs contain Unicode characters? How would you adapt your solution to such a case? \ No newline at end of file diff --git a/DataStractures/Array_and_String/242_ValidAnagram/solution.py b/DataStractures/Array_and_String/242_ValidAnagram/solution.py new file mode 100644 index 0000000..7b36ed9 --- /dev/null +++ b/DataStractures/Array_and_String/242_ValidAnagram/solution.py @@ -0,0 +1,6 @@ +from collections import Counter + + +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + return Counter(s) == Counter(t) \ No newline at end of file diff --git a/DataStractures/Array_and_String/2469_ConverttheTemperature/description.md b/DataStractures/Array_and_String/2469_ConverttheTemperature/description.md new file mode 100644 index 0000000..4558a74 --- /dev/null +++ b/DataStractures/Array_and_String/2469_ConverttheTemperature/description.md @@ -0,0 +1,31 @@ +### 2469. Convert the Temperature +|Easy + +You are given a non-negative floating point number rounded to two decimal places celsius, that denotes the temperature in Celsius. + +You should convert Celsius into Kelvin and Fahrenheit and return it as an array ans = [kelvin, fahrenheit]. + +Return the array ans. Answers within 10-5 of the actual answer will be accepted. + +Note that: + +Kelvin = Celsius + 273.15 +Fahrenheit = Celsius * 1.80 + 32.00 + + +Example 1: +``` +Input: celsius = 36.50 +Output: [309.65000,97.70000] +Explanation: Temperature at 36.50 Celsius converted in Kelvin is 309.65 and converted in Fahrenheit is 97.70. +``` +Example 2: +``` +Input: celsius = 122.11 +Output: [395.26000,251.79800] +Explanation: Temperature at 122.11 Celsius converted in Kelvin is 395.26 and converted in Fahrenheit is 251.798. +``` + +### Constraints: + +0 <= celsius <= 1000 \ No newline at end of file diff --git a/DataStractures/Array_and_String/2469_ConverttheTemperature/solution.py b/DataStractures/Array_and_String/2469_ConverttheTemperature/solution.py new file mode 100644 index 0000000..643d4bf --- /dev/null +++ b/DataStractures/Array_and_String/2469_ConverttheTemperature/solution.py @@ -0,0 +1,7 @@ +from ast import List + + +class Solution: + def convertTemperature(self, celsius: float) -> List[float]: + + return [celsius+273.15,celsius*1.80+32.00] \ No newline at end of file diff --git a/DataStractures/Array_and_String/28_FindTheIndexOfTheFirstOccurrenceInaString/description.md b/DataStractures/Array_and_String/28_FindTheIndexOfTheFirstOccurrenceInaString/description.md new file mode 100644 index 0000000..9507ce1 --- /dev/null +++ b/DataStractures/Array_and_String/28_FindTheIndexOfTheFirstOccurrenceInaString/description.md @@ -0,0 +1,26 @@ +### 28. Find the Index of the First Occurrence in a String +|Easy + +Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. + + + +Example 1: +``` +Input: haystack = "sadbutsad", needle = "sad" +Output: 0 +Explanation: "sad" occurs at index 0 and 6. +The first occurrence is at index 0, so we return 0. +``` +Example 2: +``` +Input: haystack = "leetcode", needle = "leeto" +Output: -1 +Explanation: "leeto" did not occur in "leetcode", so we return -1. +``` + +### Constraints: + +1 <= haystack.length, needle.length <= 104 + +haystack and needle consist of only lowercase English characters. \ No newline at end of file diff --git a/DataStractures/Array_and_String/28_FindTheIndexOfTheFirstOccurrenceInaString/solution.py b/DataStractures/Array_and_String/28_FindTheIndexOfTheFirstOccurrenceInaString/solution.py new file mode 100644 index 0000000..7d57030 --- /dev/null +++ b/DataStractures/Array_and_String/28_FindTheIndexOfTheFirstOccurrenceInaString/solution.py @@ -0,0 +1,10 @@ +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + + top=len(needle) + for i in range(len(haystack)): + if haystack[i:top+i]==needle: + return i + else: + return -1 + #28 diff --git a/DataStractures/Array_and_String/344_ReverseString/description.md b/DataStractures/Array_and_String/344_ReverseString/description.md new file mode 100644 index 0000000..dc3803d --- /dev/null +++ b/DataStractures/Array_and_String/344_ReverseString/description.md @@ -0,0 +1,25 @@ +### 344. Reverse String +|Easy + +Write a function that reverses a string. The input string is given as an array of characters s. + +You must do this by modifying the input array in-place with O(1) extra memory. + + + +Example 1: +``` +Input: s = ["h","e","l","l","o"] +Output: ["o","l","l","e","h"] +``` +Example 2: +``` +Input: s = ["H","a","n","n","a","h"] +Output: ["h","a","n","n","a","H"] +``` + +### Constraints: + +1 <= s.length <= 105 + +s[i] is a printable ascii character. \ No newline at end of file diff --git a/DataStractures/Array_and_String/344_ReverseString/solution.py b/DataStractures/Array_and_String/344_ReverseString/solution.py new file mode 100644 index 0000000..ae3a8b5 --- /dev/null +++ b/DataStractures/Array_and_String/344_ReverseString/solution.py @@ -0,0 +1,15 @@ +from ast import List + + +class Solution: + def reverseString(self, s: List[str]) -> None: + """ + Do not return anything, modify s in-place instead. + """ + left, right = 0, len(s) - 1 + while left < right: + s[left], s[right] = s[right], s[left] + left += 1 + right -= 1 + #344 + diff --git a/DataStractures/Array_and_String/498_DiagonalTraverse/description.md b/DataStractures/Array_and_String/498_DiagonalTraverse/description.md new file mode 100644 index 0000000..87d6eb1 --- /dev/null +++ b/DataStractures/Array_and_String/498_DiagonalTraverse/description.md @@ -0,0 +1,29 @@ +### 498. Diagonal Traverse +|Medium + +Given an m x n matrix mat, return an array of all the elements of the array in a diagonal order. + + + +Example 1: +``` +Input: mat = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,2,4,7,5,3,6,8,9] +``` +Example 2: +``` +Input: mat = [[1,2],[3,4]] +Output: [1,2,3,4] +``` + +### Constraints: + +m == mat.length + +n == mat[i].length + +1 <= m, n <= 104 + +1 <= m * n <= 104 + +-105 <= mat[i][j] <= 105 \ No newline at end of file diff --git a/DataStractures/Array_and_String/498_DiagonalTraverse/solution.py b/DataStractures/Array_and_String/498_DiagonalTraverse/solution.py new file mode 100644 index 0000000..c152b16 --- /dev/null +++ b/DataStractures/Array_and_String/498_DiagonalTraverse/solution.py @@ -0,0 +1,19 @@ +import collections + + +class Solution: + def findDiagonalOrder(self, matrix: list[list[int]]) -> list[int]: + result = [ ] + dd = collections.defaultdict(list) + if not matrix: return result + # Step 1: Numbers are grouped by the diagonals. + # Numbers in same diagonal have same value of row+col + for i in range(0, len(matrix)): + for j in range(0, len(matrix[0])): + dd[i+j+1].append(matrix[i][j]) # starting indices from 1, hence i+j+1. + # Step 2: Place diagonals in the result list. + # But remember to reverse numbers in odd diagonals. + for k in sorted(dd.keys()): + if k%2==1: dd[k].reverse() + result += dd[k] + return result \ No newline at end of file diff --git a/DataStractures/Array_and_String/54_ SpiralMatrix/descrbtion.md b/DataStractures/Array_and_String/54_ SpiralMatrix/descrbtion.md new file mode 100644 index 0000000..26ce83a --- /dev/null +++ b/DataStractures/Array_and_String/54_ SpiralMatrix/descrbtion.md @@ -0,0 +1,26 @@ +### 54. Spiral Matrix +|Medium + +Given an m x n matrix, return all elements of the matrix in spiral order. + + +Example 1: +``` +Input: matrix = [[1,2,3],[4,5,6],[7,8,9]] +Output: [1,2,3,6,9,8,7,4,5] +``` +Example 2: +``` +Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]] +Output: [1,2,3,4,8,12,11,10,9,5,6,7] +``` + +### Constraints: + +m == matrix.length + +n == matrix[i].length + +1 <= m, n <= 10 + +-100 <= matrix[i][j] <= 100 \ No newline at end of file diff --git a/DataStractures/Array_and_String/54_ SpiralMatrix/solution.py b/DataStractures/Array_and_String/54_ SpiralMatrix/solution.py new file mode 100644 index 0000000..4b68ad9 --- /dev/null +++ b/DataStractures/Array_and_String/54_ SpiralMatrix/solution.py @@ -0,0 +1,26 @@ +class Solution: + def spiralOrder(self, matrix: list[list[int]]) -> list[int]: + left, right, top, bottom = 0, len(matrix[0])-1, 0, len(matrix)-1 + res = [] + + while left<=right and top<=bottom: + + for i in range(left, right+1): + res.append(matrix[top][i]) + top += 1 + + for i in range(top, bottom+1): + res.append(matrix[i][right]) + right -= 1 + + if left>right or top>bottom: + break + + for i in range(right, left-1, -1): + res.append(matrix[bottom][i]) + bottom -= 1 + + for i in range(bottom, top-1, -1): + res.append(matrix[i][left]) + left += 1 + return res \ No newline at end of file diff --git a/DataStractures/Array_and_String/561_ArrayPartition/description.md b/DataStractures/Array_and_String/561_ArrayPartition/description.md new file mode 100644 index 0000000..f121aab --- /dev/null +++ b/DataStractures/Array_and_String/561_ArrayPartition/description.md @@ -0,0 +1,31 @@ +### 561. Array Partition +|Easy + +Given an integer array nums of 2n integers, group these integers into n pairs (a1, b1), (a2, b2), ..., (an, bn) such that the sum of min(ai, bi) for all i is maximized. Return the maximized sum. + + + +Example 1: +``` +Input: nums = [1,4,3,2] +Output: 4 +Explanation: All possible pairings (ignoring the ordering of elements) are: +1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3 +2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3 +3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4 +So the maximum possible sum is 4. +`` +Example 2: +``` +Input: nums = [6,2,6,5,1,2] +Output: 9 +Explanation: The optimal pairing is (2, 1), (2, 5), (6, 6). min(2, 1) + min(2, 5) + min(6, 6) = 1 + 2 + 6 = 9. +``` + +### Constraints: + +1 <= n <= 104 + +nums.length == 2 * n + +-104 <= nums[i] <= 104 \ No newline at end of file diff --git a/DataStractures/Array_and_String/561_ArrayPartition/solution.py b/DataStractures/Array_and_String/561_ArrayPartition/solution.py new file mode 100644 index 0000000..abe5ec0 --- /dev/null +++ b/DataStractures/Array_and_String/561_ArrayPartition/solution.py @@ -0,0 +1,16 @@ +from ast import List + + +class Solution: + def arrayPairSum(self, nums: List[int]) -> int: + nums = sorted(nums) + l,r = 0, 1 + max_sum=0 + while r < (len(nums)): + max_sum += min(nums[l], nums[r]) + l+= 2 + r+= 2 + return max_sum + #approach2 + #return sum(sorted(nums)[::2]) + #561 diff --git a/DataStractures/Array_and_String/66_PlusOne/description.md b/DataStractures/Array_and_String/66_PlusOne/description.md new file mode 100644 index 0000000..bf92ee7 --- /dev/null +++ b/DataStractures/Array_and_String/66_PlusOne/description.md @@ -0,0 +1,41 @@ +### 66. Plus One +|Easy + +You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0's. + +Increment the large integer by one and return the resulting array of digits. + + + +Example 1: +``` +Input: digits = [1,2,3] +Output: [1,2,4] +Explanation: The array represents the integer 123. +Incrementing by one gives 123 + 1 = 124. +Thus, the result should be [1,2,4]. +``` +Example 2: +``` +Input: digits = [4,3,2,1] +Output: [4,3,2,2] +Explanation: The array represents the integer 4321. +Incrementing by one gives 4321 + 1 = 4322. +Thus, the result should be [4,3,2,2]. +``` +Example 3: +``` +Input: digits = [9] +Output: [1,0] +Explanation: The array represents the integer 9. +Incrementing by one gives 9 + 1 = 10. +Thus, the result should be [1,0]. +``` + +### Constraints: + +1 <= digits.length <= 100 + +0 <= digits[i] <= 9 + +digits does not contain any leading 0's. \ No newline at end of file diff --git a/DataStractures/Array_and_String/66_PlusOne/solution.py b/DataStractures/Array_and_String/66_PlusOne/solution.py new file mode 100644 index 0000000..17c3207 --- /dev/null +++ b/DataStractures/Array_and_String/66_PlusOne/solution.py @@ -0,0 +1,25 @@ +class Solution: + def plusOne(self, digits: list[int]) -> list[int]: + sums = digits[-1] + 1 + carry = 1 if sums > 9 else 0 + digits[-1] = 0 if sums > 9 else sums + + for i in range(len(digits)-2, -1, -1): + if digits[i] + carry > 9: + carry = 1 + digits[i] = 0 + else: + digits[i] = digits[i] + carry + carry = 0 + + if carry == 1: + digits.append(1) + return digits[::-1] + + return digits + +class Solution: + def plusOne(self, digits: list[int]) -> list[int]: + num=int(''.join(str(e)for e in digits))+1 + res = map(int,str(num)) + return res \ No newline at end of file diff --git a/DataStractures/Array_and_String/67_AddBinary/description.md b/DataStractures/Array_and_String/67_AddBinary/description.md new file mode 100644 index 0000000..33ac785 --- /dev/null +++ b/DataStractures/Array_and_String/67_AddBinary/description.md @@ -0,0 +1,25 @@ +### 67. Add Binary +|Easy + +Given two binary strings a and b, return their sum as a binary string. + + + +Example 1: +``` +Input: a = "11", b = "1" +Output: "100" +``` +Example 2: +``` +Input: a = "1010", b = "1011" +Output: "10101" +``` + +### Constraints: + +1 <= a.length, b.length <= 104 + +a and b consist only of '0' or '1' characters. + +Each string does not contain leading zeros except for the zero itself. \ No newline at end of file diff --git a/DataStractures/Array_and_String/67_AddBinary/solution.py b/DataStractures/Array_and_String/67_AddBinary/solution.py new file mode 100644 index 0000000..c69c35a --- /dev/null +++ b/DataStractures/Array_and_String/67_AddBinary/solution.py @@ -0,0 +1,7 @@ +class Solution: + def addBinary(self, a: str, b: str) -> str: + num_a=int(a, 2) + num_b=int(b, 2) + res=bin(num_a+num_b) + return res[2:] + #67 diff --git a/DataStractures/Array_and_String/724_PivotIndex/description.md b/DataStractures/Array_and_String/724_PivotIndex/description.md new file mode 100644 index 0000000..d07aa3b --- /dev/null +++ b/DataStractures/Array_and_String/724_PivotIndex/description.md @@ -0,0 +1,47 @@ +### 724. Find Pivot Index +|Easy + +Given an array of integers nums, calculate the pivot index of this array. + +The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. + +If the index is on the left edge of the array, then the left sum is 0 because there are no elements to the left. This also applies to the right edge of the array. + +Return the leftmost pivot index. If no such index exists, return -1. + + + +Example 1: +``` +Input: nums = [1,7,3,6,5,6] +Output: 3 +Explanation: +The pivot index is 3. +Left sum = nums[0] + nums[1] + nums[2] = 1 + 7 + 3 = 11 +Right sum = nums[4] + nums[5] = 5 + 6 = 11 +``` +Example 2: +``` +Input: nums = [1,2,3] +Output: -1 +Explanation: +There is no index that satisfies the conditions in the problem statement. +``` +Example 3: +``` +Input: nums = [2,1,-1] +Output: 0 +Explanation: +The pivot index is 0. +Left sum = 0 (no elements to the left of index 0) +Right sum = nums[1] + nums[2] = 1 + -1 = 0 +``` + +### Constraints: + +1 <= nums.length <= 104 + +-1000 <= nums[i] <= 1000 + + +Note: This question is the same as 1991: https://leetcode.com/problems/find-the-middle-index-in-array/ \ No newline at end of file diff --git a/DataStractures/Array_and_String/724_PivotIndex/solution.py b/DataStractures/Array_and_String/724_PivotIndex/solution.py new file mode 100644 index 0000000..bb47f2b --- /dev/null +++ b/DataStractures/Array_and_String/724_PivotIndex/solution.py @@ -0,0 +1,12 @@ +class Solution(object): + def pivotIndex(self, nums): + # Initialize leftSum & rightSum to store the sum of all the numbers strictly to the index's left & right respectively... + leftSum, rightSum = 0, sum(nums) + # Traverse elements through the loop... + for idx, ele in enumerate(nums): + rightSum -= ele + # If the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right... + if leftSum == rightSum: + return idx # Return the pivot index... + leftSum += ele + return -1 # If there is no index that satisfies the conditions in the problem statement... \ No newline at end of file diff --git a/DataStractures/Array_and_String/747_LargestNumberAtLeastTwiceOfOthers/description.md b/DataStractures/Array_and_String/747_LargestNumberAtLeastTwiceOfOthers/description.md new file mode 100644 index 0000000..702a8b2 --- /dev/null +++ b/DataStractures/Array_and_String/747_LargestNumberAtLeastTwiceOfOthers/description.md @@ -0,0 +1,31 @@ +### 747. Largest Number At Least Twice of Others +|Easy + +You are given an integer array nums where the largest integer is unique. + +Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, or return -1 otherwise. + + + +Example 1: +``` +Input: nums = [3,6,1,0] +Output: 1 +Explanation: 6 is the largest integer. +For every other number in the array x, 6 is at least twice as big as x. +The index of value 6 is 1, so we return 1. +``` +Example 2: +``` +Input: nums = [1,2,3,4] +Output: -1 +Explanation: 4 is less than twice the value of 3, so we return -1. +``` + +### Constraints: + +2 <= nums.length <= 50 + +0 <= nums[i] <= 100 + +The largest element in nums is unique. \ No newline at end of file diff --git a/DataStractures/Array_and_String/747_LargestNumberAtLeastTwiceOfOthers/solution.py b/DataStractures/Array_and_String/747_LargestNumberAtLeastTwiceOfOthers/solution.py new file mode 100644 index 0000000..d69b51e --- /dev/null +++ b/DataStractures/Array_and_String/747_LargestNumberAtLeastTwiceOfOthers/solution.py @@ -0,0 +1,8 @@ +class Solution: + def dominantIndex(self, nums: list[int]) -> int: + m = max(nums) + i = nums.index(m) + nums.remove(m) + if 2*max(nums) <= m : + return i + return -1 \ No newline at end of file diff --git a/DataStractures/Array_and_String/771_JewelsandStones/description.md b/DataStractures/Array_and_String/771_JewelsandStones/description.md new file mode 100644 index 0000000..91a1ddb --- /dev/null +++ b/DataStractures/Array_and_String/771_JewelsandStones/description.md @@ -0,0 +1,27 @@ +### 771. Jewels and Stones +|Easy + +You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. + +Letters are case sensitive, so "a" is considered a different type of stone from "A". + + + +Example 1: +``` +Input: jewels = "aA", stones = "aAAbbbb" +Output: 3 +``` +Example 2: +``` +Input: jewels = "z", stones = "ZZ" +Output: 0 +``` + +### Constraints: + +1 <= jewels.length, stones.length <= 50 + +jewels and stones consist of only English letters. + +All the characters of jewels are unique. \ No newline at end of file diff --git a/DataStractures/Array_and_String/771_JewelsandStones/solution.py b/DataStractures/Array_and_String/771_JewelsandStones/solution.py new file mode 100644 index 0000000..61a6478 --- /dev/null +++ b/DataStractures/Array_and_String/771_JewelsandStones/solution.py @@ -0,0 +1,6 @@ +from collections import Counter + + +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + return sum(Counter(stones)[i] for i in jewels) \ No newline at end of file diff --git a/DataStractures/Array_and_String/7_ReverseInteger/description.md b/DataStractures/Array_and_String/7_ReverseInteger/description.md new file mode 100644 index 0000000..6ad8869 --- /dev/null +++ b/DataStractures/Array_and_String/7_ReverseInteger/description.md @@ -0,0 +1,28 @@ +### 7. Reverse Integer +Medium + +Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. + +Assume the environment does not allow you to store 64-bit integers (signed or unsigned). + + + +Example 1: +``` +Input: x = 123 +Output: 321 +``` +Example 2: +``` +Input: x = -123 +Output: -321 +``` +Example 3: +``` +Input: x = 120 +Output: 21 +``` + +### Constraints: + +-231 <= x <= 231 - 1 \ No newline at end of file diff --git a/DataStractures/Array_and_String/7_ReverseInteger/solution.py b/DataStractures/Array_and_String/7_ReverseInteger/solution.py new file mode 100644 index 0000000..c4a102d --- /dev/null +++ b/DataStractures/Array_and_String/7_ReverseInteger/solution.py @@ -0,0 +1,5 @@ +class Solution: + def reverse(self, x: int) -> int: + s = str(x) + res = int('-' + s[1:][::-1]) if s[0] == '-' else int(s[::-1]) + return res if -2147483648 <= res <= 2147483647 else 0 \ No newline at end of file diff --git a/DataStractures/Binary Tree/104_MaximumDepthofBinaryTree/description.md b/DataStractures/Binary Tree/104_MaximumDepthofBinaryTree/description.md new file mode 100644 index 0000000..9378045 --- /dev/null +++ b/DataStractures/Binary Tree/104_MaximumDepthofBinaryTree/description.md @@ -0,0 +1,25 @@ +### 104. Maximum Depth of Binary Tree +|Easy + +Given the root of a binary tree, return its maximum depth. + +A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. + + + +Example 1: +``` +Input: root = [3,9,20,null,null,15,7] +Output: 3 +``` +Example 2: +``` +Input: root = [1,null,2] +Output: 2 +``` + +### Constraints: + +The number of nodes in the tree is in the range [0, 104]. + +-100 <= Node.val <= 100 \ No newline at end of file diff --git a/DataStractures/Binary Tree/104_MaximumDepthofBinaryTree/solution.py b/DataStractures/Binary Tree/104_MaximumDepthofBinaryTree/solution.py new file mode 100644 index 0000000..71f6083 --- /dev/null +++ b/DataStractures/Binary Tree/104_MaximumDepthofBinaryTree/solution.py @@ -0,0 +1,14 @@ +# 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 maxDepth(self, root: list[TreeNode]) -> int: + # base case: if the root is None, return 0 + if root is None: + return 0 + + # recursive case: return the maximum of the depth of the left and right subtrees plus 1 + return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1 diff --git a/DataStractures/HashTable/136_Single Number/description.md b/DataStractures/HashTable/136_Single Number/description.md new file mode 100644 index 0000000..af9227f --- /dev/null +++ b/DataStractures/HashTable/136_Single Number/description.md @@ -0,0 +1,28 @@ +136. Single Number +Easy + +Given a non-empty array of integers nums, every element appears twice except for one. Find that single one. + +You must implement a solution with a linear runtime complexity and use only constant extra space. + + + +Example 1: + +Input: nums = [2,2,1] +Output: 1 +Example 2: + +Input: nums = [4,1,2,1,2] +Output: 4 +Example 3: + +Input: nums = [1] +Output: 1 + + +Constraints: + +1 <= nums.length <= 3 * 104 +-3 * 104 <= nums[i] <= 3 * 104 +Each element in the array appears twice except for one element which appears only once. \ No newline at end of file diff --git a/DataStractures/HashTable/136_Single Number/solution.py b/DataStractures/HashTable/136_Single Number/solution.py new file mode 100644 index 0000000..7de1ba7 --- /dev/null +++ b/DataStractures/HashTable/136_Single Number/solution.py @@ -0,0 +1,9 @@ +from ast import List +from collections import Counter + +class Solution: + def singleNumber(self, nums: List[int]) -> int: + s = Counter(nums).most_common() + return s[-1][0] + #136 + \ No newline at end of file diff --git a/DataStractures/HashTable/202_HappyNumber/description.md b/DataStractures/HashTable/202_HappyNumber/description.md new file mode 100644 index 0000000..369cb9e --- /dev/null +++ b/DataStractures/HashTable/202_HappyNumber/description.md @@ -0,0 +1,32 @@ +202. Happy Number +Easy + +Write an algorithm to determine if a number n is happy. + +A happy number is a number defined by the following process: + +Starting with any positive integer, replace the number by the sum of the squares of its digits. +Repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. +Those numbers for which this process ends in 1 are happy. +Return true if n is a happy number, and false if not. + + + +Example 1: + +Input: n = 19 +Output: true +Explanation: +12 + 92 = 82 +82 + 22 = 68 +62 + 82 = 100 +12 + 02 + 02 = 1 +Example 2: + +Input: n = 2 +Output: false + + +Constraints: + +1 <= n <= 231 - 1 \ No newline at end of file diff --git a/DataStractures/HashTable/202_HappyNumber/solution.py b/DataStractures/HashTable/202_HappyNumber/solution.py new file mode 100644 index 0000000..58091f9 --- /dev/null +++ b/DataStractures/HashTable/202_HappyNumber/solution.py @@ -0,0 +1,12 @@ +class Solution: + def isHappy(self, n: int) -> bool: + visited = set() + while True: + if n==1: + return True + elif n in visited: + return False + else: + visited.add(n) + n = sum(int(i)**2 for i in str(n)) + #202 \ No newline at end of file diff --git a/DataStractures/HashTable/205_IsomorphicStrings/description.md b/DataStractures/HashTable/205_IsomorphicStrings/description.md new file mode 100644 index 0000000..a711713 --- /dev/null +++ b/DataStractures/HashTable/205_IsomorphicStrings/description.md @@ -0,0 +1,30 @@ +205. Isomorphic Strings +Easy + +Given two strings s and t, determine if they are isomorphic. + +Two strings s and t are isomorphic if the characters in s can be replaced to get t. + +All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character, but a character may map to itself. + + + +Example 1: + +Input: s = "egg", t = "add" +Output: true +Example 2: + +Input: s = "foo", t = "bar" +Output: false +Example 3: + +Input: s = "paper", t = "title" +Output: true + + +Constraints: + +1 <= s.length <= 5 * 104 +t.length == s.length +s and t consist of any valid ascii character. \ No newline at end of file diff --git a/DataStractures/HashTable/205_IsomorphicStrings/solution.py b/DataStractures/HashTable/205_IsomorphicStrings/solution.py new file mode 100644 index 0000000..a010846 --- /dev/null +++ b/DataStractures/HashTable/205_IsomorphicStrings/solution.py @@ -0,0 +1,21 @@ +class Solution: + def isIsomorphic(self, s: str, t: str) -> bool: + #Approach01 + hashmap = {} + for i , j in zip(s, t): + if i in hashmap: + if hashmap[i]!=j: + return False + elif j in hashmap.values(): + return False + else: + hashmap[i]= j + + return True + + #Approach 02 + # m1 = [s.index(i) for i in s] + # m2 = [t.index(i)for i in t] + # print(m1, m2) + # return m1==m2 + #205 \ No newline at end of file diff --git a/DataStractures/HashTable/217_ContainsDuplicate/description.md b/DataStractures/HashTable/217_ContainsDuplicate/description.md new file mode 100644 index 0000000..2d7bbe2 --- /dev/null +++ b/DataStractures/HashTable/217_ContainsDuplicate/description.md @@ -0,0 +1,25 @@ +217. Contains Duplicate +Easy + +Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct. + + + +Example 1: + +Input: nums = [1,2,3,1] +Output: true +Example 2: + +Input: nums = [1,2,3,4] +Output: false +Example 3: + +Input: nums = [1,1,1,3,3,4,3,2,4,2] +Output: true + + +Constraints: + +1 <= nums.length <= 105 +-109 <= nums[i] <= 109 \ No newline at end of file diff --git a/DataStractures/HashTable/217_ContainsDuplicate/solution.py b/DataStractures/HashTable/217_ContainsDuplicate/solution.py new file mode 100644 index 0000000..7af947e --- /dev/null +++ b/DataStractures/HashTable/217_ContainsDuplicate/solution.py @@ -0,0 +1,8 @@ +from ast import List + + +class Solution: + def containsDuplicate(self, nums: List[int]) -> bool: + numSet = list(set(nums)) + return not (len(numSet) == len(nums)) + #217 \ No newline at end of file diff --git a/DataStractures/HashTable/219_ContainsDuplicateII/description.md b/DataStractures/HashTable/219_ContainsDuplicateII/description.md new file mode 100644 index 0000000..48562a3 --- /dev/null +++ b/DataStractures/HashTable/219_ContainsDuplicateII/description.md @@ -0,0 +1,30 @@ +### 219. Contains Duplicate II +|Easy + +Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= 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: false +``` + +### Constraints: + +1 <= nums.length <= 105 + +-109 <= nums[i] <= 109 + +0 <= k <= 105 \ No newline at end of file diff --git a/DataStractures/HashTable/219_ContainsDuplicateII/solution.py b/DataStractures/HashTable/219_ContainsDuplicateII/solution.py new file mode 100644 index 0000000..e0a516f --- /dev/null +++ b/DataStractures/HashTable/219_ContainsDuplicateII/solution.py @@ -0,0 +1,14 @@ +from ast import List + + +class Solution: + def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: + + seen={} + for idx,x in enumerate(nums): + + if x in seen and idx - seen[x]<=k: + return True + else: + seen[x]=idx + #219 \ No newline at end of file diff --git a/DataStractures/HashTable/2325_DecodetheMessage/description.md b/DataStractures/HashTable/2325_DecodetheMessage/description.md new file mode 100644 index 0000000..ff15f25 --- /dev/null +++ b/DataStractures/HashTable/2325_DecodetheMessage/description.md @@ -0,0 +1,39 @@ +### 2325. Decode the Message +|Easy +You are given the strings key and message, which represent a cipher key and a secret message, respectively. The steps to decode message are as follows: + +Use the first appearance of all 26 lowercase English letters in key as the order of the substitution table. +Align the substitution table with the regular English alphabet. +Each letter in message is then substituted using the table. +Spaces ' ' are transformed to themselves. +For example, given key = "happy boy" (actual key would have at least one instance of each letter in the alphabet), we have the partial substitution table of ('h' -> 'a', 'a' -> 'b', 'p' -> 'c', 'y' -> 'd', 'b' -> 'e', 'o' -> 'f'). +Return the decoded message. + + + +Example 1: +``` +Input: key = "the quick brown fox jumps over the lazy dog", message = "vkbs bs t suepuv" +Output: "this is a secret" +Explanation: The diagram above shows the substitution table. +It is obtained by taking the first appearance of each letter in "the quick brown fox jumps over the lazy dog". +``` +Example 2: +``` +Input: key = "eljuxhpwnyrdgtqkviszcfmabo", message = "zwx hnfx lqantp mnoeius ycgk vcnjrdb" +Output: "the five boxing wizards jump quickly" +Explanation: The diagram above shows the substitution table. +It is obtained by taking the first appearance of each letter in "eljuxhpwnyrdgtqkviszcfmabo". +``` + +### Constraints: + +26 <= key.length <= 2000 + +key consists of lowercase English letters and ' '. + +key contains every letter in the English alphabet ('a' to 'z') at least once. + +1 <= message.length <= 2000 + +message consists of lowercase English letters and ' '. \ No newline at end of file diff --git a/DataStractures/HashTable/2325_DecodetheMessage/solution.py b/DataStractures/HashTable/2325_DecodetheMessage/solution.py new file mode 100644 index 0000000..73f295e --- /dev/null +++ b/DataStractures/HashTable/2325_DecodetheMessage/solution.py @@ -0,0 +1,16 @@ +class Solution: + def decodeMessage(self, key: str, message: str) -> str: + lookup = {" ":" "} + i = 0 + ans = "" + alphabets = 'abcdefghijklmnopqrstuvwxyz' + + for char in key: + if char not in lookup: + lookup[char] = alphabets[i] + i += 1 + + for char in message: + ans += lookup[char] + + return ans \ No newline at end of file diff --git a/DataStractures/HashTable/349_IntersectionofTwoArrays/description.md b/DataStractures/HashTable/349_IntersectionofTwoArrays/description.md new file mode 100644 index 0000000..a651a06 --- /dev/null +++ b/DataStractures/HashTable/349_IntersectionofTwoArrays/description.md @@ -0,0 +1,23 @@ +349. Intersection of Two Arrays +Easy + + +Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order. + + + +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] +Explanation: [4,9] is also accepted. + + +Constraints: + +1 <= nums1.length, nums2.length <= 1000 +0 <= nums1[i], nums2[i] <= 1000 \ No newline at end of file diff --git a/DataStractures/HashTable/349_IntersectionofTwoArrays/solution.py b/DataStractures/HashTable/349_IntersectionofTwoArrays/solution.py new file mode 100644 index 0000000..05db768 --- /dev/null +++ b/DataStractures/HashTable/349_IntersectionofTwoArrays/solution.py @@ -0,0 +1,6 @@ +from ast import List +class Solution: + def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]: + numset1, numset2 = set(nums1), set(nums2) + return(numset1.intersection(numset2)) + #349 \ No newline at end of file diff --git a/DataStractures/HashTable/350_IntersectionofTwoArraysII/description.md b/DataStractures/HashTable/350_IntersectionofTwoArraysII/description.md new file mode 100644 index 0000000..d57a675 --- /dev/null +++ b/DataStractures/HashTable/350_IntersectionofTwoArraysII/description.md @@ -0,0 +1,33 @@ +### 350. Intersection of Two Arrays II +|Easy + +Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must appear as many times as it shows in both arrays and you may return the result in any order. + + + +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] +Explanation: [9,4] is also accepted. +``` + +### Constraints: + +1 <= nums1.length, nums2.length <= 1000 + +0 <= nums1[i], nums2[i] <= 1000 + + +### Follow up: + +What if the given array is already sorted? How would you optimize your algorithm? + +What if nums1's size is small compared to nums2's size? Which algorithm is better? + +What if elements of nums2 are stored on disk, and the memory is limited such that you cannot load all elements into the memory at once? diff --git a/DataStractures/HashTable/350_IntersectionofTwoArraysII/solution.py b/DataStractures/HashTable/350_IntersectionofTwoArraysII/solution.py new file mode 100644 index 0000000..b45a994 --- /dev/null +++ b/DataStractures/HashTable/350_IntersectionofTwoArraysII/solution.py @@ -0,0 +1,11 @@ +from ast import List +from collections import Counter + + +class Solution: + def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]: + nums1_map=Counter(list(nums1)) + nums2_map=Counter(list(nums2)) + res=nums1_map & nums2_map + return res.elements() + #350 \ No newline at end of file diff --git a/DataStractures/HashTable/36_ValidSudoku/description.md b/DataStractures/HashTable/36_ValidSudoku/description.md new file mode 100644 index 0000000..bbd7015 --- /dev/null +++ b/DataStractures/HashTable/36_ValidSudoku/description.md @@ -0,0 +1,53 @@ +### 36. Valid Sudoku +|Medium + +Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: + +Each row must contain the digits 1-9 without repetition. +Each column must contain the digits 1-9 without repetition. +Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition. +Note: + +A Sudoku board (partially filled) could be valid but is not necessarily solvable. +Only the filled cells need to be validated according to the mentioned rules. + + +Example 1: +``` + +Input: board = +[["5","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +Output: true +``` +Example 2: +``` +Input: board = +[["8","3",".",".","7",".",".",".","."] +,["6",".",".","1","9","5",".",".","."] +,[".","9","8",".",".",".",".","6","."] +,["8",".",".",".","6",".",".",".","3"] +,["4",".",".","8",".","3",".",".","1"] +,["7",".",".",".","2",".",".",".","6"] +,[".","6",".",".",".",".","2","8","."] +,[".",".",".","4","1","9",".",".","5"] +,[".",".",".",".","8",".",".","7","9"]] +Output: false +``` +Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. + + +### Constraints: + +board.length == 9 + +board[i].length == 9 + +board[i][j] is a digit 1-9 or '.'. \ No newline at end of file diff --git a/DataStractures/HashTable/36_ValidSudoku/solution.py b/DataStractures/HashTable/36_ValidSudoku/solution.py new file mode 100644 index 0000000..cbe4674 --- /dev/null +++ b/DataStractures/HashTable/36_ValidSudoku/solution.py @@ -0,0 +1,25 @@ +from ast import List +from collections import defaultdict + + +class Solution: + def isValidSudoku(self, board: List[List[str]]) -> bool: + cols=defaultdict(set) + rows=defaultdict(set) + boxes=defaultdict(set) + + for r in range(9): + for c in range(9): + medium = board[r][c] + if medium==".": + continue + + if medium in rows[r] or medium in cols[c] or medium in boxes[(r//3), c//3]: + return False + + else: + cols[c].add(medium) + rows[r].add(medium) + boxes[(r//3), c//3].add(medium) + + return True \ No newline at end of file diff --git a/DataStractures/HashTable/380_InsertDeleteGetRandomO(1)/description.md b/DataStractures/HashTable/380_InsertDeleteGetRandomO(1)/description.md new file mode 100644 index 0000000..4d9b58e --- /dev/null +++ b/DataStractures/HashTable/380_InsertDeleteGetRandomO(1)/description.md @@ -0,0 +1,39 @@ +### 380. Insert Delete GetRandom O(1) +|Medium + +Implement the RandomizedSet class: + +RandomizedSet() Initializes the RandomizedSet object. +bool insert(int val) Inserts an item val into the set if not present. Returns true if the item was not present, false otherwise. +bool remove(int val) Removes an item val from the set if present. Returns true if the item was present, false otherwise. +int getRandom() Returns a random element from the current set of elements (it's guaranteed that at least one element exists when this method is called). Each element must have the same probability of being returned. +You must implement the functions of the class such that each function works in average O(1) time complexity. + + + +Example 1: +``` +Input +["RandomizedSet", "insert", "remove", "insert", "getRandom", "remove", "insert", "getRandom"] +[[], [1], [2], [2], [], [1], [2], []] +Output +[null, true, false, true, 2, true, false, 2] + +Explanation +RandomizedSet randomizedSet = new RandomizedSet(); +randomizedSet.insert(1); // Inserts 1 to the set. Returns true as 1 was inserted successfully. +randomizedSet.remove(2); // Returns false as 2 does not exist in the set. +randomizedSet.insert(2); // Inserts 2 to the set, returns true. Set now contains [1,2]. +randomizedSet.getRandom(); // getRandom() should return either 1 or 2 randomly. +randomizedSet.remove(1); // Removes 1 from the set, returns true. Set now contains [2]. +randomizedSet.insert(2); // 2 was already in the set, so return false. +randomizedSet.getRandom(); // Since 2 is the only number in the set, getRandom() will always return 2. +``` + +### Constraints: + +-231 <= val <= 231 - 1 + +At most 2 * 105 calls will be made to insert, remove, and getRandom. + +There will be at least one element in the data structure when getRandom is called. \ No newline at end of file diff --git a/DataStractures/HashTable/380_InsertDeleteGetRandomO(1)/solution.py b/DataStractures/HashTable/380_InsertDeleteGetRandomO(1)/solution.py new file mode 100644 index 0000000..feddd7f --- /dev/null +++ b/DataStractures/HashTable/380_InsertDeleteGetRandomO(1)/solution.py @@ -0,0 +1,69 @@ +import random + + +class RandomizedSet: + + def __init__(self): + self.data_map = {} # dictionary, aka map, aka hashtable, aka hashmap + self.data = [] # list aka array + + def insert(self, val: int) -> bool: + + # the problem indicates we need to return False if the item + # is already in the RandomizedSet---checking if it's in the + # dictionary is on average O(1) where as + # checking the array is on average O(n) + if val in self.data_map: + return False + + # add the element to the dictionary. Setting the value as the + # length of the list will accurately point to the index of the + # new element. (len(some_list) is equal to the index of the last item +1) + self.data_map[val] = len(self.data) + + # add to the list + self.data.append(val) + + return True + + def remove(self, val: int) -> bool: + + # again, if the item is not in the data_map, return False. + # we check the dictionary instead of the list due to lookup complexity + if not val in self.data_map: + return False + + # essentially, we're going to move the last element in the list + # into the location of the element we want to remove. + # this is a significantly more efficient operation than the obvious + # solution of removing the item and shifting the values of every item + # in the dicitionary to match their new position in the list + last_elem_in_list = self.data[-1] + index_of_elem_to_remove = self.data_map[val] + + self.data_map[last_elem_in_list] = index_of_elem_to_remove + self.data[index_of_elem_to_remove] = last_elem_in_list + + # change the last element in the list to now be the value of the element + # we want to remove + self.data[-1] = val + + # remove the last element in the list + self.data.pop() + + # remove the element to be removed from the dictionary + self.data_map.pop(val) + return True + + def getRandom(self) -> int: + # if running outside of leetcode, you need to `import random`. + # random.choice will randomly select an element from the list of data. + return random.choice(self.data) + #380 + + +# Your RandomizedSet object will be instantiated and called as such: +# obj = RandomizedSet() +# param_1 = obj.insert(val) +# param_2 = obj.remove(val) +# param_3 = obj.getRandom() \ No newline at end of file diff --git a/DataStractures/HashTable/387_FirstUniqueCharacterinaString/description.md b/DataStractures/HashTable/387_FirstUniqueCharacterinaString/description.md new file mode 100644 index 0000000..1e99554 --- /dev/null +++ b/DataStractures/HashTable/387_FirstUniqueCharacterinaString/description.md @@ -0,0 +1,28 @@ +### 387. First Unique Character in a String +|Easy + +Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1. + + + +Example 1: +``` +Input: s = "leetcode" +Output: 0 +``` +Example 2: +``` +Input: s = "loveleetcode" +Output: 2 +``` +Example 3: +``` +Input: s = "aabb" +Output: -1 +``` + +### Constraints: + +1 <= s.length <= 105 + +s consists of only lowercase English letters. diff --git a/DataStractures/HashTable/387_FirstUniqueCharacterinaString/solution.py b/DataStractures/HashTable/387_FirstUniqueCharacterinaString/solution.py new file mode 100644 index 0000000..a78ae3f --- /dev/null +++ b/DataStractures/HashTable/387_FirstUniqueCharacterinaString/solution.py @@ -0,0 +1,12 @@ +from collections import Counter + + +class Solution: + def firstUniqChar(self, s: str) -> int: + if len(s)<=0: return -1 + occurence_map=Counter(list(s)) + print(occurence_map) + for k,v in occurence_map.items(): + if v==1 :return s.index(k) + + return -1 \ No newline at end of file diff --git a/DataStractures/HashTable/3_LongestSubstringWithoutRepeatingCharacters/description.md b/DataStractures/HashTable/3_LongestSubstringWithoutRepeatingCharacters/description.md new file mode 100644 index 0000000..8d5a8be --- /dev/null +++ b/DataStractures/HashTable/3_LongestSubstringWithoutRepeatingCharacters/description.md @@ -0,0 +1,34 @@ +### 3. Longest Substring Without Repeating Characters +|Medium + +Given a string s, find the length of the longest +substring + without repeating characters. + + + +Example 1: +``` +Input: s = "abcabcbb" +Output: 3 +Explanation: The answer is "abc", with the length of 3. +``` +Example 2: +``` +Input: s = "bbbbb" +Output: 1 +Explanation: The answer is "b", with the length of 1. +``` +Example 3: +``` +Input: s = "pwwkew" +Output: 3 +Explanation: The answer is "wke", with the length of 3. +Notice that the answer must be a substring, "pwke" is a subsequence and not a substring. +``` + +### Constraints: + +0 <= s.length <= 5 * 104 + +s consists of English letters, digits, symbols and spaces. \ No newline at end of file diff --git a/DataStractures/HashTable/3_LongestSubstringWithoutRepeatingCharacters/solution.py b/DataStractures/HashTable/3_LongestSubstringWithoutRepeatingCharacters/solution.py new file mode 100644 index 0000000..a01b045 --- /dev/null +++ b/DataStractures/HashTable/3_LongestSubstringWithoutRepeatingCharacters/solution.py @@ -0,0 +1,11 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + + visited = {} # hash map of most recent position of each character that has appeared + start = longest = 0 + for i, char in enumerate(s): + if char in visited: + start = max(start, visited[char] + 1) + visited[char] = i + longest = max(longest, i - start + 1) + return longest \ No newline at end of file diff --git a/DataStractures/HashTable/454. 4Sum II/description.md b/DataStractures/HashTable/454. 4Sum II/description.md new file mode 100644 index 0000000..7e6745e --- /dev/null +++ b/DataStractures/HashTable/454. 4Sum II/description.md @@ -0,0 +1,39 @@ +### 454. 4Sum II +|Medium + +Given four integer arrays nums1, nums2, nums3, and nums4 all of length n, return the number of tuples (i, j, k, l) such that: + +0 <= i, j, k, l < n + +nums1[i] + nums2[j] + nums3[k] + nums4[l] == 0 + + +Example 1: +``` +Input: nums1 = [1,2], nums2 = [-2,-1], nums3 = [-1,2], nums4 = [0,2] +Output: 2 +Explanation: +The two tuples are: +1. (0, 0, 0, 1) -> nums1[0] + nums2[0] + nums3[0] + nums4[1] = 1 + (-2) + (-1) + 2 = 0 +2. (1, 1, 0, 0) -> nums1[1] + nums2[1] + nums3[0] + nums4[0] = 2 + (-1) + (-1) + 0 = 0 +``` +Example 2: +``` +Input: nums1 = [0], nums2 = [0], nums3 = [0], nums4 = [0] +Output: 1 +``` + + +### Constraints: + +n == nums1.length + +n == nums2.length + +n == nums3.length + +n == nums4.length + +1 <= n <= 200 + +-228 <= nums1[i], nums2[i], nums3[i], nums4[i] <= 228 \ No newline at end of file diff --git a/DataStractures/HashTable/454. 4Sum II/solution.py b/DataStractures/HashTable/454. 4Sum II/solution.py new file mode 100644 index 0000000..019a9d3 --- /dev/null +++ b/DataStractures/HashTable/454. 4Sum II/solution.py @@ -0,0 +1,20 @@ +from ast import List +from collections import defaultdict + + +class Solution: + def fourSumCount(self, nums1: List[int], nums2: List[int], nums3: List[int], nums4: List[int]) -> int: + lookup = defaultdict(int) + counter = 0 + + for i in nums1: + for j in nums2: + count = i+j + lookup[count]+= 1 + + for k in nums3: + for l in nums4: + count = -(k+l) + if count in lookup: + counter += lookup[count] + return counter \ No newline at end of file diff --git a/DataStractures/HashTable/49_GroupAnagrams/description.md b/DataStractures/HashTable/49_GroupAnagrams/description.md new file mode 100644 index 0000000..3f914fb --- /dev/null +++ b/DataStractures/HashTable/49_GroupAnagrams/description.md @@ -0,0 +1,32 @@ +### 49. Group Anagrams +|Medium + +Given an array of strings strs, group the anagrams together. You can return the answer in any order. + +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + + + +Example 1: +``` +Input: strs = ["eat","tea","tan","ate","nat","bat"] +Output: [["bat"],["nat","tan"],["ate","eat","tea"]] +``` +Example 2: +``` +Input: strs = [""] +Output: [[""]] +``` +Example 3: +``` +Input: strs = ["a"] +Output: [["a"]] +``` + +### Constraints: + +1 <= strs.length <= 104 + +0 <= strs[i].length <= 100 + +strs[i] consists of lowercase English letters. \ No newline at end of file diff --git a/DataStractures/HashTable/49_GroupAnagrams/solution.py b/DataStractures/HashTable/49_GroupAnagrams/solution.py new file mode 100644 index 0000000..0ebe944 --- /dev/null +++ b/DataStractures/HashTable/49_GroupAnagrams/solution.py @@ -0,0 +1,21 @@ +from ast import List +from collections import defaultdict + + +class Solution: + def groupAnagrams(self, strs: List[str]) -> List[List[str]]: + #Aproach 01 + lookup = defaultdict(list) + for i in strs: + lookup[tuple(sorted(i))].append(i) + return lookup.values() + #Approach 02 + # result = {} + # for s in strs: + # key = str(sorted(s)) + # if key in result: + # result[key] += [s] + # else: + # result[key] = [s] + # return list(result.values() + #49 \ No newline at end of file diff --git a/DataStractures/HashTable/599_MinimumIndexSumofTwoLists/description.md b/DataStractures/HashTable/599_MinimumIndexSumofTwoLists/description.md new file mode 100644 index 0000000..26d49fc --- /dev/null +++ b/DataStractures/HashTable/599_MinimumIndexSumofTwoLists/description.md @@ -0,0 +1,49 @@ +### 599. Minimum Index Sum of Two Lists +|Easy + +Given two arrays of strings list1 and list2, find the common strings with the least index sum. + +A common string is a string that appeared in both list1 and list2. + +A common string with the least index sum is a common string such that if it appeared at list1[i] and list2[j] then i + j should be the minimum value among all the other common strings. + +Return all the common strings with the least index sum. Return the answer in any order. + + + +Example 1: +``` +Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["Piatti","The Grill at Torrey Pines","Hungry Hunter Steakhouse","Shogun"] +Output: ["Shogun"] +Explanation: The only common string is "Shogun". +``` +Example 2: +``` +Input: list1 = ["Shogun","Tapioca Express","Burger King","KFC"], list2 = ["KFC","Shogun","Burger King"] +Output: ["Shogun"] +Explanation: The common string with the least index sum is "Shogun" with index sum = (0 + 1) = 1. +``` +Example 3: +``` +Input: list1 = ["happy","sad","good"], list2 = ["sad","happy","good"] +Output: ["sad","happy"] +Explanation: There are three common strings: +"happy" with index sum = (0 + 1) = 1. +"sad" with index sum = (1 + 0) = 1. +"good" with index sum = (2 + 2) = 4. +The strings with the least index sum are "sad" and "happy". +``` + +### Constraints: + +1 <= list1.length, list2.length <= 1000 + +1 <= list1[i].length, list2[i].length <= 30 + +list1[i] and list2[i] consist of spaces ' ' and English letters. + +All the strings of list1 are unique. + +All the strings of list2 are unique. + +There is at least a common string between list1 and list2. \ No newline at end of file diff --git a/DataStractures/HashTable/599_MinimumIndexSumofTwoLists/solution.py b/DataStractures/HashTable/599_MinimumIndexSumofTwoLists/solution.py new file mode 100644 index 0000000..2878fa0 --- /dev/null +++ b/DataStractures/HashTable/599_MinimumIndexSumofTwoLists/solution.py @@ -0,0 +1,36 @@ +from ast import List +class Solution: + def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]: +# lookup = {i:[list1.index(i)] for i in list1} +# for j in list2: +# if j in lookup: +# lookup[j].append(list2.index(j)) + +# temp = [] +# min_idx = 2000 + +# for k, v in lookup.items(): +# if len(lookup[k])==1: +# lookup[k]= [2000] +# elif len(lookup[k])>1: +# sum_idx = sum(i for i in lookup[k]) +# min_idx = min(sum_idx, min_idx) +# for k,v in lookup.items(): +# if sum(i for i in lookup[k])==min_idx: +# temp.append(k) +# return temp + + acc_len = len(list1)+len(list2) + lookup = {} + for word in list1: + if word in list2: + length = list1.index(word) + list2.index(word) + acc_len= min(acc_len, length) + lookup[word]= length + + result = [] + for k,v in lookup.items(): + if v == acc_len: + result.append(k) + return result + #599 \ No newline at end of file diff --git a/DataStractures/HashTable/652_FindDuplicateSubtrees/description.md b/DataStractures/HashTable/652_FindDuplicateSubtrees/description.md new file mode 100644 index 0000000..a97d6ac --- /dev/null +++ b/DataStractures/HashTable/652_FindDuplicateSubtrees/description.md @@ -0,0 +1,31 @@ +### 652. Find Duplicate Subtrees +|Medium + +Given the root of a binary tree, return all duplicate subtrees. + +For each kind of duplicate subtrees, you only need to return the root node of any one of them. + +Two trees are duplicate if they have the same structure with the same node values. + + + +Example 1: +``` +Input: root = [1,2,3,4,null,2,4,null,null,4] +Output: [[2,4],[4]] +``` +Example 2: +``` +Input: root = [2,1,1] +Output: [[1]] +``` +Example 3: +``` +Input: root = [2,2,2,3,null,3,null] +Output: [[2,3],[3]] +``` + +### Constraints: + +The number of the nodes in the tree will be in the range [1, 5000] +-200 <= Node.val <= 200 \ No newline at end of file diff --git a/DataStractures/HashTable/652_FindDuplicateSubtrees/solution.py b/DataStractures/HashTable/652_FindDuplicateSubtrees/solution.py new file mode 100644 index 0000000..cf667f4 --- /dev/null +++ b/DataStractures/HashTable/652_FindDuplicateSubtrees/solution.py @@ -0,0 +1,46 @@ +import collections +# 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 + +#Approach 01 +class Solution: + def findDuplicateSubtrees(self, root): + def traverse(node): + if not node: + return 0 + triplet = (traverse(node.left), node.val, traverse(node.right)) + if triplet not in triplet_to_id: + triplet_to_id[triplet] = len(triplet_to_id) + 1 + id = triplet_to_id[triplet] + cnt[id] += 1 + if cnt[id] == 2: + res.append(node) + return id + triplet_to_id = dict() + cnt = collections.defaultdict(int) + res = [] + traverse(root) + return res + #Approach 02 + class Solution: + def findDuplicateSubtrees(self, root): + def traverse(node): + if not node: + return 0 + triplet = (traverse(node.left), node.val, traverse(node.right)) + if triplet not in triplet_to_id: + triplet_to_id[triplet] = len(triplet_to_id) + 1 + id = triplet_to_id[triplet] + cnt[id] += 1 + if cnt[id] == 2: + res.append(node) + return id + triplet_to_id = dict() + cnt = collections.defaultdict(int) + res = [] + traverse(root) + return res \ No newline at end of file diff --git a/DataStractures/HashTable/705_DesignHashSet/description.md b/DataStractures/HashTable/705_DesignHashSet/description.md new file mode 100644 index 0000000..62c34b3 --- /dev/null +++ b/DataStractures/HashTable/705_DesignHashSet/description.md @@ -0,0 +1,37 @@ +### 705. Design HashSet +|Easy + +Design a HashSet without using any built-in hash table libraries. + +Implement MyHashSet class: + +void add(key) Inserts the value key into the HashSet. +bool contains(key) Returns whether the value key exists in the HashSet or not. +void remove(key) Removes the value key in the HashSet. If key does not exist in the HashSet, do nothing. + + +Example 1: +``` +Input +["MyHashSet", "add", "add", "contains", "contains", "add", "contains", "remove", "contains"] +[[], [1], [2], [1], [3], [2], [2], [2], [2]] +Output +[null, null, null, true, false, null, true, null, false] + +Explanation +MyHashSet myHashSet = new MyHashSet(); +myHashSet.add(1); // set = [1] +myHashSet.add(2); // set = [1, 2] +myHashSet.contains(1); // return True +myHashSet.contains(3); // return False, (not found) +myHashSet.add(2); // set = [1, 2] +myHashSet.contains(2); // return True +myHashSet.remove(2); // set = [1] +myHashSet.contains(2); // return False, (already removed) +``` + +### Constraints: + +0 <= key <= 106 + +At most 104 calls will be made to add, remove, and contains. \ No newline at end of file diff --git a/DataStractures/HashTable/705_DesignHashSet/solution.py b/DataStractures/HashTable/705_DesignHashSet/solution.py new file mode 100644 index 0000000..fc6e20a --- /dev/null +++ b/DataStractures/HashTable/705_DesignHashSet/solution.py @@ -0,0 +1,32 @@ +class MyHashSet: + + def __init__(self): + self.key=[] + + def add(self, key: int) -> None: + if key not in self.key: + self.key.append(key) + + + def remove(self, key: int) -> None: + if key in self.key: + self.key.remove(key) + + + + def contains(self, key: int) -> bool: + + return key in self.key +#705 + + + + + + + +# Your MyHashSet object will be instantiated and called as such: +# obj = MyHashSet() +# obj.add(key) +# obj.remove(key) +# param_3 = obj.contains(key) \ No newline at end of file diff --git a/DataStractures/HashTable/706_DesignHashMap/description.md b/DataStractures/HashTable/706_DesignHashMap/description.md new file mode 100644 index 0000000..272d53b --- /dev/null +++ b/DataStractures/HashTable/706_DesignHashMap/description.md @@ -0,0 +1,38 @@ +### 706. Design HashMap +|Easy + +Design a HashMap without using any built-in hash table libraries. + +Implement the MyHashMap class: + +MyHashMap() initializes the object with an empty map. +void put(int key, int value) inserts a (key, value) pair into the HashMap. If the key already exists in the map, update the corresponding value. +int get(int key) returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key. +void remove(key) removes the key and its corresponding value if the map contains the mapping for the key. + + +Example 1: +``` +Input +["MyHashMap", "put", "put", "get", "get", "put", "get", "remove", "get"] +[[], [1, 1], [2, 2], [1], [3], [2, 1], [2], [2], [2]] +Output +[null, null, null, 1, -1, null, 1, null, -1] + +Explanation +MyHashMap myHashMap = new MyHashMap(); +myHashMap.put(1, 1); // The map is now [[1,1]] +myHashMap.put(2, 2); // The map is now [[1,1], [2,2]] +myHashMap.get(1); // return 1, The map is now [[1,1], [2,2]] +myHashMap.get(3); // return -1 (i.e., not found), The map is now [[1,1], [2,2]] +myHashMap.put(2, 1); // The map is now [[1,1], [2,1]] (i.e., update the existing value) +myHashMap.get(2); // return 1, The map is now [[1,1], [2,1]] +myHashMap.remove(2); // remove the mapping for 2, The map is now [[1,1]] +myHashMap.get(2); // return -1 (i.e., not found), The map is now [[1,1]] +``` + +### Constraints: + +0 <= key, value <= 106 + +At most 104 calls will be made to put, get, and remove. \ No newline at end of file diff --git a/DataStractures/HashTable/706_DesignHashMap/solution.py b/DataStractures/HashTable/706_DesignHashMap/solution.py new file mode 100644 index 0000000..f59a658 --- /dev/null +++ b/DataStractures/HashTable/706_DesignHashMap/solution.py @@ -0,0 +1,28 @@ +class MyHashMap: + + def __init__(self): + self.map=dict() + + + def put(self, key: int, value: int) -> None: + self.map[key]= value + + + def get(self, key: int) -> int: + if key in self.map.keys(): + return self.map.get(key) + else: return -1 + + + def remove(self, key: int) -> None: + if key in self.map.keys(): + del self.map[key] + #706 + + + +# Your MyHashMap object will be instantiated and called as such: +# obj = MyHashMap() +# obj.put(key,value) +# param_2 = obj.get(key) +# obj.remove(key) \ No newline at end of file diff --git a/DataStractures/HashTable/771_JewelsandStones/description.md b/DataStractures/HashTable/771_JewelsandStones/description.md new file mode 100644 index 0000000..cde90d5 --- /dev/null +++ b/DataStractures/HashTable/771_JewelsandStones/description.md @@ -0,0 +1,27 @@ +### 771. Jewels and Stones +|Easy + +You're given strings jewels representing the types of stones that are jewels, and stones representing the stones you have. Each character in stones is a type of stone you have. You want to know how many of the stones you have are also jewels. + +Letters are case sensitive, so "a" is considered a different type of stone from "A". + + + +Example 1: +``` +Input: jewels = "aA", stones = "aAAbbbb" +Output: 3 +``` +Example 2: +``` +Input: jewels = "z", stones = "ZZ" +Output: 0 +`````` + +### Constraints: + +1 <= jewels.length, stones.length <= 50 + +jewels and stones consist of only English letters. + +All the characters of jewels are unique. \ No newline at end of file diff --git a/DataStractures/HashTable/771_JewelsandStones/solution.py b/DataStractures/HashTable/771_JewelsandStones/solution.py new file mode 100644 index 0000000..11bec90 --- /dev/null +++ b/DataStractures/HashTable/771_JewelsandStones/solution.py @@ -0,0 +1,21 @@ +class Solution: + def numJewelsInStones(self, jewels: str, stones: str) -> int: + #Approach 01 +# jewel_l = [i for i in jewels] +# stone_l = [i for i in stones] +# counter = 0 + +# for i in stone_l: +# if i in jewel_l: +# counter +=1 +# else: +# continue +# return counter + #Approach 02 + lookup_jewel = {i:0 for i in jewels} + for i in stones: + if i in lookup_jewel.keys(): + lookup_jewel[i] +=1 + + return(sum(lookup_jewel.values())) + ## return sum(Counter(stones)[i] for i in jewels) \ No newline at end of file diff --git a/DataStractures/Heap/215_KthLargestElementinanArray/description.md b/DataStractures/Heap/215_KthLargestElementinanArray/description.md new file mode 100644 index 0000000..a9c083b --- /dev/null +++ b/DataStractures/Heap/215_KthLargestElementinanArray/description.md @@ -0,0 +1,27 @@ +### 215. Kth Largest Element in an Array +|Medium + +Given an integer array nums and an integer k, return the kth largest element in the array. + +Note that it is the kth largest element in the sorted order, not the kth distinct element. + +Can you solve it without sorting? + + + +Example 1: +``` +Input: nums = [3,2,1,5,6,4], k = 2 +Output: 5 +``` +Example 2: +``` +Input: nums = [3,2,3,1,2,4,5,5,6], k = 4 +Output: 4 +``` + +### Constraints: + +1 <= k <= nums.length <= 105 + +-104 <= nums[i] <= 104 \ No newline at end of file diff --git a/DataStractures/Heap/215_KthLargestElementinanArray/solution.py b/DataStractures/Heap/215_KthLargestElementinanArray/solution.py new file mode 100644 index 0000000..6180ce2 --- /dev/null +++ b/DataStractures/Heap/215_KthLargestElementinanArray/solution.py @@ -0,0 +1,14 @@ + +from ast import List +import heapq +class Solution: + def findKthLargest(self, nums: List[int], k: int) -> int: + if not nums or not k or k < 0: + return None + maxheap, res = [], None + for num in nums: + heapq.heappush(maxheap, -num) + + for _ in range(k): + res = -heapq.heappop(maxheap) + return res diff --git a/DataStractures/LinkedList/1290_ConvertBinaryNumberinaLinkedListtoInteger/descrioption.md b/DataStractures/LinkedList/1290_ConvertBinaryNumberinaLinkedListtoInteger/descrioption.md new file mode 100644 index 0000000..39cc4ff --- /dev/null +++ b/DataStractures/LinkedList/1290_ConvertBinaryNumberinaLinkedListtoInteger/descrioption.md @@ -0,0 +1,30 @@ +### 1290. Convert Binary Number in a Linked List to Integer +|Easy + +Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. + +Return the decimal value of the number in the linked list. + +The most significant bit is at the head of the linked list. + + + +Example 1: +``` +Input: head = [1,0,1] +Output: 5 +Explanation: (101) in base 2 = (5) in base 10 +``` +Example 2: +``` +Input: head = [0] +Output: 0 +``` + +### Constraints: + +The Linked List is not empty. + +Number of nodes will not exceed 30. + +Each node's value is either 0 or 1. \ No newline at end of file diff --git a/DataStractures/LinkedList/1290_ConvertBinaryNumberinaLinkedListtoInteger/solution.py b/DataStractures/LinkedList/1290_ConvertBinaryNumberinaLinkedListtoInteger/solution.py new file mode 100644 index 0000000..9c12188 --- /dev/null +++ b/DataStractures/LinkedList/1290_ConvertBinaryNumberinaLinkedListtoInteger/solution.py @@ -0,0 +1,14 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def getDecimalValue(self, head: ListNode) -> int: + + answer =0 + + while head: + answer = 2*answer + head.val + head = head.next + return answer \ No newline at end of file diff --git a/DataStractures/LinkedList/138_CopyListwithRandomPointer/description.md b/DataStractures/LinkedList/138_CopyListwithRandomPointer/description.md new file mode 100644 index 0000000..1564fed --- /dev/null +++ b/DataStractures/LinkedList/138_CopyListwithRandomPointer/description.md @@ -0,0 +1,46 @@ +### 138. Copy List with Random Pointer +|Medium + +A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list, or null. + +Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes, where each new node has its value set to the value of its corresponding original node. Both the next and random pointer of the new nodes should point to new nodes in the copied list such that the pointers in the original list and copied list represent the same list state. None of the pointers in the new list should point to nodes in the original list. + +For example, if there are two nodes X and Y in the original list, where X.random --> Y, then for the corresponding two nodes x and y in the copied list, x.random --> y. + +Return the head of the copied linked list. + +The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where: + +val: an integer representing Node.val +random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node. +Your code will only be given the head of the original linked list. + + + +Example 1: +``` + +Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]] +Output: [[7,null],[13,0],[11,4],[10,2],[1,0]] +``` +Example 2: +``` + +Input: head = [[1,1],[2,1]] +Output: [[1,1],[2,1]] +``` +Example 3: + + +``` +Input: head = [[3,null],[3,0],[3,null]] +Output: [[3,null],[3,0],[3,null]] +``` + +### Constraints: + +0 <= n <= 1000 + +-104 <= Node.val <= 104 + +Node.random is null or is pointing to some node in the linked list. \ No newline at end of file diff --git a/DataStractures/LinkedList/138_CopyListwithRandomPointer/solution.py b/DataStractures/LinkedList/138_CopyListwithRandomPointer/solution.py new file mode 100644 index 0000000..fdc8374 --- /dev/null +++ b/DataStractures/LinkedList/138_CopyListwithRandomPointer/solution.py @@ -0,0 +1,29 @@ +""" +# Definition for a Node.""" +class Node: + def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): + self.val = int(x) + self.next = next + self.random = random + + +class Solution: + def copyRandomList(self, head: list[Node]) -> list[Node]: + + # return deepcopy(head) + if head is None: + return head + temp=head + mp = {} + while temp: + mp[temp]=Node(temp.val) + temp=temp.next + temp=head + while temp: + if temp.next: + mp[temp].next=mp[temp.next] + if temp.random: + mp[temp].random=mp[temp.random] + temp=temp.next + return mp[head] + #138 diff --git a/DataStractures/LinkedList/141_LinkedListCycle/description.md b/DataStractures/LinkedList/141_LinkedListCycle/description.md new file mode 100644 index 0000000..214bfee --- /dev/null +++ b/DataStractures/LinkedList/141_LinkedListCycle/description.md @@ -0,0 +1,40 @@ +### 141. Linked List Cycle +|Easy + +Given head, the head of a linked list, determine if the linked list has a cycle in it. + +There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter. + +Return true if there is a cycle in the linked list. Otherwise, return false. + + + +Example 1: +``` + +Input: head = [3,2,0,-4], pos = 1 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed). + +Example 2: +``` + +Input: head = [1,2], pos = 0 +Output: true +Explanation: There is a cycle in the linked list, where the tail connects to the 0th node. +``` +Example 3: + +``` +Input: head = [1], pos = -1 +Output: false +Explanation: There is no cycle in the linked list. +``` + +### Constraints: + +The number of the nodes in the list is in the range [0, 104]. + +-105 <= Node.val <= 105 + +pos is -1 or a valid index in the linked-list. \ No newline at end of file diff --git a/DataStractures/LinkedList/141_LinkedListCycle/solution.py b/DataStractures/LinkedList/141_LinkedListCycle/solution.py new file mode 100644 index 0000000..a97a472 --- /dev/null +++ b/DataStractures/LinkedList/141_LinkedListCycle/solution.py @@ -0,0 +1,16 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def hasCycle(self, head: list[ListNode]) -> bool: + fast=head + slow=head + while fast and fast.next: + fast=fast.next.next + slow= slow.next + if fast==slow: return True + + return False \ No newline at end of file diff --git a/DataStractures/LinkedList/142_LinkedListCycleII/description.md b/DataStractures/LinkedList/142_LinkedListCycleII/description.md new file mode 100644 index 0000000..42efeea --- /dev/null +++ b/DataStractures/LinkedList/142_LinkedListCycleII/description.md @@ -0,0 +1,42 @@ +### 142. Linked List Cycle II +|Medium + +Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null. + +There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to (0-indexed). It is -1 if there is no cycle. Note that pos is not passed as a parameter. + +Do not modify the linked list. + + + +Example 1: +``` + +Input: head = [3,2,0,-4], pos = 1 +Output: tail connects to node index 1 +Explanation: There is a cycle in the linked list, where tail connects to the second node. +``` +Example 2: + +``` +Input: head = [1,2], pos = 0 +Output: tail connects to node index 0 +Explanation: There is a cycle in the linked list, where tail connects to the first node. +``` +Example 3: +``` +Input: head = [1], pos = -1 +Output: no cycle +Explanation: There is no cycle in the linked list. +``` + +### Constraints: + +The number of the nodes in the list is in the range [0, 104]. + +-105 <= Node.val <= 105 + +pos is -1 or a valid index in the linked-list. + + +### Follow up: Can you solve it using O(1) (i.e. constant) memory? \ No newline at end of file diff --git a/DataStractures/LinkedList/142_LinkedListCycleII/solution.py b/DataStractures/LinkedList/142_LinkedListCycleII/solution.py new file mode 100644 index 0000000..f053726 --- /dev/null +++ b/DataStractures/LinkedList/142_LinkedListCycleII/solution.py @@ -0,0 +1,18 @@ +class ListNode: + def __init__(self, x): + + self.val = x + self.next = None + +class Solution: + def detectCycle(self, head): + fast = slow = head + while fast and fast.next: + fast = fast.next.next + slow = slow.next + if slow is fast: #Cycle detected + fast = head + while fast is not slow: + fast = fast.next + slow = slow.next + return fast \ No newline at end of file diff --git a/DataStractures/LinkedList/160_IntersectionofTwoLinkedLists/description.md b/DataStractures/LinkedList/160_IntersectionofTwoLinkedLists/description.md new file mode 100644 index 0000000..aa0e45c --- /dev/null +++ b/DataStractures/LinkedList/160_IntersectionofTwoLinkedLists/description.md @@ -0,0 +1,68 @@ +### 160. Intersection of Two Linked Lists +|Easy + +Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. + +For example, the following two linked lists begin to intersect at node c1: + + +The test cases are generated such that there are no cycles anywhere in the entire linked structure. + +Note that the linked lists must retain their original structure after the function returns. + +Custom Judge: + +The inputs to the judge are given as follows (your program is not given these inputs): + +intersectVal - The value of the node where the intersection occurs. This is 0 if there is no intersected node. +listA - The first linked list. +listB - The second linked list. +skipA - The number of nodes to skip ahead in listA (starting from the head) to get to the intersected node. +skipB - The number of nodes to skip ahead in listB (starting from the head) to get to the intersected node. +The judge will then create the linked structure based on these inputs and pass the two heads, headA and headB to your program. If you correctly return the intersected node, then your solution will be accepted. + + + +Example 1: +``` + +Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3 +Output: Intersected at '8' +Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,6,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. +- Note that the intersected node's value is not 1 because the nodes with value 1 in A and B (2nd node in A and 3rd node in B) are different node references. In other words, they point to two different locations in memory, while the nodes with value 8 in A and B (3rd node in A and 4th node in B) point to the same location in memory. +``` +Example 2: +``` + +Input: intersectVal = 2, listA = [1,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 +Output: Intersected at '2' +Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). +From the head of A, it reads as [1,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. +``` +Example 3: + +``` +Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 +Output: No intersection +Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. +Explanation: The two lists do not intersect, so return null. +``` + +### Constraints: + +The number of nodes of listA is in the m. + +The number of nodes of listB is in the n. + +1 <= m, n <= 3 * 104 + +1 <= Node.val <= 105 + +0 <= skipA < m + +0 <= skipB < n + +intersectVal is 0 if listA and listB do not intersect. + +intersectVal == listA[skipA] == listB[skipB] if listA and listB intersect. diff --git a/DataStractures/LinkedList/160_IntersectionofTwoLinkedLists/solution.py b/DataStractures/LinkedList/160_IntersectionofTwoLinkedLists/solution.py new file mode 100644 index 0000000..7b9dbc3 --- /dev/null +++ b/DataStractures/LinkedList/160_IntersectionofTwoLinkedLists/solution.py @@ -0,0 +1,24 @@ +#Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def getIntersectionNode(self, headA: ListNode, headB: ListNode) ->ListNode: + + temp_A=set() + while headA: + temp_A.add(headA) + headA = headA.next + while headB: + if headB in temp_A: + return headB + headB= headB.next + return None + + # a_pointer, b_pointer = headA, headB + # while a_pointer != b_pointer: + # a_pointer = a_pointer.next if a_pointer else headB + # b_pointer = b_pointer.next if b_pointer else headA + # return a_pointer \ No newline at end of file diff --git a/DataStractures/LinkedList/19_RemoveNthNodeFromEndofList/description.md b/DataStractures/LinkedList/19_RemoveNthNodeFromEndofList/description.md new file mode 100644 index 0000000..e6a84cf --- /dev/null +++ b/DataStractures/LinkedList/19_RemoveNthNodeFromEndofList/description.md @@ -0,0 +1,36 @@ +### 19. Remove Nth Node From End of List +|Medium + +Given the head of a linked list, remove the nth node from the end of the list and return its head. + + + +Example 1: + +``` +Input: head = [1,2,3,4,5], n = 2 +Output: [1,2,3,5] +``` +Example 2: +``` +Input: head = [1], n = 1 +Output: [] +``` +Example 3: +``` +Input: head = [1,2], n = 1 +Output: [1] +``` + +### Constraints: + +The number of nodes in the list is sz. + +1 <= sz <= 30 + +0 <= Node.val <= 100 + +1 <= n <= sz + + +### Follow up: Could you do this in one pass? \ No newline at end of file diff --git a/DataStractures/LinkedList/19_RemoveNthNodeFromEndofList/solution.py b/DataStractures/LinkedList/19_RemoveNthNodeFromEndofList/solution.py new file mode 100644 index 0000000..4d1d2c4 --- /dev/null +++ b/DataStractures/LinkedList/19_RemoveNthNodeFromEndofList/solution.py @@ -0,0 +1,16 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def removeNthFromEnd(self, head: list[ListNode], n: int) -> list[ListNode]: + fast, slow = head, head + for _ in range(n): + fast = fast.next + if not fast: return head.next + while fast.next: + fast, slow = fast.next, slow.next + slow.next = slow.next.next + return head + \ No newline at end of file diff --git a/DataStractures/LinkedList/203_RemoveLinkedListElements/description.md b/DataStractures/LinkedList/203_RemoveLinkedListElements/description.md new file mode 100644 index 0000000..1679d8d --- /dev/null +++ b/DataStractures/LinkedList/203_RemoveLinkedListElements/description.md @@ -0,0 +1,31 @@ +### 203. Remove Linked List Elements +|Easy + +Given the head of a linked list and an integer val, remove all the nodes of the linked list that has Node.val == val, and return the new head. + + + +Example 1: + +``` +Input: head = [1,2,6,3,4,5,6], val = 6 +Output: [1,2,3,4,5] +``` +Example 2: +``` +Input: head = [], val = 1 +Output: [] +``` +Example 3: +``` +Input: head = [7,7,7,7], val = 7 +Output: [] +``` + +### Constraints: + +The number of nodes in the list is in the range [0, 104]. + +1 <= Node.val <= 50 + +0 <= val <= 50 \ No newline at end of file diff --git a/DataStractures/LinkedList/203_RemoveLinkedListElements/solution.py b/DataStractures/LinkedList/203_RemoveLinkedListElements/solution.py new file mode 100644 index 0000000..5950c63 --- /dev/null +++ b/DataStractures/LinkedList/203_RemoveLinkedListElements/solution.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def removeElements(self, head: list[ListNode], val: int) -> list[ListNode]: + if head==None :return head + while head.val==val: + head=head.next + if head==None :return head + + current=head + while current and current.next: + if current.next.val== val: + current.next=current.next.next + else: + current=current.next + return head \ No newline at end of file diff --git a/DataStractures/LinkedList/206_ReverseLinkedList/description.md b/DataStractures/LinkedList/206_ReverseLinkedList/description.md new file mode 100644 index 0000000..cf0ac14 --- /dev/null +++ b/DataStractures/LinkedList/206_ReverseLinkedList/description.md @@ -0,0 +1,30 @@ +### 206. Reverse Linked List +|Easy + +Given the head of a singly linked list, reverse the list, and return the reversed list. + + +Example 1: +``` +Input: head = [1,2,3,4,5] +Output: [5,4,3,2,1] +``` +Example 2: +``` +Input: head = [1,2] +Output: [2,1] +``` +Example 3: +``` +Input: head = [] +Output: [] +``` + +### Constraints: + +The number of nodes in the list is the range [0, 5000]. + +-5000 <= Node.val <= 5000 + + +### Follow up: A linked list can be reversed either iteratively or recursively. Could you implement both? \ No newline at end of file diff --git a/DataStractures/LinkedList/206_ReverseLinkedList/solution.py b/DataStractures/LinkedList/206_ReverseLinkedList/solution.py new file mode 100644 index 0000000..e48b628 --- /dev/null +++ b/DataStractures/LinkedList/206_ReverseLinkedList/solution.py @@ -0,0 +1,20 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def reverseList(self, head: list[ListNode]) -> list[ListNode]: + if head is None: + return head + + current = head + previous = None + + while current is not None: + temp = current.next + current.next = previous + previous = current + current = temp + + return previous \ No newline at end of file diff --git a/DataStractures/LinkedList/2095_DeletetheMiddleNodeofaLinkedList/description.md b/DataStractures/LinkedList/2095_DeletetheMiddleNodeofaLinkedList/description.md new file mode 100644 index 0000000..e2acf52 --- /dev/null +++ b/DataStractures/LinkedList/2095_DeletetheMiddleNodeofaLinkedList/description.md @@ -0,0 +1,48 @@ +### 2095. Delete the Middle Node of a Linked List +|Medium + +You are given the head of a linked list. Delete the middle node, and return the head of the modified linked list. + +The middle node of a linked list of size n is the ⌊n / 2⌋th node from the start using 0-based indexing, where ⌊x⌋ denotes the largest integer less than or equal to x. + +For n = 1, 2, 3, 4, and 5, the middle nodes are 0, 1, 1, 2, and 2, respectively. + + +Example 1: +``` +Input: head = [1,3,4,7,1,2,6] +Output: [1,3,4,1,2,6] +``` +Explanation: +``` +The above figure represents the given linked list. The indices of the nodes are written below. +Since n = 7, node 3 with value 7 is the middle node, which is marked in red. +We return the new list after removing this node. +``` +Example 2: +``` +Input: head = [1,2,3,4] +Output: [1,2,4] +``` +Explanation: +``` +The above figure represents the given linked list. +For n = 4, node 2 with value 3 is the middle node, which is marked in red. +``` +Example 3: +``` +Input: head = [2,1] +Output: [2] +``` +Explanation: +``` +The above figure represents the given linked list. +For n = 2, node 1 with value 1 is the middle node, which is marked in red. +Node 0 with value 2 is the only node remaining after removing node 1. +``` + +### Constraints: + +The number of nodes in the list is in the range [1, 105]. + +1 <= Node.val <= 105 \ No newline at end of file diff --git a/DataStractures/LinkedList/2095_DeletetheMiddleNodeofaLinkedList/solution.py b/DataStractures/LinkedList/2095_DeletetheMiddleNodeofaLinkedList/solution.py new file mode 100644 index 0000000..6b6023b --- /dev/null +++ b/DataStractures/LinkedList/2095_DeletetheMiddleNodeofaLinkedList/solution.py @@ -0,0 +1,25 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def deleteMiddle(self, head: list[ListNode]) -> list[ListNode]: + count=0 + res=head + while res: + count+=1 + res=res.next + if count<=1 :return None + if count%2==0 : + middel=(count//2) +1 + else: + middel=count//2+1 + temp=head + for i in range(middel-2): + temp=temp.next + + temp.next=temp.next.next + + return head + # 2095 \ No newline at end of file diff --git a/DataStractures/LinkedList/21_MergeTwoSortedLists/description.md b/DataStractures/LinkedList/21_MergeTwoSortedLists/description.md new file mode 100644 index 0000000..8e3dc75 --- /dev/null +++ b/DataStractures/LinkedList/21_MergeTwoSortedLists/description.md @@ -0,0 +1,35 @@ +### 21. Merge Two Sorted Lists +|Easy + +You are given the heads of two sorted linked lists list1 and list2. + +Merge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists. + +Return the head of the merged linked list. + + + +Example 1: + +``` +Input: list1 = [1,2,4], list2 = [1,3,4] +Output: [1,1,2,3,4,4] +``` +Example 2: +``` +Input: list1 = [], list2 = [] +Output: [] +``` +Example 3: +``` +Input: list1 = [], list2 = [0] +Output: [0] +``` + +### Constraints: + +The number of nodes in both lists is in the range [0, 50]. + +-100 <= Node.val <= 100 + +Both list1 and list2 are sorted in non-decreasing order. \ No newline at end of file diff --git a/DataStractures/LinkedList/21_MergeTwoSortedLists/solution.py b/DataStractures/LinkedList/21_MergeTwoSortedLists/solution.py new file mode 100644 index 0000000..7b0b4d9 --- /dev/null +++ b/DataStractures/LinkedList/21_MergeTwoSortedLists/solution.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def mergeTwoLists(self, list1: list[ListNode], list2: list[ListNode]) -> list[ListNode]: + if not list1 and not list2 : + return list1 + elif list1 and not list2 : + return list1 + elif not list1 and list2: return list2 + + else: + cur = dummy = ListNode() + while list1 and list2: + if list1.val < list2.val: + cur.next = list1 + list1, cur = list1.next, list1 + else: + cur.next = list2 + list2, cur = list2.next, list2 + + if list1 or list2: + cur.next = list1 if list1 else list2 + + return dummy.next \ No newline at end of file diff --git a/DataStractures/LinkedList/234_PalindromeLinkedList/description.md b/DataStractures/LinkedList/234_PalindromeLinkedList/description.md new file mode 100644 index 0000000..f1fef71 --- /dev/null +++ b/DataStractures/LinkedList/234_PalindromeLinkedList/description.md @@ -0,0 +1,26 @@ +### 234. Palindrome Linked List +|Easy + +Given the head of a singly linked list, return true if it is a palindromeor false otherwise. + + + +Example 1: +``` +Input: head = [1,2,2,1] +Output: true +``` +Example 2: +``` +Input: head = [1,2] +Output: false +``` + +### Constraints: + +The number of nodes in the list is in the range [1, 105]. + +0 <= Node.val <= 9 + + +### Follow up: Could you do it in O(n) time and O(1) space? \ No newline at end of file diff --git a/DataStractures/LinkedList/234_PalindromeLinkedList/solution.py b/DataStractures/LinkedList/234_PalindromeLinkedList/solution.py new file mode 100644 index 0000000..4e435c9 --- /dev/null +++ b/DataStractures/LinkedList/234_PalindromeLinkedList/solution.py @@ -0,0 +1,29 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def isPalindrome(self, head: list[ListNode]) -> bool: + + arr = [] + current = head + while current is not None: + arr.append(current.val) + current = current.next + if arr == arr[::-1]: + return True + else: return False +# self.front_pointer = head + +# def recursively_check(current_node=head): + +# if current_node is not None: +# if not recursively_check(current_node.next): +# return False +# if self.front_pointer.val != current_node.val: +# return False +# self.front_pointer = self.front_pointer.next +# return True + +# return recursively_check() \ No newline at end of file diff --git a/DataStractures/LinkedList/237_DeleteNodeinaLinkedList/description.md b/DataStractures/LinkedList/237_DeleteNodeinaLinkedList/description.md new file mode 100644 index 0000000..5dc48bb --- /dev/null +++ b/DataStractures/LinkedList/237_DeleteNodeinaLinkedList/description.md @@ -0,0 +1,44 @@ +### 237. Delete Node in a Linked List +|Medium + +There is a singly-linked list head and we want to delete a node node in it. + +You are given the node to be deleted node. You will not be given access to the first node of head. + +All the values of the linked list are unique, and it is guaranteed that the given node node is not the last node in the linked list. + +Delete the given node. Note that by deleting the node, we do not mean removing it from memory. We mean: + +The value of the given node should not exist in the linked list. +The number of nodes in the linked list should decrease by one. +All the values before node should be in the same order. +All the values after node should be in the same order. +Custom testing: + +For the input, you should provide the entire linked list head and the node to be given node. node should not be the last node of the list and should be an actual node in the list. +We will build the linked list and pass the node to your function. +The output will be the entire list after calling your function. + + +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: +``` +Input: head = [4,5,1,9], node = 1 +Output: [4,5,9] +Explanation: You are given the third node with value 1, the linked list should become 4 -> 5 -> 9 after calling your function. +``` + +### Constraints: + +The number of the nodes in the given list is in the range [2, 1000]. + +-1000 <= Node.val <= 1000 + +The value of each node in the list is unique. + +The node to be deleted is in the list and is not a tail node. \ No newline at end of file diff --git a/DataStractures/LinkedList/237_DeleteNodeinaLinkedList/solution.py b/DataStractures/LinkedList/237_DeleteNodeinaLinkedList/solution.py new file mode 100644 index 0000000..d2dab4d --- /dev/null +++ b/DataStractures/LinkedList/237_DeleteNodeinaLinkedList/solution.py @@ -0,0 +1,14 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, x): + self.val = x + self.next = None + +class Solution: + def deleteNode(self, node): + """ + :type node: ListNode + :rtype: void Do not return anything, modify node in-place instead. + """ + node.val = node.next.val + node.next = node.next.next \ No newline at end of file diff --git a/DataStractures/LinkedList/2_AddTwoNumbers/description.md b/DataStractures/LinkedList/2_AddTwoNumbers/description.md new file mode 100644 index 0000000..153d7d9 --- /dev/null +++ b/DataStractures/LinkedList/2_AddTwoNumbers/description.md @@ -0,0 +1,35 @@ +### 2. Add Two Numbers +|Medium + +You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list. + +You may assume the two numbers do not contain any leading zero, except the number 0 itself. + + + +Example 1: + +``` +Input: l1 = [2,4,3], l2 = [5,6,4] +Output: [7,0,8] +Explanation: 342 + 465 = 807. +``` +Example 2: +``` +Input: l1 = [0], l2 = [0] +Output: [0] +``` +Example 3: +``` +Input: l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9] +Output: [8,9,9,9,0,0,0,1] +``` + + +### Constraints: + +The number of nodes in each linked list is in the range [1, 100]. + +0 <= Node.val <= 9 + +It is guaranteed that the list represents a number that does not have leading zeros. \ No newline at end of file diff --git a/DataStractures/LinkedList/2_AddTwoNumbers/solution.py b/DataStractures/LinkedList/2_AddTwoNumbers/solution.py new file mode 100644 index 0000000..11fa800 --- /dev/null +++ b/DataStractures/LinkedList/2_AddTwoNumbers/solution.py @@ -0,0 +1,24 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def addTwoNumbers(self, l1: list[ListNode], l2: list[ListNode]) -> list[ListNode]: + num1=[] + num2=[] + while l1: + num1.append(str(l1.val)) + l1= l1.next + + while l2 : + num2.append(str(l2.val)) + l2= l2.next + + res=int(''.join(map(str,reversed(num1))))+int(''.join(map(str,reversed(num2)))) + arr =str(res)[::-1] + root=n=ListNode(0) + for i in arr : + root.next= ListNode(i) + root=root.next + return n.next \ No newline at end of file diff --git a/DataStractures/LinkedList/328_OddEvenLinkedList/description.md b/DataStractures/LinkedList/328_OddEvenLinkedList/description.md new file mode 100644 index 0000000..b524368 --- /dev/null +++ b/DataStractures/LinkedList/328_OddEvenLinkedList/description.md @@ -0,0 +1,29 @@ +### 328. Odd Even Linked List +|Medium + +Given the head of a singly linked list, group all the nodes with odd indices together followed by the nodes with even indices, and return the reordered list. + +The first node is considered odd, and the second node is even, and so on. + +Note that the relative order inside both the even and odd groups should remain as it was in the input. + +You must solve the problem in O(1) extra space complexity and O(n) time complexity. + + + +Example 1: +``` +Input: head = [1,2,3,4,5] +Output: [1,3,5,2,4] +``` +Example 2: +``` +Input: head = [2,1,3,5,6,4,7] +Output: [2,3,6,7,1,5,4] +``` + +### Constraints: + +The number of nodes in the linked list is in the range [0, 104]. + +-106 <= Node.val <= 106 \ No newline at end of file diff --git a/DataStractures/LinkedList/328_OddEvenLinkedList/solution.py b/DataStractures/LinkedList/328_OddEvenLinkedList/solution.py new file mode 100644 index 0000000..950111b --- /dev/null +++ b/DataStractures/LinkedList/328_OddEvenLinkedList/solution.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def oddEvenList(self, head: list[ListNode]) -> list[ListNode]: + if not head or not head.next:return head + odd=head + even=head.next + even_head=even + + while even and even.next: + odd.next = even.next + odd = odd.next + even.next = odd.next + even = even.next + odd.next=even_head + return head \ No newline at end of file diff --git a/DataStractures/LinkedList/430_FlattenaMultilevelDoublyLinkedList/description.md b/DataStractures/LinkedList/430_FlattenaMultilevelDoublyLinkedList/description.md new file mode 100644 index 0000000..51e8199 --- /dev/null +++ b/DataStractures/LinkedList/430_FlattenaMultilevelDoublyLinkedList/description.md @@ -0,0 +1,67 @@ +###430. Flatten a Multilevel Doubly Linked List +|Medium + +You are given a doubly linked list, which contains nodes that have a next pointer, a previous pointer, and an additional child pointer. This child pointer may or may not point to a separate doubly linked list, also containing these special nodes. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure as shown in the example below. + +Given the head of the first level of the list, flatten the list so that all the nodes appear in a single-level, doubly linked list. Let curr be a node with a child list. The nodes in the child list should appear after curr and before curr.next in the flattened list. + +Return the head of the flattened list. The nodes in the list must have all of their child pointers set to null. + + + +Example 1: +``` +Input: head = [1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] +Output: [1,2,3,7,8,11,12,9,10,4,5,6] +Explanation: The multilevel linked list in the input is shown. +After flattening the multilevel linked list it becomes: +``` +Example 2: +``` +Input: head = [1,2,null,3] +Output: [1,3,2] +Explanation: The multilevel linked list in the input is shown. +After flattening the multilevel linked list it becomes: +``` +Example 3: +``` +Input: head = [] +Output: [] +Explanation: There could be empty list in the input. +``` + +### Constraints: + +The number of Nodes will not exceed 1000. + +1 <= Node.val <= 105 + + +How the multilevel linked list is represented in test cases: + +We use the multilevel linked list from Example 1 above: +``` + 1---2---3---4---5---6--NULL + | + 7---8---9---10--NULL + | + 11--12--NULL +``` +The serialization of each level is as follows: +``` +[1,2,3,4,5,6,null] +[7,8,9,10,null] +[11,12,null] +``` +To serialize all levels together, we will add nulls in each level to signify no node connects to the upper node of the previous level. The serialization becomes: +``` +[1, 2, 3, 4, 5, 6, null] + | +[null, null, 7, 8, 9, 10, null] + | +[ null, 11, 12, null] +``` +Merging the serialization of each level and removing trailing nulls we obtain: +``` +[1,2,3,4,5,6,null,null,null,7,8,9,10,null,null,11,12] +``` \ No newline at end of file diff --git a/DataStractures/LinkedList/430_FlattenaMultilevelDoublyLinkedList/solution.py b/DataStractures/LinkedList/430_FlattenaMultilevelDoublyLinkedList/solution.py new file mode 100644 index 0000000..890bc0f --- /dev/null +++ b/DataStractures/LinkedList/430_FlattenaMultilevelDoublyLinkedList/solution.py @@ -0,0 +1,44 @@ +""" +# Definition for a Node.""" +class Node: + def __init__(self, val, prev, next, child): + self.val = val + self.prev = prev + self.next = next + self.child = child + +class Solution: + def flatten(self, head: list[Node]) -> list[Node]: + #approve01 + parents = [] + node = head + while node: + if node.child: + node.next and parents.append(node.next) + node.next = node.child + node.next.prev = node + node.child = None + if not node.next and len(parents) > 0: + node.next = parents.pop() + node.next.prev = node + node = node.next + return head + #430 + #approve02 + # if not head:return None + # nodes = [] + # def dfs(node): + # if node is None:return + # nodes.append(node) + # if node.child:dfs(node.child) + # if node.next:dfs(node.next) + # dfs(head) + # head = nodes[0] + # head.child=None + # for i in range(1, len(nodes)): + # node = nodes[i] + # prev = nodes[i-1] + # node.child=None + # node.prev=prev + # prev.next = node + # return head \ No newline at end of file diff --git a/DataStractures/LinkedList/61_RotateList/description.md b/DataStractures/LinkedList/61_RotateList/description.md new file mode 100644 index 0000000..3572c80 --- /dev/null +++ b/DataStractures/LinkedList/61_RotateList/description.md @@ -0,0 +1,27 @@ +### 61. Rotate List +|Medium + +Given the head of a linked list, rotate the list to the right by k places. + + + +Example 1: + +``` +Input: head = [1,2,3,4,5], k = 2 +Output: [4,5,1,2,3] +``` +Example 2: + +``` +Input: head = [0,1,2], k = 4 +Output: [2,0,1] +``` + +### Constraints: + +The number of nodes in the list is in the range [0, 500]. + +-100 <= Node.val <= 100 + +0 <= k <= 2 * 109 \ No newline at end of file diff --git a/DataStractures/LinkedList/61_RotateList/solution.py b/DataStractures/LinkedList/61_RotateList/solution.py new file mode 100644 index 0000000..a1371f4 --- /dev/null +++ b/DataStractures/LinkedList/61_RotateList/solution.py @@ -0,0 +1,39 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def rotateRight(self, head: list[ListNode], k: int) -> list[ListNode]: + size=0 + pc=head + while pc : + size+=1 + pc=pc.next + + if head is None:return + + if k>=size : + k=k%size + + if k==0 : return head + + pa=head + for i in range (k): + while pa.next: + pb=pa + pa=pa.next + if size>1: + pb.next=pa.next + print(pb.next) + pa.next=head + print(pa.next) + head=pa + print(head) + else: + return head + return head + + + + \ No newline at end of file diff --git a/DataStractures/LinkedList/707_DesignLinkedList/707_design-linked-list.py b/DataStractures/LinkedList/707_DesignLinkedList/707_design-linked-list.py new file mode 100644 index 0000000..1eab1dc --- /dev/null +++ b/DataStractures/LinkedList/707_DesignLinkedList/707_design-linked-list.py @@ -0,0 +1,91 @@ +class ListNode: + def __init__(self, val): + self.val = val + self.next = None + + +class MyLinkedList(object): + def __init__(self): + """ + Initialize your data structure here. + """ + self.head = None + self.size = 0 + + def get(self, index: int) -> int: + """ + Get the value of the index-th node in the linked list. If the index is invalid, return -1. + """ + if index < 0 or index >= self.size: + return -1 + + current = self.head + + for _ in range(0, index): + current = current.next + + return current.val + + def addAtHead(self, val: int) -> None: + """ + Add a node of value val before the first element of the linked list. After the insertion, the new node will be + the first node of the linked list. + """ + self.addAtIndex(0, val) + + def addAtTail(self, val: int) -> None: + """ + Append a node of value val to the last element of the linked list. + """ + self.addAtIndex(self.size, val) + + def addAtIndex(self, index: int, val: int) -> None: + """ + Add a node of value val before the index-th node in the linked list. If index equals to the length of linked + list, the node will be appended to the end of linked list. If index is greater than the length, the node will not + be inserted. + """ + if index > self.size: + return + + current = self.head + new_node = ListNode(val) + + if index <= 0: + new_node.next = current + self.head = new_node + else: + for _ in range(index - 1): + current = current.next + new_node.next = current.next + current.next = new_node + + self.size += 1 + + def deleteAtIndex(self, index: int) -> None: + """ + Delete the index-th node in the linked list, if the index is valid. + """ + if index < 0 or index >= self.size: + return + + current = self.head + + if index == 0: + self.head = self.head.next + else: + for _ in range(0, index - 1): + current = current.next + current.next = current.next.next + + self.size -= 1 + + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) \ No newline at end of file diff --git a/DataStractures/LinkedList/707_DesignLinkedList/description.md b/DataStractures/LinkedList/707_DesignLinkedList/description.md new file mode 100644 index 0000000..56d44b7 --- /dev/null +++ b/DataStractures/LinkedList/707_DesignLinkedList/description.md @@ -0,0 +1,43 @@ +### 707. Design Linked List +|Medium + +Design your implementation of the linked list. You can choose to use a singly or doubly linked list. +A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node. +If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed. + +Implement the MyLinkedList class: + +MyLinkedList() Initializes the MyLinkedList object. +int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1. +void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. +void addAtTail(int val) Append a node of value val as the last element of the linked list. +void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted. +void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid. + + +Example 1: +``` +Input +["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"] +[[], [1], [3], [1, 2], [1], [1], [1]] +Output +[null, null, null, null, 2, null, 3] +``` +Explanation +``` +MyLinkedList myLinkedList = new MyLinkedList(); +myLinkedList.addAtHead(1); +myLinkedList.addAtTail(3); +myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3 +myLinkedList.get(1); // return 2 +myLinkedList.deleteAtIndex(1); // now the linked list is 1->3 +myLinkedList.get(1); // return 3 +``` + +###Constraints: + +0 <= index, val <= 1000 + +Please do not use the built-in LinkedList library. + +At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex. \ No newline at end of file diff --git a/DataStractures/LinkedList/707_DesignLinkedList/solution.py b/DataStractures/LinkedList/707_DesignLinkedList/solution.py new file mode 100644 index 0000000..1c272df --- /dev/null +++ b/DataStractures/LinkedList/707_DesignLinkedList/solution.py @@ -0,0 +1,100 @@ +class Node(object): + + def __init__(self, val, nxt=None, prev=None): + self.val =val + self.next = nxt + self.prev = prev + +class MyLinkedList(): + + def __init__(self): + self.head=None + self.tail=None + self.size=0 + + + def get(self, index: int) -> int: + if index < 0 or index >= self.size: + return -1 + cur = self.head + for _ in range(index): + cur = cur.next + return cur.val + + + + def addAtHead(self, val: int) -> None: + + add = Node(val) + if self.size == 0: + add.next = None + self.tail = add + else: + add.next = self.head + self.head.prev = add + add.prev = None + self.head = add + self.size += 1 + + def addAtTail(self, val): + + add = Node(val) + if self.size == 0: + add.prev = None + self.head = add + else: + add.prev = self.tail + self.tail.next = add + add.next = None + self.tail = add + self.size += 1 + + def addAtIndex(self, index: int, val: int) -> None: + if index > self.size: + return + if index <= 0: + self.addAtHead(val) + elif index == self.size: + self.addAtTail(val) + else: + add = Node(val) + prev = self.head + for _ in range(index-1): + prev = prev.next + next_ = prev.next + add.prev = prev + add.next = next_ + prev.next = add + next_.prev = add + self.size += 1 + + + def deleteAtIndex(self, index: int) -> None: + if index < 0 or index >= self.size: + return + cur = self.head + for _ in range(index): + cur = cur.next + if self.size == 1: + self.head = None + self.tail = None + elif cur is self.head: + cur.next.prev = cur.prev + self.head = cur.next + elif cur is self.tail: + cur.prev.next = cur.next + self.tail = cur.prev + else: + cur.prev.next = cur.next + cur.next.prev = cur.prev + self.size -= 1 + + + +# Your MyLinkedList object will be instantiated and called as such: +# obj = MyLinkedList() +# param_1 = obj.get(index) +# obj.addAtHead(val) +# obj.addAtTail(val) +# obj.addAtIndex(index,val) +# obj.deleteAtIndex(index) \ No newline at end of file diff --git a/DataStractures/LinkedList/876_MiddleoftheLinkedList/description.md b/DataStractures/LinkedList/876_MiddleoftheLinkedList/description.md new file mode 100644 index 0000000..b107eb0 --- /dev/null +++ b/DataStractures/LinkedList/876_MiddleoftheLinkedList/description.md @@ -0,0 +1,27 @@ +### 876. Middle of the Linked List +|Easy + +Given the head of a singly linked list, return the middle node of the linked list. + +If there are two middle nodes, return the second middle node. + + + +Example 1: +``` +Input: head = [1,2,3,4,5] +Output: [3,4,5] +Explanation: The middle node of the list is node 3. +``` +Example 2: +``` +Input: head = [1,2,3,4,5,6] +Output: [4,5,6] +Explanation: Since the list has two middle nodes with values 3 and 4, we return the second one. +``` + +### Constraints: + +The number of nodes in the list is in the range [1, 100]. + +1 <= Node.val <= 100 \ No newline at end of file diff --git a/DataStractures/LinkedList/876_MiddleoftheLinkedList/solution.py b/DataStractures/LinkedList/876_MiddleoftheLinkedList/solution.py new file mode 100644 index 0000000..4195d6f --- /dev/null +++ b/DataStractures/LinkedList/876_MiddleoftheLinkedList/solution.py @@ -0,0 +1,19 @@ +# Definition for singly-linked list. +class ListNode: + def __init__(self, val=0, next=None): + self.val = val + self.next = next +class Solution: + def middleNode(self, head: list[ListNode]) -> list[ListNode]: + count=0 + res=head + while res: + count+=1 + res=res.next + + middel=count//2+1 + + for i in range(middel-1): + head=head.next + return head + #876 \ No newline at end of file diff --git a/DataStractures/Queue_and_Stack/622_DesignCircularQueue/description.md b/DataStractures/Queue_and_Stack/622_DesignCircularQueue/description.md new file mode 100644 index 0000000..91f3148 --- /dev/null +++ b/DataStractures/Queue_and_Stack/622_DesignCircularQueue/description.md @@ -0,0 +1,52 @@ +### 622. Design Circular Queue +|Medium + +Design your implementation of the circular queue. The circular queue is a linear data structure in which the operations are performed based on FIFO (First In First Out) principle, and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". + +One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. In a normal queue, once the queue becomes full, we cannot insert the next element even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. + +Implement the MyCircularQueue class: + +MyCircularQueue(k) Initializes the object with the size of the queue to be k. +int Front() Gets the front item from the queue. If the queue is empty, return -1. +int Rear() Gets the last item from the queue. If the queue is empty, return -1. +boolean enQueue(int value) Inserts an element into the circular queue. Return true if the operation is successful. +boolean deQueue() Deletes an element from the circular queue. Return true if the operation is successful. +boolean isEmpty() Checks whether the circular queue is empty or not. +boolean isFull() Checks whether the circular queue is full or not. +You must solve the problem without using the built-in queue data structure in your programming language. + + + +Example 1: +``` +Input +["MyCircularQueue", "enQueue", "enQueue", "enQueue", "enQueue", "Rear", "isFull", "deQueue", "enQueue", "Rear"] +[[3], [1], [2], [3], [4], [], [], [], [4], []] +Output +[null, true, true, true, false, 3, true, true, true, 4] +``` +Explanation +``` +MyCircularQueue myCircularQueue = new MyCircularQueue(3); +myCircularQueue.enQueue(1); // return True +myCircularQueue.enQueue(2); // return True +myCircularQueue.enQueue(3); // return True +myCircularQueue.enQueue(4); // return False +myCircularQueue.Rear(); // return 3 +myCircularQueue.isFull(); // return True +myCircularQueue.deQueue(); // return True +myCircularQueue.enQueue(4); // return True +myCircularQueue.Rear(); // return 4 +``` + +### Constraints: +``` +1 <= k <= 1000 +``` +``` +0 <= value <= 1000 +``` +``` +At most 3000 calls will be made to enQueue, deQueue, Front, Rear, isEmpty, and isFull. +``` \ No newline at end of file diff --git a/DataStractures/Queue_and_Stack/622_DesignCircularQueue/solution.py b/DataStractures/Queue_and_Stack/622_DesignCircularQueue/solution.py new file mode 100644 index 0000000..3394721 --- /dev/null +++ b/DataStractures/Queue_and_Stack/622_DesignCircularQueue/solution.py @@ -0,0 +1,52 @@ +class MyCircularQueue: + + def __init__(self, k: int): + self.size = k + self.queue = [] + + def enQueue(self, value: int) -> bool: + if len(self.queue) == self.size: + return False + + self.queue.append(value) + return True + + def deQueue(self) -> bool: + if len(self.queue) == 0: + return False + + self.queue.pop(0) + return True + + def Front(self) -> int: + if self.queue: + return self.queue[0] + + return -1 + + def Rear(self) -> int: + if self.queue: + return self.queue[-1] + + return -1 + + def isEmpty(self) -> bool: + if self.queue: + return False + + return True + + def isFull(self) -> bool: + if len(self.queue) == self.size: + return True + + return False + +# Your MyCircularQueue object will be instantiated and called as such: +# obj = MyCircularQueue(k) +# param_1 = obj.enQueue(value) +# param_2 = obj.deQueue() +# param_3 = obj.Front() +# param_4 = obj.Rear() +# param_5 = obj.isEmpty() +# param_6 = obj.isFull() \ No newline at end of file diff --git a/DataStractures/Queue_and_Stack/735_AsteroidCollision/description.md b/DataStractures/Queue_and_Stack/735_AsteroidCollision/description.md new file mode 100644 index 0000000..8ed3ca4 --- /dev/null +++ b/DataStractures/Queue_and_Stack/735_AsteroidCollision/description.md @@ -0,0 +1,37 @@ +### 735. Asteroid Collision +|Medium + +We are given an array asteroids of integers representing asteroids in a row. + +For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. + +Find out the state of the asteroids after all collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet. + + + +Example 1: +``` +Input: asteroids = [5,10,-5] +Output: [5,10] +Explanation: The 10 and -5 collide resulting in 10. The 5 and 10 never collide. +``` +Example 2: +``` +Input: asteroids = [8,-8] +Output: [] +Explanation: The 8 and -8 collide exploding each other. +``` +Example 3: +``` +Input: asteroids = [10,2,-5] +Output: [10] +Explanation: The 2 and -5 collide resulting in -5. The 10 and -5 collide resulting in 10. +``` + +### Constraints: + +2 <= asteroids.length <= 104 + +-1000 <= asteroids[i] <= 1000 + +asteroids[i] != 0 \ No newline at end of file diff --git a/DataStractures/Queue_and_Stack/735_AsteroidCollision/solution.py b/DataStractures/Queue_and_Stack/735_AsteroidCollision/solution.py new file mode 100644 index 0000000..77b8426 --- /dev/null +++ b/DataStractures/Queue_and_Stack/735_AsteroidCollision/solution.py @@ -0,0 +1,22 @@ +from ast import List + + +class Solution: + def asteroidCollision(self, asteroids: List[int]) -> List[int]: + stk = [] + + for asteroid in asteroids: + if not stk or asteroid > 0: + stk.append(asteroid) + else: + while stk and stk[-1] > 0 and stk[-1] < abs(asteroid): + stk.pop() + + if stk and stk[-1] == abs(asteroid): + stk.pop() + else: + if not stk or stk[-1] < 0: + stk.append(asteroid) + + return stk + \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..c57781f --- /dev/null +++ b/Dockerfile @@ -0,0 +1,9 @@ +FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9 + +WORKDIR /code + +COPY . /code + +RUN pip install --no-cache-dir --upgrade -r /code/requirements.txt + +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080"] diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..5134f4f --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +install: + pip install --upgrade pip &&\ + pip install -r requirements.txt + +test: + python -m pytest -vv --cov=main --cov=calCLI --cov=mylib test_*.py + +format: + black *.py + +lint: + pylint --disable=R,C + +container-lint: + docker run --rm -i hadolint/hadolint < Dockerfile + +refactor: format lint + +deploy: + aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 561744971673.dkr.ecr.us-east-1.amazonaws.com + docker build -t logistics . + docker tag logistics:latest 561744971673.dkr.ecr.us-east-1.amazonaws.com/logistics:latest + docker push 561744971673.dkr.ecr.us-east-1.amazonaws.com/logistics:latest + + +all: install lint test format deploy diff --git a/requirements.txt b/requirements.txt index 1411a4a..8adaf89 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,11 @@ -pandas \ No newline at end of file +pylint==2.15.3 +click==8.1.3 +pytest==7.1.3 +pytest-cov==4.0.0 +fastapi==0.85.0 +uvicorn==0.18.3 +black==22.8.0 +wikipedia==1.4.0 +ipdb +geopy +git+https://github.com/LIAAD/yake