From dfb67d0e669b3a0929ee7147c46919be4148f3be Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Tue, 3 Jan 2023 22:38:51 +0000 Subject: [PATCH 01/22] added: delete columns to make sorted --- ...eetcode 944 - delete columns to make sorted.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 14. Questions/leetcode 944 - delete columns to make sorted.py diff --git a/14. Questions/leetcode 944 - delete columns to make sorted.py b/14. Questions/leetcode 944 - delete columns to make sorted.py new file mode 100644 index 0000000..de41086 --- /dev/null +++ b/14. Questions/leetcode 944 - delete columns to make sorted.py @@ -0,0 +1,15 @@ +# delete columns to make sorted | leetcode 944 | https://leetcode.com/problems/delete-columns-to-make-sorted/ + +class Solution: + def minDeletionSize(self, strs: list[str]) -> int: + n_cols = len(strs[0]) + n_rows = len(strs) + cols_d = 0 + + for col in range(n_cols): + for row in range(1, n_rows): + if strs[row][col] < strs[row - 1][col]: + cols_d += 1 + break + + return cols_d \ No newline at end of file From b91c171afe572e5fc3f1b46a48221457089be1ae Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Tue, 3 Jan 2023 22:41:42 +0000 Subject: [PATCH 02/22] added: product of array except self --- ...code 238 - product of array except self.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 14. Questions/leetcode 238 - product of array except self.py diff --git a/14. Questions/leetcode 238 - product of array except self.py b/14. Questions/leetcode 238 - product of array except self.py new file mode 100644 index 0000000..a9c54b0 --- /dev/null +++ b/14. Questions/leetcode 238 - product of array except self.py @@ -0,0 +1,24 @@ +# product of array except self | leetcode 238 | https://leetcode.com/problems/product-of-array-except-self/ +# save prefixes to result array and apply postfix in reverse +# (since output array doesnt increase space complexity) + +class Solution: + def productExceptSelf(self, nums: list[int]) -> list[int]: + result = [] + N = len(nums) + + # save prefix to result array + product = 1 + for i in range(N): + product = nums[i] * product + result.append(product) + + # update result array as per postfix + postfix = 1 + for i in range(N - 1, 0, -1): + result[i] = result[i - 1] * postfix + postfix = postfix * nums[i] + result[0] = postfix + + return result + \ No newline at end of file From 06565fb197471d945dbb41bbd2e467019de37295 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Thu, 26 Jan 2023 13:36:47 +0000 Subject: [PATCH 03/22] added: non-overlapping intervals --- .../leetcode 435 - non-overlapping intervals.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 14. Questions/leetcode 435 - non-overlapping intervals.py diff --git a/14. Questions/leetcode 435 - non-overlapping intervals.py b/14. Questions/leetcode 435 - non-overlapping intervals.py new file mode 100644 index 0000000..836a8b9 --- /dev/null +++ b/14. Questions/leetcode 435 - non-overlapping intervals.py @@ -0,0 +1,17 @@ +# non-overlapping intervals | leetcode 435 | https://leetcode.com/problems/non-overlapping-intervals +# sort by starting times; keep track of latest ending time; always keep interval with min end time + +class Solution: + def eraseOverlapIntervals(self, intervals: list[list[int]]) -> int: + min_intervals_to_remove = 0 + intervals.sort(key = lambda x: x[0]) + latest_end = intervals[0][1] + + for i in range(1, len(intervals)): + if intervals[i][0] < latest_end: + min_intervals_to_remove += 1 + latest_end = min(intervals[i][1], latest_end) + else: + latest_end = intervals[i][1] + + return min_intervals_to_remove From 87ba408da9a0ece1bbf8e6d593d762ddfbe48b25 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Thu, 26 Jan 2023 14:49:53 +0000 Subject: [PATCH 04/22] added: barclays plc uk - online assessment --- .../barclays plc uk - online assesment.py | 110 ++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 14. Questions/barclays plc uk - online assesment.py diff --git a/14. Questions/barclays plc uk - online assesment.py b/14. Questions/barclays plc uk - online assesment.py new file mode 100644 index 0000000..a7221c6 --- /dev/null +++ b/14. Questions/barclays plc uk - online assesment.py @@ -0,0 +1,110 @@ +""" +Allie is working on a system that can allocate resources to the +applications in a manner efficient enough to allow the maximum number +of applications to be executed. There are N number of applications +and each application is identified by a unique integer ID (1 to N). +Only M types of resources are available with a unique resourceD. +Each application sends a request message to the system. +The request message includes the information regarding the request time, +the execution ending time, and the type of resource required for execution. +Time is in the MMSS format where MM is minutes and SS is seconds. + +If more than one application sends a request at the same time then only +one application will be approved by the system. The denied requests are +automatically destroyed by the system. When approving the request, the +system ensures that the request will be granted to the application in a +way that will maximize the number of executions. The system can execute +only one application at a time with a given resource. It will deny all +other requests for the resource until the previous application has finished. +Allie wants to know the maximum number of applications that have been +executed successfully. + +Write an algorithm to help Allie calculate the maximum number of applications +that are executed successfully by the system. + +Input +The first line of the input consists of two space-separated integers num and +constX, representing the number of applications (N) and constX is always 3. +The next N lines consist of constX space-separated integers representing the +request time, the execution ending time, and the resourceD of the resource +required by each application for successful execution. + +Output +Print an integer representing the maximum number of applications that are +executed successfully by the system. + + +Testcase 1 | Answer: 4 +4 3 +1000 1020 3 +1020 1030 3 +1030 1040 3 +1010 1045 2 + +Testcase 2 | Ans: 3 +5 3 +1200 1230 1 +1120 1125 2 +1015 1230 1 +1100 1230 1 +1200 1230 3 + +Testcase 3 | Ans: 4 +6 3 +1200 1250 1 +1210 1220 1 +1225 1230 1 +1330 1345 2 +1330 1340 2 +1340 1345 2 +""" + + +# to bucket all requests by resource type +def bucketRequestsByResource(arr): + buckets = dict() + for each_req in arr: + if buckets.get(each_req[2], False) != False: + buckets[each_req[2]].append((each_req[0], each_req[1])) + else: + buckets[each_req[2]] = [(each_req[0], each_req[1])] + + return buckets + + +# to get max number of executed tasks for a single bucket +def numExecutedAppsByBucket(arr): + arr.sort(key = lambda x: x[0]) + N = len(arr) + dont_execute = 0 + latest_end = arr[0][1] + + for i in range(1, N): + if arr[i][0] < latest_end: + dont_execute += 1 + latest_end = min(arr[i][1], latest_end) + else: + latest_end = arr[i][1] + + return (N - dont_execute) + + +# get the maximum number of executed tasks +def numExecutedApps(arr): + buckets = bucketRequestsByResource(arr) + num_execute = 0 + for each_bucket in buckets.values(): + num_execute += numExecutedAppsByBucket(each_bucket) + + return num_execute + + +# driver code +arr = [] +arr_rows, arr_cols = map(int, input().split()) +for idx in range(arr_rows): + arr.append(list(map(int, input().split()))) + +result = numExecutedApps(arr) +print (result) + From 39af035acbfa8da8456ab2c2ad2a0b7e3f021bbe Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Sun, 5 Feb 2023 23:41:11 +0000 Subject: [PATCH 05/22] added: find all anagrams in a string --- ...tcode 438 - find all anagrams in string.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 14. Questions/leetcode 438 - find all anagrams in string.py diff --git a/14. Questions/leetcode 438 - find all anagrams in string.py b/14. Questions/leetcode 438 - find all anagrams in string.py new file mode 100644 index 0000000..c57b15a --- /dev/null +++ b/14. Questions/leetcode 438 - find all anagrams in string.py @@ -0,0 +1,24 @@ +# find all anagrams in string | leetcode 438 | https://leetcode.com/problems/find-all-anagrams-in-a-string/ +# sliding window to track "which" substring; add ptr2 to counter, remove ptr1 from counter + + +from collections import Counter + +class Solution: + def findAnagrams(self, s: str, p: str) -> list[int]: + Ns, Np = len(s), len(p) + ptr1 = 0 + ptr2 = Np - 1 + anagrams = [] + freq_s, freq_p = Counter(s[ptr1:(ptr2 + 1)]), Counter(p) + + while ptr2 < Ns: + if freq_s == freq_p: + anagrams.append(ptr1) + freq_s[s[ptr1]] -= 1 + ptr1 += 1 + ptr2 += 1 + if ptr2 != Ns: + freq_s[s[ptr2]] = 1 + freq_s.get(s[ptr2], 0) + + return anagrams \ No newline at end of file From c233167e681ebd89c8628c920dd7ce08b06bb5a5 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Mon, 6 Feb 2023 01:08:42 +0000 Subject: [PATCH 06/22] added: add two numbers --- .../leetcode 02 - add two numbers.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 14. Questions/leetcode 02 - add two numbers.py diff --git a/14. Questions/leetcode 02 - add two numbers.py b/14. Questions/leetcode 02 - add two numbers.py new file mode 100644 index 0000000..e39d1d9 --- /dev/null +++ b/14. Questions/leetcode 02 - add two numbers.py @@ -0,0 +1,38 @@ +# add two numbers | leetcode 02 | https://leetcode.com/problems/add-two-numbers/ + +# 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]: + res = ListNode() + head = res + + while l1 != None or l2 != None: + if l1 == None: + this_val = res.val + l2.val + l2 = l2.next + elif l2 == None: + this_val = res.val + l1.val + l1 = l1.next + else: + this_val = res.val + l1.val + l2.val + l1, l2 = l1.next, l2.next + + this_digit = this_val % 10 + next_digit = this_val // 10 + + res.val = this_digit + if l1 != None or l2 != None: + res.next = ListNode(next_digit) + res = res.next + + if next_digit > 0: + res.next = ListNode(next_digit) + res = res.next + + return head + \ No newline at end of file From 356678c63f613a11dbc74ef19602c0d6e27c895c Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Mon, 6 Feb 2023 02:18:38 +0000 Subject: [PATCH 07/22] added: longest substring without repeating characters --- ...t substring without repeating characters.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 14. Questions/leetcode 03 - longest substring without repeating characters.py diff --git a/14. Questions/leetcode 03 - longest substring without repeating characters.py b/14. Questions/leetcode 03 - longest substring without repeating characters.py new file mode 100644 index 0000000..d1a4c58 --- /dev/null +++ b/14. Questions/leetcode 03 - longest substring without repeating characters.py @@ -0,0 +1,18 @@ +# longest substring without repeating characters | leetcode 03 | https://leetcode.com/problems/longest-substring-without-repeating-characters +# sliding window; remove elements until last occurence of current duplicate + +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + ptrL = 0 + seen = dict() + longest = 0 + + for ptrR in range(len(s)): + while seen.get(s[ptrR]) is not None: + seen.pop(s[ptrL]) + ptrL += 1 + seen[s[ptrR]] = True + longest = max(ptrR - ptrL + 1, longest) + + return longest + \ No newline at end of file From 22fa69e4c116bdb837e5d65afd92b9ce2cd9c9ac Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Mon, 6 Feb 2023 11:21:31 +0000 Subject: [PATCH 08/22] added: longest consecutive sequence --- ...code 128 - longest consecutive sequence.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 14. Questions/leetcode 128 - longest consecutive sequence.py diff --git a/14. Questions/leetcode 128 - longest consecutive sequence.py b/14. Questions/leetcode 128 - longest consecutive sequence.py new file mode 100644 index 0000000..4427aec --- /dev/null +++ b/14. Questions/leetcode 128 - longest consecutive sequence.py @@ -0,0 +1,22 @@ +# longest consecutive sequence | leetcode 128 | https://leetcode.com/problems/longest-consecutive-sequence/ +# set to look-up previous and next numbers; nested while loop is O(2n) + +class Solution: + def longestConsecutive(self, nums: list[int]) -> int: + if nums == []: + return 0 + + all = set(nums) + longest = 0 + + for each in all: + if each - 1 not in all: + curr = each + seq = 1 + while curr + 1 in all: + seq += 1 + curr = curr + 1 + if seq > longest: + longest = seq + + return longest \ No newline at end of file From 7bb22e8b123e3e050715ba458929804e0148bf3f Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Mon, 6 Feb 2023 12:30:28 +0000 Subject: [PATCH 09/22] added: longest repeating character replacement --- ...longest repeating character replacement.py | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 14. Questions/leetcode 424 - longest repeating character replacement.py diff --git a/14. Questions/leetcode 424 - longest repeating character replacement.py b/14. Questions/leetcode 424 - longest repeating character replacement.py new file mode 100644 index 0000000..92a5607 --- /dev/null +++ b/14. Questions/leetcode 424 - longest repeating character replacement.py @@ -0,0 +1,23 @@ +# longest repeating character replacement | leetcode 424 | https://leetcode.com/problems/longest-repeating-character-replacement/ +# keep track of max freq in sliding window and check if size of window - max freq > k + +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + ptrL = 0 + ptrR = 0 + longest = 0 + freq = dict() + max_freq = 0 + w_size = 0 + + for ptrR in range(len(s)): + freq[s[ptrR]] = 1 + freq.get(s[ptrR], 0) + max_freq = max(max_freq, freq[s[ptrR]]) + + if (ptrR - ptrL + 1) - max_freq > k: + freq[s[ptrL]] -= 1 + ptrL += 1 + + longest = max(longest, (ptrR - ptrL + 1)) + + return longest \ No newline at end of file From 0492572687c3abf00e81e6501ac12a29774d8d73 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Fri, 10 Feb 2023 09:52:25 +0000 Subject: [PATCH 10/22] added: naming a company --- .../leetcode 2306 - naming a company.py | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 14. Questions/leetcode 2306 - naming a company.py diff --git a/14. Questions/leetcode 2306 - naming a company.py b/14. Questions/leetcode 2306 - naming a company.py new file mode 100644 index 0000000..1bb30b7 --- /dev/null +++ b/14. Questions/leetcode 2306 - naming a company.py @@ -0,0 +1,24 @@ +# naming a company | leetcode 2306 | https://leetcode.com/problems/naming-a-company +# bucket by starting character to make it n(26^2.n) and compare each set with each other + +class Solution: + def distinctNames(self, ideas: list[str]) -> int: + buckets = dict() + num_distinct = 0 + + for idea in ideas: + if buckets.get(idea[0]) is None: + buckets[idea[0]] = {idea[1:]} + else: + buckets[idea[0]].add(idea[1:]) + + for prefix_i, suffix_i in buckets.items(): + for prefix_j, suffix_j in buckets.items(): + if prefix_i == prefix_j: + continue + common = len(suffix_i & suffix_j) + common_i = len(suffix_i) - common + common_j = len(suffix_j) - common + num_distinct += common_i * common_j + + return num_distinct \ No newline at end of file From dcfe1110b80de4ccb88b4672d094b8b130ff22fc Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Sat, 11 Feb 2023 13:57:35 +0000 Subject: [PATCH 11/22] added: two sum II --- 14. Questions/leetcode 167 - two sum II.py | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 14. Questions/leetcode 167 - two sum II.py diff --git a/14. Questions/leetcode 167 - two sum II.py b/14. Questions/leetcode 167 - two sum II.py new file mode 100644 index 0000000..f7f43bc --- /dev/null +++ b/14. Questions/leetcode 167 - two sum II.py @@ -0,0 +1,21 @@ +# two sum II - input array is sorted | leetcode 167 | https://leetcode.com/problems/two-sum-ii-input-array-is-sorted +# use two pointers on sorted array; if sum > target slide window left, else slide window right + +class Solution: + def twoSum(self, numbers: list[int], target: int) -> list[int]: + ptrL = 0 + ptrR = 1 + N = len(numbers) + + while ptrR < N: + s = numbers[ptrR] + numbers[ptrL] + if s == target: + return [ptrL + 1, ptrR + 1] + elif s < target: + ptrL += 1 + ptrR += 1 + else: + ptrL -= 1 + + # unreachable for testcases with exactly one solution + return [-1, -1] \ No newline at end of file From 82defae8acc69ef17233797059b69f09c4a149d5 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Sat, 11 Feb 2023 13:57:49 +0000 Subject: [PATCH 12/22] added: three sum --- 14. Questions/leetcode 15 - three sum.py | 29 ++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 14. Questions/leetcode 15 - three sum.py diff --git a/14. Questions/leetcode 15 - three sum.py b/14. Questions/leetcode 15 - three sum.py new file mode 100644 index 0000000..9178a13 --- /dev/null +++ b/14. Questions/leetcode 15 - three sum.py @@ -0,0 +1,29 @@ +# three sum | leetcode 15 | https://leetcode.com/problems/3sum/ +# - sorted; nested loop; outer loop for first element +# - inner loop for two sum on rest of list +# - avoid duplicates by shifting window till last occurrence + +class Solution: + def threeSum(self, nums: list[int]) -> list[list[int]]: + nums.sort() + N = len(nums) + triplets = [] + for i in range(N): + if i > 0 and nums[i] == nums[i - 1]: + continue + + ptrL = i + 1 + ptrR = N - 1 + while ptrL < ptrR: + s = nums[i] + nums[ptrL] + nums[ptrR] + if s > 0: + ptrR -= 1 + elif s < 0: + ptrL += 1 + else: + triplets.append([nums[i], nums[ptrL], nums[ptrR]]) + ptrL += 1 + while nums[ptrL] == nums[ptrL - 1] and ptrL < ptrR: + ptrL += 1 + + return triplets \ No newline at end of file From 0d52aba7ca762b832a960ac772e6ffc0cfb1f7d3 Mon Sep 17 00:00:00 2001 From: Mihir Singh <44063783+mihirs16@users.noreply.github.com> Date: Sun, 19 Feb 2023 10:04:30 +0000 Subject: [PATCH 13/22] added leetcode questions (#20) * added: minimum distance between bst nodes * added: zigzag level order traversal --- ...code 103 - zigzag level order traversal.py | 37 +++++++++++++++++++ ...83 - minimum distance between bst nodes.py | 33 +++++++++++++++++ 2 files changed, 70 insertions(+) create mode 100644 14. Questions/leetcode 103 - zigzag level order traversal.py create mode 100644 14. Questions/leetcode 783 - minimum distance between bst nodes.py diff --git a/14. Questions/leetcode 103 - zigzag level order traversal.py b/14. Questions/leetcode 103 - zigzag level order traversal.py new file mode 100644 index 0000000..59d42a8 --- /dev/null +++ b/14. Questions/leetcode 103 - zigzag level order traversal.py @@ -0,0 +1,37 @@ +# binary tree zigzag level order traversal | leetcode 103 | https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal +# use flag to keep track of reversed levels; O(n) because worst case is full level - n/2 elements + +# 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 zigzagLevelOrder(self, root: TreeNode) -> list[list[int]]: + res = [] + tempQ = [] + zig = False + + # queue to track visits + tempQ.append(root) + LtempQ = len(tempQ) + + # keep iterating till: + # the track queue is empty + while LtempQ is not 0: + LtempQ = len(tempQ) + level = [] + for i in range(LtempQ): + node = tempQ.pop(0) # pop this node from queue (visited) + if node is not None: + level.append(node.val) # add this node to the level + tempQ.append(node.left) # add left child to queue (to visit) + tempQ.append(node.right) # add right child to queue (to visit) + + if len(level) is not 0: # add level and reverse if zig + res.append(reversed(level) if zig else level) + zig = not zig + + return res \ No newline at end of file diff --git a/14. Questions/leetcode 783 - minimum distance between bst nodes.py b/14. Questions/leetcode 783 - minimum distance between bst nodes.py new file mode 100644 index 0000000..9129953 --- /dev/null +++ b/14. Questions/leetcode 783 - minimum distance between bst nodes.py @@ -0,0 +1,33 @@ +# minimum distance between bst nodes | leetcode 783 | https://leetcode.com/problems/minimum-distance-between-bst-nodes +# dfs; inorder; keep track of last traversed node and check against minimum difference + + +# 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 minDiffInBST(self, root: TreeNode) -> int: + stack = [] + curr = root + last = None + minDiff = float("inf") + while True: + if curr is not None: + stack.append(curr) + curr = curr.left + elif stack: + curr = stack.pop() + if last is not None: + minDiff = min(abs(last.val - curr.val), minDiff) + last = curr + curr = curr.right + else: + break + + return int(minDiff) + From c7c4498295db81f01d3344c871986d526096440d Mon Sep 17 00:00:00 2001 From: Mihir Singh <44063783+mihirs16@users.noreply.github.com> Date: Fri, 24 Feb 2023 19:51:05 +0000 Subject: [PATCH 14/22] added leetcode question (#21) * added: minimum distance between bst nodes * added: zigzag level order traversal * added: add to array form of integer * added: capacity to ship * added: single element in sorted array * added: ipo --- ...etcode 1011 - capacity to ship packages.py | 33 +++++++++++++++++++ 14. Questions/leetcode 502 - ipo.py | 21 ++++++++++++ ... 540 - single element in a sorted array.py | 24 ++++++++++++++ ...code 989 - add to array form of integer.py | 19 +++++++++++ 4 files changed, 97 insertions(+) create mode 100644 14. Questions/leetcode 1011 - capacity to ship packages.py create mode 100644 14. Questions/leetcode 502 - ipo.py create mode 100644 14. Questions/leetcode 540 - single element in a sorted array.py create mode 100644 14. Questions/leetcode 989 - add to array form of integer.py diff --git a/14. Questions/leetcode 1011 - capacity to ship packages.py b/14. Questions/leetcode 1011 - capacity to ship packages.py new file mode 100644 index 0000000..ad5e4da --- /dev/null +++ b/14. Questions/leetcode 1011 - capacity to ship packages.py @@ -0,0 +1,33 @@ +# capacity to ship packages within D days | leetcode 1011 | https://leetcode.com/problems/capacity-to-ship-packages-within-d-days/ +# binary search on a range of min and max capacity required +# min capacity = max(weights) and max capacity = sum(weights) + +class Solution: + def shipWithinDays(self, weights: list[int], days: int) -> int: + low, high = max(weights), sum(weights) + res = high + + # check if days required for a capacity is less than D + def isPossible (capacity): + daysReq = 1 + window = capacity + for weight in weights: + if window - weight < 0: + window = capacity + daysReq += 1 + window -= weight + + return daysReq <= days + + # binary search on [min...max] + while low <= high: + mid = (high + low) // 2 + + if isPossible(mid): + res = min(res, mid) + high = mid - 1 + else: + low = mid + 1 + + return res + diff --git a/14. Questions/leetcode 502 - ipo.py b/14. Questions/leetcode 502 - ipo.py new file mode 100644 index 0000000..e48b6e1 --- /dev/null +++ b/14. Questions/leetcode 502 - ipo.py @@ -0,0 +1,21 @@ +# IPO | leetcode 502 | https://leetcode.com/problems/ipo/ +# min-heap to track capital and max-heap to track profits + +import heapq + +class Solution: + def findMaximizedCapital(self, k: int, w: int, profits: list[int], capital: list[int]) -> int: + maxHeap = [] + minHeap = [(c, p) for c, p in zip(capital, profits)] + heapq.heapify(minHeap) + + for _ in range(k): + while minHeap and minHeap[0][0] <= w: + _, p = heapq.heappop(minHeap) + heapq.heappush(maxHeap, -1 * p) + if not maxHeap: + break + w += -1 * heapq.heappop(maxHeap) + + return w + diff --git a/14. Questions/leetcode 540 - single element in a sorted array.py b/14. Questions/leetcode 540 - single element in a sorted array.py new file mode 100644 index 0000000..fe28feb --- /dev/null +++ b/14. Questions/leetcode 540 - single element in a sorted array.py @@ -0,0 +1,24 @@ +# single element in a sorted array | leetcode 540 | https://leetcode.com/problems/single-element-in-a-sorted-array/ +# binary search over sorted array; check if mid is even and mid is the first of the duplicates + +class Solution: + def singleNonDuplicate(self, nums: list[int]) -> int: + N = len(nums) + if N < 2: + return nums[0] + low, high, mid = 0, N, 0 + while low <= high: + mid = low + ((high - low) // 2) + + if mid == N - 1: + return nums[mid] + + if nums[mid] == nums[mid - 1] or nums[mid] == nums[mid + 1]: + if (mid % 2 == 0) == (nums[mid] == nums[mid + 1]): + low = mid + else: + high = mid + else: + return nums[mid] + + return nums[mid] \ No newline at end of file diff --git a/14. Questions/leetcode 989 - add to array form of integer.py b/14. Questions/leetcode 989 - add to array form of integer.py new file mode 100644 index 0000000..6fbd9ef --- /dev/null +++ b/14. Questions/leetcode 989 - add to array form of integer.py @@ -0,0 +1,19 @@ +# add to array form of integer | leetcode 989 | https://leetcode.com/problems/add-to-array-form-of-integer + +class Solution: + def addToArrayForm(self, num: list[int], k: int) -> list[int]: + n = len(num) - 1 + carry = 0 + while k or carry: + k, digit = k // 10, k % 10 + each = carry + digit + if n < 0: + num.insert(0, each % 10) + else: + each = each + num[n] + num[n] = each % 10 + carry = each // 10 + n -= 1 + + return num + From 1340e539cfb2a6964a420657403e1ab6bc791b53 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Sat, 25 Feb 2023 12:19:19 +0000 Subject: [PATCH 15/22] added: target sum --- 14. Questions/leetcode 494 - target sum.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 14. Questions/leetcode 494 - target sum.py diff --git a/14. Questions/leetcode 494 - target sum.py b/14. Questions/leetcode 494 - target sum.py new file mode 100644 index 0000000..ddc9e1b --- /dev/null +++ b/14. Questions/leetcode 494 - target sum.py @@ -0,0 +1,22 @@ +# target sum | leetcode 494 | https://leetcode.com/problems/target-sum/ +# 0/1 knapsack to decide +/- and cache (index, total) + +class Solution: + def findTargetSumWays(self, nums: list[int], target: int) -> int: + N = len(nums) + mem = dict() + + if N == 0: + return 0 + + def knapsack(n, s): + if n == N: + return 1 if s == target else 0 + + if (n, s) in mem: + return mem[(n, s)] + + mem[(n, s)] = knapsack(n+1, s + nums[n]) + knapsack(n+1, s - nums[n]) + return mem[(n, s)] + + return knapsack(0, 0) From 40c285cff56cc56aee3ba7d176b045e74b622a89 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Tue, 28 Feb 2023 01:18:42 +0000 Subject: [PATCH 16/22] added: construct quad trees --- .../leetcode 427 - construct quad tree.py | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 14. Questions/leetcode 427 - construct quad tree.py diff --git a/14. Questions/leetcode 427 - construct quad tree.py b/14. Questions/leetcode 427 - construct quad tree.py new file mode 100644 index 0000000..f2dba66 --- /dev/null +++ b/14. Questions/leetcode 427 - construct quad tree.py @@ -0,0 +1,37 @@ +# construct quad tree | leetcode 427 | https://leetcode.com/problems/construct-quad-tree/ +# recursively call each quad of the grid and check if each quad is uniform or not + +# Definition for a QuadTree node. +class Node: + def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): + self.val = val + self.isLeaf = isLeaf + self.topLeft = topLeft + self.topRight = topRight + self.bottomLeft = bottomLeft + self.bottomRight = bottomRight + + +class Solution: + def construct(self, grid: list[list[int]]) -> Node: + def checkThisQuad(row, col, n) -> bool: + for i in range(row, row + n): + for j in range(col, col + n): + if grid[i][j] != grid[row][col]: + return False + return True + + def quadTree(row, col, n): + if checkThisQuad(row, col, n): + return Node(grid[row][col], 1, None, None, None, None) + + + return Node(grid[row][col], 0, + quadTree(row, col, n//2), + quadTree(row, col + n//2, n//2), + quadTree(row + n//2, col, n//2), + quadTree(row + n//2, col + n//2, n//2) + ) + + return quadTree(0, 0, len(grid)) + From d6df4b013d9b980759fbaa692313c31350da0d37 Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Thu, 2 Mar 2023 02:02:43 +0000 Subject: [PATCH 17/22] added: string compression --- .../leetcode 443 - string compression.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 14. Questions/leetcode 443 - string compression.py diff --git a/14. Questions/leetcode 443 - string compression.py b/14. Questions/leetcode 443 - string compression.py new file mode 100644 index 0000000..098546c --- /dev/null +++ b/14. Questions/leetcode 443 - string compression.py @@ -0,0 +1,22 @@ +# string compression | leetcode 443 | https://leetcode.com/problems/string-compression/ +# sliding window to keep track of a char's occurence + +class Solution: + def compress(self, chars: list[str]) -> int: + ptrL, ptrR = 0, 0 + total = 0 + chars += " " + + while ptrR < len(chars): + if chars[ptrL] != chars[ptrR]: + chars[total] = chars[ptrL] + total += 1 + group = ptrR - ptrL + if group > 1: + for x in str(group): + chars[total] = x + total += 1 + ptrL = ptrR + ptrR += 1 + + return total From 3d577429c3c9fab205f3d141d006ec3f10add45b Mon Sep 17 00:00:00 2001 From: mihirs16 Date: Fri, 3 Mar 2023 03:31:27 +0000 Subject: [PATCH 18/22] added: index of first occurrence --- ...leetcode 28 - index of first occurrence.py | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 14. Questions/leetcode 28 - index of first occurrence.py diff --git a/14. Questions/leetcode 28 - index of first occurrence.py b/14. Questions/leetcode 28 - index of first occurrence.py new file mode 100644 index 0000000..e059e17 --- /dev/null +++ b/14. Questions/leetcode 28 - index of first occurrence.py @@ -0,0 +1,26 @@ +# find the index of the first occurrence of a string | leetcode 28 | https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/ +# sliding window to match each character of the haystack with the needle; no slices. + +class Solution: + def strStr(self, haystack: str, needle: str) -> int: + # ----- using regex ----- + # if needle == '': + # return 0 + + # import re + # match = re.search(needle, haystack) + # return match.start() if match else -1 + + # ----- using sliding windows ----- + ptrL, ptrR = 0, 0 + N_needle, N_haystack = len(needle), len(haystack) + while ptrR < N_haystack: + if haystack[ptrR] == needle[ptrR - ptrL]: + ptrR += 1 + if ptrR - ptrL > N_needle - 1: + return ptrL + else: + ptrR = ptrL + 1 + ptrL += 1 + + return -1 From c455b1c86c9f9f017dc7c60860e0fb20e2eaf8d0 Mon Sep 17 00:00:00 2001 From: Viththal Khandelwal Date: Sat, 25 Mar 2023 14:30:24 -0400 Subject: [PATCH 19/22] enumerate function --- 07. Functional Programming/enumerate.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 07. Functional Programming/enumerate.py diff --git a/07. Functional Programming/enumerate.py b/07. Functional Programming/enumerate.py new file mode 100644 index 0000000..eef1904 --- /dev/null +++ b/07. Functional Programming/enumerate.py @@ -0,0 +1,4 @@ +fruits = ['apple', 'banana', 'cherry', 'grape'] + +for index, fruit in enumerate(fruits, 1): + print(index, fruit) From 0ee2da7b9fc7513bd2201dcd3d0cb444ef865668 Mon Sep 17 00:00:00 2001 From: Jackyrd3 Date: Sat, 30 Mar 2024 16:10:41 -0700 Subject: [PATCH 20/22] Add logger Middleware --- server.js | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 server.js diff --git a/server.js b/server.js new file mode 100644 index 0000000..ec24f31 --- /dev/null +++ b/server.js @@ -0,0 +1,32 @@ +// Import required modules +const express = require('express'); + +// Create an Express application +const app = express(); + +// Middleware function to log requests +app.use((req, res, next) => { + console.log(`Received a ${req.method} request to ${req.url}`); + next(); // Call next() to move to the next middleware or route handler +}); + +// Middleware function to check if the request contains a specific header +app.use((req, res, next) => { + if (req.headers.authorization) { + console.log('Authorization header present'); + } else { + console.log('Authorization header not present'); + } + next(); +}); + +// Route handler +app.get('/', (req, res) => { + res.send('Hello, World!'); +}); + +// Starting the server +const PORT = process.env.PORT || 3000; +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +}); From a00994566223b040934f82ef5a0a0096e8f875a2 Mon Sep 17 00:00:00 2001 From: Jackyrd3 Date: Sat, 30 Mar 2024 16:10:56 -0700 Subject: [PATCH 21/22] Add logger --- loggerMiddleware.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 loggerMiddleware.js diff --git a/loggerMiddleware.js b/loggerMiddleware.js new file mode 100644 index 0000000..25925e8 --- /dev/null +++ b/loggerMiddleware.js @@ -0,0 +1,29 @@ +const express = require('express'); +const app = express(); + +// Middleware function to log requests +app.use((req, res, next) => { + console.log(`Received a ${req.method} request to ${req.url}`); + next(); // Call next() to move to the next middleware or route handler +}); + +// Middleware function to check if the request contains a specific header +app.use((req, res, next) => { + if (req.headers.authorization) { + console.log('Authorization header present'); + } else { + console.log('Authorization header not present'); + } + next(); +}); + +// Route handler +app.get('/', (req, res) => { + res.send('Hello, World!'); +}); + +// Starting the server +const PORT = process.env.PORT || 3000; +app.listen(PORT, () => { + console.log(`Server is running on port ${PORT}`); +}); From 199033535d0e3ee41d61760dbcb767d07e48c306 Mon Sep 17 00:00:00 2001 From: Agamergen Date: Sat, 25 Jan 2025 16:49:29 +0300 Subject: [PATCH 22/22] Create LEARN I have to learn this --- 03. Data Structures/Queues/LEARN | 1 + 1 file changed, 1 insertion(+) create mode 100644 03. Data Structures/Queues/LEARN diff --git a/03. Data Structures/Queues/LEARN b/03. Data Structures/Queues/LEARN new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/03. Data Structures/Queues/LEARN @@ -0,0 +1 @@ +