98 |
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
--------------------------------------------------------------------------------
/Problem code submissions/1189. Maximum Number of Balloons.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #1189. Maximum Number of Balloons
3 | def maxNumberOfBalloons(self, text: str) -> int:
4 | d = {"b":0, "a":0, "l":0, "o":0, "n":0}
5 |
6 | for l in text:
7 | if l in d:
8 | d[l] += 1
9 |
10 | lo_count = min(d["l"], d["o"]) // 2
11 | ban_count = min(d["b"], d["a"], d["n"])
12 |
13 | return min(lo_count, ban_count)
--------------------------------------------------------------------------------
/Problem code submissions/1207. Unique Number of Occurrences.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #1207. Unique Number of Occurrences
3 | def uniqueOccurrences(self, arr: List[int]) -> bool:
4 | d = {}
5 | for i in arr:
6 | if i in d:
7 | d[i] += 1
8 | else:
9 | d[i] = 1
10 | return len(set(d.values())) == len(d.values())
--------------------------------------------------------------------------------
/Problem code submissions/1295. Find Numbers with Even Number of Digits.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #1295. Find Numbers with Even Number of Digits
3 | def findNumbers(self, nums: List[int]) -> int:
4 | return sum(len(str(i))%2 == 0 for i in nums)
--------------------------------------------------------------------------------
/Problem code submissions/1304. Find N Unique Integers Sum up to Zero.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #1304. Find N Unique Integers Sum up to Zero
3 | def sumZero(self, n: int) -> List[int]:
4 | res = []
5 |
6 | for i in range(1, (n //2)+ 1):
7 | res.append(i)
8 | res.append(-i)
9 |
10 | if n % 2 != 0:
11 | res.append(0)
12 | return res
--------------------------------------------------------------------------------
/Problem code submissions/136. Single Number.py:
--------------------------------------------------------------------------------
1 | nums = [2, 2, 1]
2 |
3 | d = {}
4 | print('h')
5 | #for i in nums:
6 | # pass
--------------------------------------------------------------------------------
/Problem code submissions/144. BinaryTreePreorderTraversal.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def preorderTraversal(self, root: TreeNode) -> List[int]:
9 | if root is None:
10 | return []
11 |
12 | return [root.val] + self.preorderTraversal(root.left) + self.preorderTraversal(root.right)
13 |
--------------------------------------------------------------------------------
/Problem code submissions/1448. Count Good Nodes in Binary Tree.py:
--------------------------------------------------------------------------------
1 | #1448. Count Good Nodes in Binary Tree
2 |
3 | # Definition for a binary tree node.
4 | # class TreeNode:
5 | # def __init__(self, val=0, left=None, right=None):
6 | # self.val = val
7 | # self.left = left
8 | # self.right = right
9 |
10 | class Solution:
11 | total = 0
12 | def goodNodes(self, root: TreeNode) -> int:
13 |
14 | def traverse(root, max = None):
15 | if root == None:
16 | return
17 |
18 | if max == None:
19 | max = root.val
20 |
21 | traverse(root.left, max)
22 | traverse(root.right, max)
23 |
24 | self.total += 1
25 |
26 | else:
27 | if(root.val >= max):
28 | max = root.val
29 | self.total += 1
30 |
31 | traverse(root.left, max)
32 | traverse(root.right, max)
33 | return
34 |
35 | traverse(root,None)
36 | return self.total
--------------------------------------------------------------------------------
/Problem code submissions/145. BinaryTreePostorderTraversal.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def postorderTraversal(self, root: TreeNode) -> List[int]:
9 | if root is None:
10 | return []
11 |
12 | return self.postorderTraversal(root.left) + self.postorderTraversal(root.right) + [root.val]
13 |
--------------------------------------------------------------------------------
/Problem code submissions/1450. Number of Students Doing Homework at a Given Time.py:
--------------------------------------------------------------------------------
1 | #Brute Force:
2 | class Solution:
3 | '''
4 | 1450. Number of Students Doing Homework at a Given Time
5 | '''
6 | def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
7 | count = 0
8 | for i in range(len(startTime)):
9 | if startTime[i] <= queryTime <=endTime[i]:
10 | count += 1
11 | return count
12 |
13 |
14 | #One-liner:
15 | class Solution:
16 | def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
17 | return sum((startTime[i] <= queryTime <=endTime[i]) for i in range(len(startTime)))
18 |
--------------------------------------------------------------------------------
/Problem code submissions/1550. Three Consecutive Odds.py:
--------------------------------------------------------------------------------
1 | def threeConsecutiveOdds(arr):
2 | '''
3 | 1550. Three Consecutive Odds
4 | Author: Ayushi Rawat
5 | '''
6 | if len(arr) < 3:
7 | return False
8 |
9 | for i in range(len(arr) - 2):
10 | odd1 = arr[i]
11 | odd2 = arr[i + 1]
12 | odd3 = arr[i + 2]
13 |
14 | if (odd1 % 2 != 0) and (odd2 % 2 != 0) and (odd3 % 2 != 0):
15 | return True
16 | return False
17 |
18 | # res = threeConsecutiveOdds([7,8,9,3,2,3])
19 | # print(res)
--------------------------------------------------------------------------------
/Problem code submissions/1619. Mean of Array After Removing Some Elements.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | 1619. Mean of Array After Removing Some Elements
4 | Author: Ayushi Rawat
5 | '''
6 |
7 | def trimMean(self, arr: List[int]) -> float:
8 | arr.sort()
9 |
10 | n = len(arr)
11 |
12 | per = int(n*5/100)
13 |
14 | l2 = arr[per:len(arr)-per]
15 | x = sum(l2)/len(l2)
16 |
17 | return x
18 |
19 |
--------------------------------------------------------------------------------
/Problem code submissions/1636. Sort Array by Increasing Frequency.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | 1636. Sort Array by Increasing Frequency
4 | Author: Ayushi Rawat
5 | '''
6 |
7 | def frequencySort(self, nums: List[int]) -> List[int]:
8 | nums.sort(reverse=True)
9 |
10 | x = sorted(nums, key=nums.count)
11 | return x
--------------------------------------------------------------------------------
/Problem code submissions/1721. Swapping Nodes in a Linked List.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | 1721. Swapping Nodes in a Linked List
4 | '''
5 | def swapNodes(self, head: ListNode, k: int) -> ListNode:
6 |
7 | # Initial State
8 | slow, fast = head, head
9 |
10 | # Phase 1
11 | for _ in range(k - 1):
12 | fast = fast.next
13 | first = fast
14 |
15 | # Phase 2
16 | while fast.next:
17 | slow, fast = slow.next, fast.next
18 |
19 | # Last
20 | first.val, slow.val = slow.val, first.val
21 |
22 | return head
--------------------------------------------------------------------------------
/Problem code submissions/1748. Sum of Unique Elements.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #1748. Sum of Unique Elements
3 | def sumOfUnique(self, nums: List[int]) -> int:
4 | s = {}
5 | for i in nums:
6 | if i in s:
7 | s[i] += 1
8 | else:
9 | s[i] = 1
10 |
11 | res = 0
12 | for i in s:
13 | if s[i]==1:
14 | res += i
15 | return res(a)
--------------------------------------------------------------------------------
/Problem code submissions/1816. Truncate Sentence.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | 1816. Truncate Sentence
4 | '''
5 | def truncateSentence(self, s: str, k: int) -> str:
6 | words = s.split(" ")
7 | return " ".join(words[:k])
--------------------------------------------------------------------------------
/Problem code submissions/1822. Sign of the Product of an Array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def arraySign(self, nums: List[int]) -> int:
3 | prod = 1
4 |
5 | for i in range(len(nums)):
6 | prod *= nums[i]
7 |
8 | if prod > 0:
9 | return 1
10 | elif prod == 0:
11 | return 0
12 | else:
13 | return -1
14 |
15 |
16 | #Second solution
17 | class Solution:
18 | def arraySign(self, nums: List[int]) -> int:
19 | if 0 in nums:
20 | return 0
21 |
22 | count = 0
23 | for i in nums:
24 | if i < 0:
25 | count += 1
26 | return 1 if count%2 == 0 else -1
27 |
--------------------------------------------------------------------------------
/Problem code submissions/1869. Longer Contiguous Segments of Ones than Zeros.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def checkZeroOnes(self, s: str) -> bool:
3 | '''
4 | 1869. Longer Contiguous Segments of Ones than Zeros
5 | By: Ayushi Rawat
6 | '''
7 | count0, count1, temp0, temp1 = 0, 0, 0, 0
8 |
9 | for number in s:
10 | if number == '0':
11 | temp0 += 1
12 | temp1 = 0
13 | else:
14 | temp1 += 1
15 | temp0 = 0
16 | count0 = max(count0, temp0)
17 | count1 = max(count1, temp1)
18 |
19 | return count1 > count0
20 |
--------------------------------------------------------------------------------
/Problem code submissions/2027. Minimum Moves to Convert String.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #2027. Minimum Moves to Convert String
3 | def minimumMoves(self, s: str) -> int:
4 | count, i = 0, 0
5 |
6 | while i < len(s):
7 | if s[i] == 'O':
8 | i += 1
9 | else:
10 | #print(s[i],count,i)
11 | count += 1
12 | i = i + 3
13 | return count
14 |
--------------------------------------------------------------------------------
/Problem code submissions/206. Reverse LinkedList.py:
--------------------------------------------------------------------------------
1 | # Definition for singly-linked list.
2 | # class ListNode:
3 | # def __init__(self, val=0, next=None):
4 | # self.val = val
5 | # self.next = next
6 | class Solution:
7 | def reverseList(self, head: ListNode) -> ListNode:
8 | prev=None
9 | while head:
10 | temp=head
11 | head=head.next
12 | temp.next=prev
13 | prev=temp
14 | return prev
15 |
--------------------------------------------------------------------------------
/Problem code submissions/217. Contains Duplicate.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #217. Contains Duplicate
3 | def containsDuplicate(self, nums: List[int]) -> bool:
4 | return len(set(nums)) != len(nums)
--------------------------------------------------------------------------------
/Problem code submissions/220. Contains Duplicate III.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
3 | if t == 0 and len(nums) == len(set(nums)):
4 | return False
5 | for i in range(len(nums)):
6 | for j in range(i+1, i+k+1,1):
7 | if j < len(nums) and abs(nums[i] - nums[j]) <= t:
8 | return True
9 | return False
--------------------------------------------------------------------------------
/Problem code submissions/242. Valid Anagram.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #242. Valid Anagram
3 | def isAnagram(self, s: str, t: str) -> bool:
4 | return sorted(s) == sorted(t)
--------------------------------------------------------------------------------
/Problem code submissions/344. Reverse String.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def reverseString(self, s: List[str]) -> None:
3 | """
4 | Do not return anything, modify s in-place instead.
5 | """
6 | head = 0
7 | tail = len(s)-1
8 |
9 | while tail > head:
10 | #swap
11 | s[head], s[tail] = s[tail], s[head]
12 |
13 | #increment pointer
14 | head += 1
15 | tail -= 1
--------------------------------------------------------------------------------
/Problem code submissions/387. First Unique Character in a String.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #387. First Unique Character in a String
3 | def firstUniqChar(self, s: str) -> int:
4 | from collections import Counter
5 | d = Counter(s)
6 |
7 | for i in d:
8 | if d[i] == 1:
9 | return s.index(i)
10 | else:
11 | return -1
--------------------------------------------------------------------------------
/Problem code submissions/453. Minimum Moves to Equal Array Elements.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #gives timeout error
3 | def minMoves(self, nums: List[int]) -> int:
4 | '''
5 | 453. Minimum Moves to Equal Array Elements
6 | By: Ayushi Rawat
7 | '''
8 | counter = 0
9 | curr_min = min(nums)
10 | curr_max = max(nums)
11 |
12 | while curr_max != curr_min:
13 | counter += 1
14 | nums.sort()
15 |
16 | for i in range(len(nums)-1):
17 | nums[i] += 1
18 |
19 | curr_min = min(nums)
20 | curr_max = max(nums)
21 | return counter
22 |
23 | #second improved solution
24 | def minMoves(self, nums: List[int]) -> int:
25 | _sum = 0
26 | _min = min(nums)
27 |
28 | for i in range(len(nums)):
29 | _sum += (nums[i] - _min)
30 |
31 | return _sum
--------------------------------------------------------------------------------
/Problem code submissions/459. Repeated Substring Pattern.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def repeatedSubstringPattern(self, s: str) -> bool:
3 | sub = ''
4 | l1 = len(s)
5 |
6 | for i in range(l1-1):
7 | sub = sub + s[i]
8 | l2 = len(sub)
9 |
10 | res = sub*(l1//l2)
11 |
12 | if res == s:
13 | return True
14 | return False
--------------------------------------------------------------------------------
/Problem code submissions/500. Keyboard Row.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #500. Keyboard Row
3 | def findWords(self, words: List[str]) -> List[str]:
4 | a, b, c = 'qwertyuiop', 'asdfghjkl', 'zxcvbnm'
5 | res =[]
6 |
7 | for word in words:
8 | counter1, counter2, counter3 = 0, 0, 0
9 |
10 | for i in word:
11 | if i.lower() in a:
12 | counter1 += 1
13 | elif i.lower() in b:
14 | counter2 += 1
15 | elif i.lower() in c:
16 | counter3 += 1
17 |
18 | if counter1 == len(word) or counter2 == len(word) or counter3 == len(word):
19 | res.append(word)
20 | return res
21 |
--------------------------------------------------------------------------------
/Problem code submissions/5734. Check if the Sentence Is Pangram.py:
--------------------------------------------------------------------------------
1 | '''
2 | 5734. Check if the Sentence Is Pangram
3 | Author: Ayushi Rawat
4 |
5 | A pangram is a sentence where every letter of the English alphabet appears at least once.
6 |
7 | Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
8 |
9 |
10 |
11 | Example 1:
12 |
13 | Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
14 | Output: true
15 | Explanation: sentence contains at least one of every letter of the English alphabet.
16 | Example 2:
17 |
18 | Input: sentence = "leetcode"
19 | Output: false
20 |
21 |
22 | Constraints:
23 |
24 | 1 <= sentence.length <= 1000
25 | sentence consists of lowercase English letters.
26 | '''
27 |
28 | class Solution:
29 | def checkIfPangram(self, sentence: str) -> bool:
30 | return len(set(sentence)) == 26
31 |
--------------------------------------------------------------------------------
/Problem code submissions/5735. Maximum Ice Cream Bars.py:
--------------------------------------------------------------------------------
1 | '''
2 | 5735. Maximum Ice Cream Bars
3 | Author: Ayushi Rawat
4 |
5 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
6 | At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
7 | Return the maximum number of ice cream bars the boy can buy with coins coins.
8 |
9 | Note: The boy can buy the ice cream bars in any order.
10 |
11 | Example 1:
12 |
13 | Input: costs = [1,3,2,4,1], coins = 7
14 | Output: 4
15 | Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
16 | Example 2:
17 |
18 | Input: costs = [10,6,8,7,7,8], coins = 5
19 | Output: 0
20 | Explanation: The boy cannot afford any of the ice cream bars.
21 | Example 3:
22 |
23 | Input: costs = [1,6,3,1,2,5], coins = 20
24 | Output: 6
25 | Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
26 |
27 |
28 | Constraints:
29 |
30 | costs.length == n
31 | 1 <= n <= 105
32 | 1 <= costs[i] <= 105
33 | 1 <= coins <= 108
34 | '''
35 |
36 | class Solution:
37 | def maxIceCream(self, costs: List[int], coins: int) -> int:
38 | costs.sort()
39 | a=0
40 | cnt=0
41 | for c in costs:
42 | a+=c
43 | if a<=coins:
44 | cnt+=1
45 | else:
46 | break
47 | return cnt
48 |
49 |
--------------------------------------------------------------------------------
/Problem code submissions/5736. Single-Threaded CPU.py:
--------------------------------------------------------------------------------
1 | '''
2 | 5736. Single-Threaded CPU
3 | Author: Ayushi Rawat
4 |
5 | You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
6 | You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
7 | If the CPU is idle and there are no available tasks to process, the CPU remains idle.
8 | If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
9 | Once a task is started, the CPU will process the entire task without stopping.
10 | The CPU can finish a task then start a new one instantly.
11 | Return the order in which the CPU will process the tasks.
12 |
13 | Constraints:
14 | tasks.length == n
15 | 1 <= n <= 105
16 | 1 <= enqueueTimei, processingTimei <= 109
17 | '''
18 |
19 | class Solution:
20 | def getOrder(self, tasks: List[List[int]]) -> List[int]:
21 | tasks=[ (ent,pt,i) for i,(ent,pt) in enumerate(tasks)]
22 | tasks.sort()
23 | #print(tasks)
24 | heap=[]
25 | #t=tasks[0][0]
26 | i=0
27 | Ans=[]
28 | t=0
29 | while(i int:
35 | A1=[0]*32
36 | A2=[0]*32
37 | for a in arr1:
38 | for i in range(32):
39 | if a&(1< int:
4 | if len(set(candyType)) >= len(candyType)//2:
5 | return len(candyType)//2
6 | else:
7 | return len(set(candyType))
8 |
--------------------------------------------------------------------------------
/Problem code submissions/75. Sort Colors.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def sortColors(self, nums: List[int]) -> None:
3 | """
4 | Do not return anything, modify nums in-place instead.
5 | """
6 | zero, one, two = 0, 0, 0
7 |
8 | #count occourance of 1's 2's 3's
9 | for i in nums:
10 | if i == 0:
11 | zero += 1
12 | elif i == 1:
13 | one += 1
14 | else:
15 | two += 1
16 |
17 | nums[:] = [0]*zero + [1]*one + [2]*two
--------------------------------------------------------------------------------
/Problem code submissions/763. Partition Labels.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def partitionLabels(self, S: str) -> List[int]:
3 | res = []
4 | last_indices = [0] * 26
5 |
6 | for i in range(len(S)):
7 | last_indices[ord(S[i]) - ord('a')] = i
8 |
9 | begin = end = 0
10 | for i in range(len(S)):
11 | end = max(end, last_indices[ord(S[i]) - ord('a')])
12 |
13 | if end == i:
14 | res.append(end - begin + 1)
15 | begin = end + 1
16 |
17 | return res
--------------------------------------------------------------------------------
/Problem code submissions/771. Jewels and Stones.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | # 771. Jewels and Stones
3 | def numJewelsInStones(self, jewels: str, stones: str) -> int:
4 | count = 0
5 | for i in stones:
6 | if i in jewels:
7 | count += 1
8 | return count
--------------------------------------------------------------------------------
/Problem code submissions/884. Uncommon Words from Two Sentences.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #884. Uncommon Words from Two Sentences
3 | def uncommonFromSentences(self, a: str, b: str) -> List[str]:
4 | s1 = a.split(' ') + b.split(' ')
5 | d = {}
6 |
7 | for i in s1:
8 | if i in d:
9 | d[i] += 1
10 | else:
11 | d[i] = 1
12 |
13 | res = []
14 |
15 | for i in d:
16 | if d[i] == 1:
17 | res.append(i)
18 | return res
--------------------------------------------------------------------------------
/Problem code submissions/94. BinaryTreeInorderTraversal.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 | class Solution:
8 | def inorderTraversal(self, root: TreeNode) -> List[int]:
9 | if root is None:
10 | return []
11 |
12 | return self.inorderTraversal(root.left) + [root.val] + self.inorderTraversal(root.right)
13 |
--------------------------------------------------------------------------------
/Problem code submissions/949. Largest Time for Given Digits.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | September Leetcode Challenge Day 1
4 | '''
5 | def largestTimeFromDigits(self, mylist1: List[int]) -> str:
6 | if len(mylist1) == 0:
7 | return ""
8 | mylist1.sort(reverse = True)
9 | arr = list(permutations(mylist1))
10 |
11 | for h1, h2, m1, m2 in arr:
12 | hrs = h1 * 10 + h2
13 | mins = m1 * 10 + m2
14 |
15 | if hrs < 24 and mins < 60:
16 | return "{}{}:{}{}".format(h1, h2, m1, m2)
17 | return ""
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # LeetCode
2 | Competitive coding submissions at Leetcode goes here
3 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D01 LargestTimeforGivenDigits/README.md:
--------------------------------------------------------------------------------
1 | Largest Time for Given Digits
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | You can find a complete step by step explanation walkthrough at my september Leetcode challenge [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 |
13 | Given an array of 4 digits, return the largest 24 hour time that can be made.
14 |
15 | The smallest 24 hour time is 00:00, and the largest is 23:59. Starting from 00:00, a time is larger if more time has elapsed since midnight.
16 |
17 | Return the answer as a string of length 5. If no valid time can be made, return an empty string.
18 |
19 |
20 | ---
21 | Example 1:
22 | ==========================
23 | ```
24 | Input: [1,2,3,4]
25 | Output: "23:41"
26 | ```
27 |
28 | Example 2:
29 | ==========================
30 | ```
31 | Input: [5,5,5,5]
32 | Output: ""
33 | ```
34 |
35 | Note:
36 | ```
37 | A.length == 4
38 | 0 <= A[i] <= 9
39 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D01 LargestTimeforGivenDigits/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D01 LargestTimeforGivenDigits/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D01 LargestTimeforGivenDigits/d1_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: LargestTimeforGivenDigits
4 | Author: Ayushi Rawat
5 | Date: 01-09-2020
6 | '''
7 | def largestTimeFromDigits(self, mylist1: List[int]) -> str:
8 | if len(mylist1) == 0:
9 | return ""
10 | mylist1.sort(reverse = True)
11 | arr = list(permutations(mylist1))
12 |
13 | for h1, h2, m1, m2 in arr:
14 | hrs = h1 * 10 + h2
15 | mins = m1 * 10 + m2
16 |
17 | if hrs < 24 and mins < 60:
18 | return "{}{}:{}{}".format(h1, h2, m1, m2)
19 | return ""
20 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D02 ContainsDuplicateIII/README.md:
--------------------------------------------------------------------------------
1 | Contains Duplicate III
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
13 |
14 | ---
15 | Example 1
16 | ==========================
17 | ```
18 | Input: nums = [1,2,3,1], k = 3, t = 0
19 | Output: true
20 | ```
21 |
22 | Example 2
23 | ==========================
24 | ```
25 | Input: nums = [1,0,1,1], k = 1, t = 2
26 | Output: true
27 | ```
28 |
29 | Example 3
30 | ==========================
31 | ```
32 | Input: nums = [1,5,9,1,5,9], k = 2, t = 3
33 | Output: false
34 | ```
35 | Show Hint #1:
36 | ```
37 | Time complexity O(n logk) - This will give an indication that sorting is involved for k elements.
38 | ```
39 | Show Hint #1:
40 | ```
41 | Use already existing state to evaluate next state - Like, a set of k sorted numbers are only needed to be tracked.
42 | When we are processing the next number in array, then we can utilize the existing sorted state and it is not necessary to sort next
43 | overlapping set of k numbers again.
44 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D02 ContainsDuplicateIII/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D02 ContainsDuplicateIII/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D02 ContainsDuplicateIII/d2_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: ContainsDuplicateIII
4 | Author: Ayushi Rawat
5 | Date: 02-09-2020
6 | '''
7 | def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
8 | if t == 0 and len(nums) == len(set(nums)):
9 | return False
10 | for i in range(len(nums)):
11 | for j in range(i+1, i+k+1,1):
12 | if j < len(nums) and abs(nums[i] - nums[j]) <= t:
13 | return True
14 | return False
--------------------------------------------------------------------------------
/September Leetcode Challenge/D03 RepeatedSubstringPattern/README.md:
--------------------------------------------------------------------------------
1 | Repeated Substring Pattern
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | You can find a complete step by step explanation walkthrough at my september Leetcode challenge [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a non-empty string check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only and its length will not exceed 10000.
13 |
14 | ---
15 | Example 1
16 | ==========================
17 | ```
18 | Input: "abab"
19 | Output: True
20 | Explanation: It's the substring "ab" twice.
21 | ```
22 |
23 | Example 2
24 | ==========================
25 | ```
26 | Input: "aba"
27 | Output: False
28 | ```
29 |
30 | Example 3
31 | ==========================
32 | ```
33 | Input: "abcabcabcabc"
34 | Output: True
35 | Explanation: It's the substring "abc" four times. (And the substring "abcabc" twice.)
36 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D03 RepeatedSubstringPattern/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D03 RepeatedSubstringPattern/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D03 RepeatedSubstringPattern/d3_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: RepeatedSubstringPattern
4 | Author: Ayushi Rawat
5 | Date: 03-09-2020
6 | '''
7 | def repeatedSubstringPattern(self, s: str) -> bool:
8 | sub = ''
9 | l1 = len(s)
10 |
11 | for i in range(l1-1):
12 | sub = sub + s[i]
13 | l2 = len(sub)
14 |
15 | res = sub*(l1//l2)
16 |
17 | if res == s:
18 | return True
19 | return False
--------------------------------------------------------------------------------
/September Leetcode Challenge/D04 Partition Labels/README.md:
--------------------------------------------------------------------------------
1 | Partition Labels
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | A string S of lowercase English letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.
13 |
14 | ---
15 | Example 1
16 | ==========================
17 | ```
18 | Input: S = "ababcbacadefegdehijhklij"
19 | Output: [9,7,8]
20 | Explanation:
21 | The partition is "ababcbaca", "defegde", "hijhklij".
22 | This is a partition so that each letter appears in at most one part.
23 | A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
24 | ```
25 |
26 | Note:
27 | ==========================
28 | ```
29 | S will have length in range [1, 500].
30 | S will consist of lowercase English letters ('a' to 'z') only.
31 | ```
32 |
33 | Hide Hint #1
34 | ==========================
35 | ```
36 | Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
37 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D04 Partition Labels/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D04 Partition Labels/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D04 Partition Labels/d4_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Partition Labels
4 | Author: Ayushi Rawat
5 | Date: 04-09-2020
6 | '''
7 | def partitionLabels(self, S: str) -> List[int]:
8 | res = []
9 | last_indices = [0] * 26
10 |
11 | for i in range(len(S)):
12 | last_indices[ord(S[i]) - ord('a')] = i
13 |
14 | begin = end = 0
15 | for i in range(len(S)):
16 | end = max(end, last_indices[ord(S[i]) - ord('a')])
17 |
18 | if end == i:
19 | res.append(end - begin + 1)
20 | begin = end + 1
21 |
22 | return res
--------------------------------------------------------------------------------
/September Leetcode Challenge/D05 All Elements in Two Binary Search Trees/README.md:
--------------------------------------------------------------------------------
1 | All Elements in Two Binary Search Trees
2 | ==========================
3 |
4 | 
6 |
7 | Explanation Walkthrough:
8 | ==========================
9 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
10 |
11 | Problem Statement:
12 | ==========================
13 | Given two binary search trees root1 and root2.
14 | Return a list containing all the integers from both trees sorted in ascending order.
15 |
16 | ---
17 | Example 1
18 | ==========================
19 | ```
20 | Input: root1 = [2,1,4], root2 = [1,0,3]
21 | Output: [0,1,1,2,3,4]
22 | ```
23 |
24 | Example 2
25 | ==========================
26 | ```
27 | Input: root1 = [0,-10,10], root2 = [5,1,7,0,2]
28 | Output: [-10,0,0,1,2,5,7,10]
29 | ```
30 |
31 | Example 3
32 | ==========================
33 | ```
34 | Input: root1 = [], root2 = [5,1,7,0,2]
35 | Output: [0,1,2,5,7]
36 | ```
37 |
38 | Example 4
39 | ==========================
40 | ```
41 | Input: root1 = [0,-10,10], root2 = []
42 | Output: [-10,0,10]
43 | ```
44 |
45 | Example 5
46 | ==========================
47 | ```
48 | Input: root1 = [1,null,8], root2 = [8,1]
49 | Output: [1,1,8,8]
50 | ```
51 |
52 | Constraints:
53 | ==========================
54 | ```
55 | Each tree has at most 5000 nodes.
56 | Each node's value is between [-10^5, 10^5].
57 | ```
58 |
59 | Hint #1
60 | ==========================
61 | ```
62 | Traverse the first tree in list1 and the second tree in list2.
63 | ```
64 |
65 | Hint #2
66 | ==========================
67 | ```
68 | Merge the two trees in one list and sort it.
69 | ```
70 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D05 All Elements in Two Binary Search Trees/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D05 All Elements in Two Binary Search Trees/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D05 All Elements in Two Binary Search Trees/d5_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: All Elements in Two Binary Search Trees
4 | Author: Ayushi Rawat
5 | Date: 05-09-2020
6 | '''
7 | def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
8 | def traverse(node):
9 | if not node:
10 | return []
11 | return [node.val] + traverse(node.left) + traverse(node.right)
12 |
13 | res = traverse(root1)
14 | res += traverse(root2)
15 | return sorted(res)
--------------------------------------------------------------------------------
/September Leetcode Challenge/D06 Image Overlap/README.md:
--------------------------------------------------------------------------------
1 | Image Overlap
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Two images A and B are given, represented as binary, square matrices of the same size. (A binary matrix has only 0s and 1s as values.)
13 |
14 | We translate one image however we choose (sliding it left, right, up, or down any number of units), and place it on top of the other image. After, the overlap of this translation is the number of positions that have a 1 in both images.
15 |
16 | (Note also that a translation does not include any kind of rotation.)
17 |
18 | What is the largest possible overlap?
19 |
20 | Example 1
21 | ==========================
22 | ```
23 | Input: A = [[1,1,0],
24 | [0,1,0],
25 | [0,1,0]]
26 | B = [[0,0,0],
27 | [0,1,1],
28 | [0,0,1]]
29 | Output: 3
30 | Explanation: We slide A to right by 1 unit and down by 1 unit.
31 | ```
32 |
33 | Note:
34 | ==========================
35 | ```
36 | 1 <= A.length = A[0].length = B.length = B[0].length <= 30
37 | 0 <= A[i][j], B[i][j] <= 1
38 | ```
39 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D06 Image Overlap/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D06 Image Overlap/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D06 Image Overlap/d6_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Image Overlap
4 | Author: Ayushi Rawat
5 | Date: 06-09-2020
6 | '''
7 | def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
8 | d1 = collections.defaultdict(int)
9 | temp1 = []
10 | temp2 = []
11 | for i in range(len(A)):
12 | for j in range(len(A[0])):
13 | if(A[i][j] == 1):
14 | temp1.append((i,j))
15 | if(B[i][j] == 1):
16 | temp2.append((i,j))
17 | res = 0
18 | for a in temp1:
19 | for b in temp2:
20 | c = (b[0]-a[0],b[1]-a[1])
21 | d1[c] += 1
22 | res = max(res, d1[c])
23 | return res
--------------------------------------------------------------------------------
/September Leetcode Challenge/D07 Word Pattern/README.md:
--------------------------------------------------------------------------------
1 | Word Pattern
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a pattern and a string str, find if str follows the same pattern.
13 |
14 | Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str.
15 |
16 | Example 1
17 | ==========================
18 | ```
19 | Input: pattern = "abba", str = "dog cat cat dog"
20 | Output: true
21 |
22 | ```
23 |
24 | Example 2
25 | ==========================
26 | ```
27 | Input:pattern = "abba", str = "dog cat cat fish"
28 | Output: false
29 |
30 | ```
31 |
32 | Example 3
33 | ==========================
34 | ```
35 | Input: pattern = "aaaa", str = "dog cat cat dog"
36 | Output: false
37 |
38 | ```
39 |
40 | Example 4
41 | ==========================
42 | ```
43 | Input: pattern = "abba", str = "dog dog dog dog"
44 | Output: false
45 |
46 | ```
47 |
48 | Note:
49 | ==========================
50 | ```
51 | You may assume pattern contains only lowercase letters, and str contains lowercase letters that may be separated by a single space.
52 | ```
53 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D07 Word Pattern/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D07 Word Pattern/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D07 Word Pattern/d7_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Word Pattern
4 | Author: Ayushi Rawat
5 | Date: 07-09-2020
6 | '''
7 |
8 | def wordPattern(self, pattern: str, str: str) -> bool:
9 | map_char = {}
10 | map_word = {}
11 |
12 | words = str.split(' ')
13 |
14 | if len(words)!= len(pattern):
15 | return False
16 |
17 | for c,w in zip(pattern, words):
18 | if c not in map_char:
19 | if w in map_word:
20 | return False
21 | else:
22 | map_char[c] = w
23 | map_word[w] = c
24 |
25 | else:
26 | if map_char[c] != w:
27 | return False
28 | return True
29 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D08 Sum of Root to Leaf Binary Numbers/README.md:
--------------------------------------------------------------------------------
1 | Sum of Root To Leaf Binary Numbers
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
13 |
14 | For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
15 |
16 | Return the sum of these numbers.
17 |
18 | Example 1
19 | ==========================
20 | 
21 |
22 | ```
23 | Input: [1,0,1,0,1,0,1]
24 | Output: 22
25 | Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
26 |
27 | ```
28 |
29 | Note:
30 | ==========================
31 | ```
32 | The number of nodes in the tree is between 1 and 1000.
33 | node.val is 0 or 1.
34 | The answer will not exceed 2^31 - 1.
35 | ```
36 |
37 | Hint:
38 | ==========================
39 | ```
40 | Find each path, then transform that path to an integer in base 10.
41 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D08 Sum of Root to Leaf Binary Numbers/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D08 Sum of Root to Leaf Binary Numbers/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D08 Sum of Root to Leaf Binary Numbers/d8_solution.py:
--------------------------------------------------------------------------------
1 | # Definition for a binary tree node.
2 | # class TreeNode:
3 | # def __init__(self, val=0, left=None, right=None):
4 | # self.val = val
5 | # self.left = left
6 | # self.right = right
7 |
8 | class Solution:
9 | '''
10 | Problem Name: Sum of Root To Leaf Binary Numbers
11 | Author: Ayushi Rawat
12 | Date: 08-09-2020
13 | '''
14 | def sumRootToLeaf(self, root: TreeNode) -> int:
15 | def preorder(r, cur_number):
16 | nonlocal root_to_leaf
17 | if r:
18 | cur_number = (cur_number << 1) | r.val
19 | # if it's a leaf, update root-to-leaf sum
20 | if not (r.left or r.right):
21 | root_to_leaf += cur_number
22 |
23 | preorder(r.left, cur_number)
24 | preorder(r.right, cur_number)
25 |
26 | root_to_leaf = 0
27 | preorder(root, 0)
28 | return root_to_leaf
29 |
30 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D08 Sum of Root to Leaf Binary Numbers/example_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D08 Sum of Root to Leaf Binary Numbers/example_1.png
--------------------------------------------------------------------------------
/September Leetcode Challenge/D09 Compare Version numbers/README.md:
--------------------------------------------------------------------------------
1 | Compare Version Numbers
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Compare two version numbers version1 and version2.
13 | If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
14 |
15 | You may assume that the version strings are non-empty and contain only digits and the . character.
16 |
17 | The . character does not represent a decimal point and is used to separate number sequences.
18 |
19 | For instance, 2.5 is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
20 |
21 | You may assume the default revision number for each level of a version number to be 0. For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number. Its third and fourth level revision number are both 0.
22 |
23 | Example 1
24 | ==========================
25 |
26 | ```
27 | Input: version1 = "0.1", version2 = "1.1"
28 | Output: -1
29 |
30 | ```
31 |
32 | Example 2
33 | ==========================
34 |
35 | ```
36 | Input: version1 = "1.0.1", version2 = "1"
37 | Output: 1
38 |
39 | ```
40 |
41 | Example 3
42 | ==========================
43 |
44 | ```
45 | Input: version1 = "7.5.2.4", version2 = "7.5.3"
46 | Output: -1
47 |
48 | ```
49 |
50 | Example 4
51 | ==========================
52 |
53 | ```
54 | Input: version1 = "1.01", version2 = "1.001"
55 | Output: 0
56 | Explanation: Ignoring leading zeroes, both “01” and “001" represent the same number “1”
57 |
58 | ```
59 |
60 | Example 5
61 | ==========================
62 |
63 | ```
64 | Input: version1 = "1.0", version2 = "1.0.0"
65 | Output: 0
66 | Explanation: The first version number does not have a third level revision number,
67 | which means its third level revision number is default to "0"
68 |
69 | ```
70 |
71 | Note:
72 | ==========================
73 | ```
74 | Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes.
75 | Version strings do not start or end with dots, and they will not be two consecutive dots.
76 | ```
77 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D09 Compare Version numbers/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D09 Compare Version numbers/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D09 Compare Version numbers/d9_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Compare Version Numbers
4 | Author: Ayushi Rawat
5 | Date: 09-09-2020
6 | '''
7 | def compareVersion(self, version1: str, version2: str) -> int:
8 | v1 = version1.split('.')
9 | v2 = version2.split('.')
10 |
11 | len1 = len(v1)
12 | len2 = len(v2)
13 |
14 | for i in range(max(len1,len2)):
15 | x = int(v1[i]) if iy else -1
20 | return 0
21 |
22 |
23 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D10 Bulls and Cows/README.md:
--------------------------------------------------------------------------------
1 | Bulls and Cows
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | You are playing the following Bulls and Cows game with your friend: You write down a number and ask your friend to guess what the number is. Each time your friend makes a guess, you provide a hint that indicates how many digits in said guess match your secret number exactly in both digit and position (called "bulls") and how many digits match the secret number but locate in the wrong position (called "cows"). Your friend will use successive guesses and hints to eventually derive the secret number.
13 |
14 | Write a function to return a hint according to the secret number and friend's guess, use A to indicate the bulls and B to indicate the cows.
15 |
16 | Please note that both secret number and friend's guess may contain duplicate digits.
17 |
18 | Example 1
19 | ==========================
20 | ```
21 | Input: secret = "1807", guess = "7810"
22 |
23 | Output: "1A3B"
24 |
25 | Explanation: 1 bull and 3 cows. The bull is 8, the cows are 0, 1 and 7.
26 |
27 | ```
28 |
29 | Example 2
30 | ==========================
31 | ```
32 | Input: secret = "1123", guess = "0111"
33 |
34 | Output: "1A1B"
35 |
36 | Explanation: The 1st 1 in friend's guess is a bull, the 2nd or 3rd 1 is a cow.
37 | ```
38 |
39 | Note:
40 | ==========================
41 | ```
42 | You may assume that the secret number and your friend's guess only contain digits, and their lengths are always equal.
43 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D10 Bulls and Cows/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D10 Bulls and Cows/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D10 Bulls and Cows/d10_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Bulls and Cows
4 | Author: Ayushi Rawat
5 | Date: 10-09-2020
6 | '''
7 | def getHint(self, secret: str, guess: str) -> str:
8 | bulls, cows = 0, 0
9 | new_guess = []
10 | new_secret = []
11 |
12 | for i in range(len(secret)):
13 | if secret[i] == guess[i]:
14 | bulls += 1
15 | else:
16 | new_secret.append(secret[i])
17 | new_guess.append(guess[i])
18 | for key in new_guess:
19 | if key in new_secret:
20 | cows += 1
21 | new_secret.remove(key)
22 |
23 | return("{}A{}B".format(bulls, cows))
24 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D11 Maximum Product Subarray/README.md:
--------------------------------------------------------------------------------
1 | Maximum Product Subarray
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
13 |
14 | Example 1
15 | ==========================
16 | ```
17 | Input: [2,3,-2,4]
18 | Output: 6
19 | Explanation: [2,3] has the largest product 6.
20 |
21 | ```
22 |
23 | Example 2
24 | ==========================
25 | ```
26 | Input: [-2,0,-1]
27 | Output: 0
28 | Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
29 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D11 Maximum Product Subarray/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D11 Maximum Product Subarray/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D11 Maximum Product Subarray/d11_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Maximum Product Subarray
4 | Author: Ayushi Rawat
5 | Date: 11-09-2020
6 | '''
7 | def maxProduct(self, nums: List[int]) -> int:
8 | totalmax = nums[0]
9 | currentmin = nums[0]
10 | currentmax = nums[0]
11 | current = nums[0]
12 |
13 | for i in range(1,len(nums)):
14 | current = nums[i]
15 |
16 | currentmaxtemp = max(currentmin*current, currentmax*current, current)
17 | currentmintemp = min(currentmin*current, currentmax*current, current)
18 |
19 | currentmin = currentmintemp
20 | currentmax = currentmaxtemp
21 |
22 | if currentmax > totalmax:
23 | totalmax = currentmax
24 |
25 | return totalmax
--------------------------------------------------------------------------------
/September Leetcode Challenge/D12 Combination Sum III/README.md:
--------------------------------------------------------------------------------
1 | Combination Sum III
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
13 |
14 | Example 1
15 | ==========================
16 | ```
17 | Input: k = 3, n = 7
18 | Output: [[1,2,4]]
19 |
20 | ```
21 |
22 | Example 2
23 | ==========================
24 | ```
25 | Input: k = 3, n = 9
26 | Output: [[1,2,6], [1,3,5], [2,3,4]]
27 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D12 Combination Sum III/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D12 Combination Sum III/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D12 Combination Sum III/d12_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Combination Sum III
4 | Author: Ayushi Rawat
5 | Date: 12-09-2020
6 | '''
7 | def combinationSum3(self, k: int, n: int) -> List[List[int]]:
8 | res = []
9 |
10 | def helper(nums, k, n, index, path, res):
11 | if k < 0 or n < 0:
12 | return
13 | if k == 0 and n == 0:
14 | res.append(path)
15 |
16 | for i in range(index, len(nums)):
17 | helper(nums, k-1, n-nums[i], i+1, path+[nums[i]], res)
18 |
19 | helper(range(1,10), k, n, 0, [], res)
20 |
21 | return res
--------------------------------------------------------------------------------
/September Leetcode Challenge/D13 Insert Interval/README.md:
--------------------------------------------------------------------------------
1 | Insert Interval
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).
13 |
14 | You may assume that the intervals were initially sorted according to their start times.
15 |
16 | Example 1
17 | ==========================
18 | ```
19 | Input: intervals = [[1,3],[6,9]], newInterval = [2,5]
20 | Output: [[1,5],[6,9]]
21 | ```
22 |
23 | Example 2
24 | ==========================
25 | ```
26 | Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8]
27 | Output: [[1,2],[3,10],[12,16]]
28 | Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10].
29 | ```
30 |
31 | NOTE:
32 | ==========================
33 | ```
34 | input types have been changed on April 15, 2019. Please reset to default code definition to get new method signature.
35 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D13 Insert Interval/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D13 Insert Interval/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D13 Insert Interval/d13_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Insert Interval
4 | Author: Ayushi Rawat
5 | Date: 13-09-2020
6 | '''
7 | def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]:
8 | merged = []
9 |
10 | i, start, end = 0, 0, 1
11 |
12 | # Add all intervals that comes before the new Interval
13 | while i < len(intervals) and intervals[i][end] < newInterval[start]:
14 | merged.append(intervals[i])
15 | i += 1
16 |
17 | # Merge all intervals that overlap with new interval
18 | while i < len(intervals) and intervals[i][start] <= newInterval[end]:
19 | newInterval[start] = min(intervals[i][start], newInterval[start])
20 | newInterval[end] = max(intervals[i][end], newInterval[end])
21 | i += 1
22 |
23 | # Insert new interval
24 | merged.append(newInterval)
25 |
26 | # All all remaining intervals to the result
27 | while i < len(intervals):
28 | merged.append(intervals[i])
29 | i += 1
30 |
31 | return merged
32 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D14 House Robbers/README.md:
--------------------------------------------------------------------------------
1 | House Robber
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
13 |
14 | Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.
15 |
16 | Example 1
17 | ==========================
18 | ```
19 | Input: nums = [1,2,3,1]
20 | Output: 4
21 | Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
22 | Total amount you can rob = 1 + 3 = 4.
23 | ```
24 |
25 | Example 2
26 | ==========================
27 | ```
28 | Input: nums = [2,7,9,3,1]
29 | Output: 12
30 | Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
31 | Total amount you can rob = 2 + 9 + 1 = 12.
32 | ```
33 |
34 | Constraints:
35 | ==========================
36 | ```
37 | 0 <= nums.length <= 100
38 | 0 <= nums[i] <= 400
39 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D14 House Robbers/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D14 House Robbers/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D14 House Robbers/d14_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: House Robber
4 | Author: Ayushi Rawat
5 | Date: 14-09-2020
6 | '''
7 | def rob(self, nums: List[int]) -> int:
8 | if not nums:
9 | return 0
10 |
11 | if len(nums) < 3:
12 | return max(nums)
13 |
14 | if (len(nums)> 2):
15 | nums[1] = max(nums[1], nums[0])
16 |
17 | nums[2] = max(nums[2]+nums[0], nums[1])
18 |
19 | return self.rob(nums[1:])
20 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D15 Length of Last Word/README.md:
--------------------------------------------------------------------------------
1 | Length of Last Word
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word (last word means the last appearing word if we loop from left to right) in the string.
13 |
14 | If the last word does not exist, return 0.
15 |
16 | Example 1
17 | ==========================
18 | ```
19 | Input: "Hello World"
20 | Output: 5
21 | ```
22 |
23 | Note:
24 | ==========================
25 | ```
26 | A word is defined as a maximal substring consisting of non-space characters only.
27 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D15 Length of Last Word/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D15 Length of Last Word/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D15 Length of Last Word/d15_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Length of Last Word
4 | Author: Ayushi Rawat
5 | Date: 15-09-2020
6 | '''
7 | def lengthOfLastWord(self, s: str) -> int:
8 | string = s.strip() #remove leading and trailing whitespaces
9 | counter = 0
10 | for i in string[::-1]: #reverse the whole string
11 | if i == ' ':
12 | break
13 | else:
14 | counter += 1
15 | return counter
16 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D16 Maximum XOR of Two Numbers in an Array/README.md:
--------------------------------------------------------------------------------
1 | Maximum XOR of Two Numbers in an Array
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a non-empty array of numbers, a0, a1, a2, … , an-1, where 0 ≤ ai < 231.
13 |
14 | Find the maximum result of ai XOR aj, where 0 ≤ i, j < n.
15 |
16 | Could you do this in O(n) runtime?
17 |
18 | Example 1
19 | ==========================
20 | ```
21 | Input: [3, 10, 5, 25, 2, 8]
22 |
23 | Output: 28
24 |
25 | Explanation: The maximum result is 5 ^ 25 = 28.
26 | ```
27 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D16 Maximum XOR of Two Numbers in an Array/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D16 Maximum XOR of Two Numbers in an Array/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D16 Maximum XOR of Two Numbers in an Array/d16_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Maximum XOR of Two Numbers in an Array
4 | Author: Ayushi Rawat
5 | Date: 16-09-2020
6 | '''
7 | def findMaximumXOR(self, nums: List[int]) -> int:
8 | L = len(bin(max(nums))) - 2
9 |
10 | nums_bits = [[(x>>i) & 1 for i in reversed(range(L))] for x in nums]
11 |
12 | root = {}
13 |
14 | for num, bits in zip(nums, nums_bits):
15 | node = root
16 |
17 | for bit in bits:
18 | node = node.setdefault(bit, {})
19 |
20 | node['#'] = num
21 |
22 | max_xor = 0
23 |
24 | for num, bits in zip(nums, nums_bits):
25 | node = root
26 |
27 | for bit in bits:
28 | toggled_bit = 1 - bit
29 |
30 | if toggled_bit in node:
31 | node = node[toggled_bit]
32 | else:
33 | node = node[bit]
34 |
35 | max_xor = max(max_xor, node['#'] ^ num)
36 | return max_xor
37 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D17 Robot Bounded In Circle/README.md:
--------------------------------------------------------------------------------
1 | Robot Bounded In Circle
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
13 |
14 | "G": go straight 1 unit;
15 | "L": turn 90 degrees to the left;
16 | "R": turn 90 degress to the right.
17 | The robot performs the instructions given in order, and repeats them forever.
18 |
19 | Return true if and only if there exists a circle in the plane such that the robot never leaves the circle.
20 |
21 | Example 1:
22 | ==========================
23 | ```
24 | Input: "GGLLGG"
25 | Output: true
26 | Explanation:
27 | The robot moves from (0,0) to (0,2), turns 180 degrees, and then returns to (0,0).
28 | When repeating these instructions, the robot remains in the circle of radius 2 centered at the origin.
29 | ```
30 |
31 | Example 2:
32 | ==========================
33 | ```
34 | Input: "GG"
35 | Output: false
36 | Explanation:
37 | The robot moves north indefinitely.
38 | ```
39 |
40 | Example 3:
41 | ==========================
42 | ```
43 | Input: "GL"
44 | Output: true
45 | Explanation:
46 | The robot moves from (0, 0) -> (0, 1) -> (-1, 1) -> (-1, 0) -> (0, 0) -> ...
47 | ```
48 |
49 | Note:
50 | ==========================
51 | ```
52 | 1. 1 <= instructions.length <= 100
53 | 2. instructions[i] is in {'G', 'L', 'R'}
54 | ```
55 |
56 | Hint 1:
57 | ==========================
58 | ```
59 | Calculate the final vector of how the robot travels after executing all instructions once - it consists of a change in position plus a change in direction.
60 | ```
61 |
62 | Hint 2:
63 | ==========================
64 | ```
65 | The robot stays in the circle iff (looking at the final vector) it changes direction (ie. doesn't stay pointing north), or it moves 0.
66 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D17 Robot Bounded In Circle/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D17 Robot Bounded In Circle/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D17 Robot Bounded In Circle/d17_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Robot Bounded In Circle
4 | Author: Ayushi Rawat
5 | Date: 17-09-2020
6 | '''
7 | def isRobotBounded(self, instructions: str) -> bool:
8 | di = (0,1)
9 |
10 | x,y = 0,0
11 |
12 | for instruction in instructions:
13 | if instruction == 'G':
14 | x,y = x+di[0],y+di[1]
15 | elif instruction == 'L':
16 | di = (-di[1],di[0])
17 | else:
18 | di = (di[1],-di[0])
19 |
20 | return (x == 0 and y == 0) or di!=(0,1)
--------------------------------------------------------------------------------
/September Leetcode Challenge/D18 Best Time to Buy and Sell Stock/README.md:
--------------------------------------------------------------------------------
1 | Robot Bounded In Circle
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Say you have an array for which the ith element is the price of a given stock on day i.
13 |
14 | If you were only permitted to complete at most one transaction (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
15 |
16 | Note that you cannot sell a stock before you buy one.
17 |
18 | Example 1:
19 | ==========================
20 | ```
21 | Input: [7,1,5,3,6,4]
22 | Output: 5
23 | Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
24 | Not 7-1 = 6, as selling price needs to be larger than buying price.
25 | ```
26 |
27 | Example 2:
28 | ==========================
29 | ```
30 | Input: [7,6,4,3,1]
31 | Output: 0
32 | Explanation: In this case, no transaction is done, i.e. max profit = 0.
33 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D18 Best Time to Buy and Sell Stock/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D18 Best Time to Buy and Sell Stock/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D18 Best Time to Buy and Sell Stock/d18_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Best Time to Buy and Sell Stock
4 | Author: Ayushi Rawat
5 | Date: 18-09-2020
6 | '''
7 | def maxProfit(self, prices: List[int]) -> int:
8 | min_price = float(inf)
9 | max_profit = 0
10 |
11 | for price in prices:
12 | if price < min_price:
13 | min_price = price
14 | else:
15 | temp = price - min_price
16 | max_profit = max(max_profit, temp)
17 | return max_profit
--------------------------------------------------------------------------------
/September Leetcode Challenge/D19 Sequential Digits/README.md:
--------------------------------------------------------------------------------
1 | Sequential Digits
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | An integer has sequential digits if and only if each digit in the number is one more than the previous digit.
13 |
14 | Return a sorted list of all the integers in the range [low, high] inclusive that have sequential digits.
15 |
16 | Example 1:
17 | ==========================
18 | ```
19 | Input: low = 100, high = 300
20 | Output: [123,234]
21 | ```
22 |
23 | Example 2:
24 | ==========================
25 | ```
26 | Input: low = 1000, high = 13000
27 | Output: [1234,2345,3456,4567,5678,6789,12345]
28 | ```
29 |
30 | Constraints:
31 | ==========================
32 | ```
33 | 10 <= low <= high <= 10^9
34 | ```
35 |
36 | Hint 1:
37 | ==========================
38 | ```
39 | Generate all numbers with sequential digits and check if they are in the given range.
40 | ```
41 |
42 | Hint 2:
43 | ==========================
44 | ```
45 | Fix the starting digit then do a recursion that tries to append all valid digits.
46 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D19 Sequential Digits/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D19 Sequential Digits/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D19 Sequential Digits/d19_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Sequential Digits
4 | Author: Ayushi Rawat
5 | Date: 19-09-2020
6 | '''
7 | def sequentialDigits(self, low: int, high: int) -> List[int]:
8 | res = []
9 | for num in range(1,9):
10 | while num <= high:
11 | x = num % 10
12 |
13 | if x == 0:
14 | break
15 |
16 | if num >= low:
17 | res.append(num)
18 |
19 | num = (num * 10) + x + 1
20 |
21 | return sorted(res)
22 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D20 Unique Paths III/README.md:
--------------------------------------------------------------------------------
1 | Unique Paths III
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | On a 2-dimensional grid, there are 4 types of squares:
13 |
14 | 1 represents the starting square. There is exactly one starting square.
15 |
16 | 2 represents the ending square. There is exactly one ending square.
17 |
18 | 0 represents empty squares we can walk over.
19 |
20 | -1 represents obstacles that we cannot walk over.
21 |
22 | Return the number of 4-directional walks from the starting square to the ending square, that walk over every non-obstacle square exactly once
23 |
24 | Example 1:
25 | ==========================
26 | ```
27 | Input: [[1,0,0,0],[0,0,0,0],[0,0,2,-1]]
28 | Output: 2
29 | Explanation: We have the following two paths:
30 | 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2)
31 | 2. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2)
32 | ```
33 |
34 | Example 2:
35 | ==========================
36 | ```
37 | Input: [[1,0,0,0],[0,0,0,0],[0,0,0,2]]
38 | Output: 4
39 | Explanation: We have the following four paths:
40 | 1. (0,0),(0,1),(0,2),(0,3),(1,3),(1,2),(1,1),(1,0),(2,0),(2,1),(2,2),(2,3)
41 | 2. (0,0),(0,1),(1,1),(1,0),(2,0),(2,1),(2,2),(1,2),(0,2),(0,3),(1,3),(2,3)
42 | 3. (0,0),(1,0),(2,0),(2,1),(2,2),(1,2),(1,1),(0,1),(0,2),(0,3),(1,3),(2,3)
43 | 4. (0,0),(1,0),(2,0),(2,1),(1,1),(0,1),(0,2),(0,3),(1,3),(1,2),(2,2),(2,3)
44 | ```
45 |
46 | Note:
47 | ==========================
48 | ```
49 | 1 <= grid.length * grid[0].length <= 20
50 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D20 Unique Paths III/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D20 Unique Paths III/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D20 Unique Paths III/d20_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Unique Paths III
4 | Author: Ayushi Rawat
5 | Date: 20-09-2020
6 | '''
7 | def uniquePathsIII(self, grid: List[List[int]]) -> int:
8 | rows, cols = len(grid), len(grid[0])
9 |
10 | non_obstacles = 0
11 | start_row, start_col = 0, 0
12 | for row in range(0, rows):
13 | for col in range(0, cols):
14 | cell = grid[row][col]
15 | if cell >= 0:
16 | non_obstacles += 1
17 | if cell == 1:
18 | start_row, start_col = row, col
19 |
20 | path_count = 0
21 |
22 | def helper_backtrack(row, col, remain):
23 | nonlocal path_count
24 |
25 | if grid[row][col] == 2 and remain == 1:
26 |
27 | path_count += 1
28 | return
29 |
30 | temp = grid[row][col]
31 | grid[row][col] = -4
32 | remain -= 1
33 |
34 | for ro, co in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
35 | next_row, next_col = row + ro, col + co
36 |
37 | if not (0 <= next_row < rows and 0 <= next_col < cols):
38 |
39 | continue
40 | if grid[next_row][next_col] < 0:
41 |
42 | continue
43 |
44 | helper_backtrack(next_row, next_col, remain)
45 |
46 | grid[row][col] = temp
47 |
48 | helper_backtrack(start_row, start_col, non_obstacles)
49 |
50 | return path_count
51 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D21 Car Pooling/README.md:
--------------------------------------------------------------------------------
1 | Car Pooling
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | You are driving a vehicle that has capacity empty seats initially available for passengers. The vehicle only drives east (ie. it cannot turn around and drive west.)
13 |
14 | Given a list of trips, trip[i] = [num_passengers, start_location, end_location] contains information about the i-th trip: the number of passengers that must be picked up, and the locations to pick them up and drop them off. The locations are given as the number of kilometers due east from your vehicle's initial location.
15 |
16 | Return true if and only if it is possible to pick up and drop off all passengers for all the given trips.
17 |
18 | Example 1:
19 | ==========================
20 | ```
21 | Input: trips = [[2,1,5],[3,3,7]], capacity = 4
22 | Output: false
23 | ```
24 |
25 | Example 2:
26 | ==========================
27 | ```
28 | Input: trips = [[2,1,5],[3,3,7]], capacity = 5
29 | Output: true
30 | ```
31 |
32 | Example 3:
33 | ==========================
34 | ```
35 | Input: trips = [[2,1,5],[3,5,7]], capacity = 3
36 | Output: true
37 | ```
38 |
39 | Example 4:
40 | ==========================
41 | ```
42 | Input: trips = [[3,2,7],[3,7,9],[8,3,9]], capacity = 11
43 | Output: true
44 | ```
45 |
46 | Constraints:
47 | ==========================
48 | ```
49 | trips.length <= 1000
50 |
51 | trips[i].length == 3
52 |
53 | 1 <= trips[i][0] <= 100
54 |
55 | 0 <= trips[i][1] < trips[i][2] <= 1000
56 |
57 | 1 <= capacity <= 100000
58 | ```
59 |
60 | Hint:
61 | ==========================
62 | Sort the pickup and dropoff events by location, then process them in order.
--------------------------------------------------------------------------------
/September Leetcode Challenge/D21 Car Pooling/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D21 Car Pooling/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D21 Car Pooling/d21_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Car Pooling
4 | Author: Ayushi Rawat
5 | Date: 21-09-2020
6 | '''
7 | def carPooling(self, trips: List[List[int]], capacity: int) -> bool:
8 | trip_capacity = collections.defaultdict(int)
9 |
10 | for i in range(len(trips)):
11 | num = trips[i][0]
12 | start = trips[i][1]
13 | dest = trips[i][2]
14 |
15 | for j in range(start,dest):
16 | trip_capacity[j] += num
17 |
18 | if trip_capacity[j] > capacity:
19 | return False
20 | return True
21 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D22 Majority Element II/README.md:
--------------------------------------------------------------------------------
1 | Majority Element II
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times.
13 |
14 | Example 1:
15 | ==========================
16 | ```
17 | Input: [3,2,3]
18 | Output: [3]
19 | ```
20 |
21 | Example 2:
22 | ==========================
23 | ```
24 | Input: [1,1,1,3,3,2,2,2]
25 | Output: [1,2]
26 | ```
27 |
28 | Note:
29 | ==========================
30 | ```
31 | The algorithm should run in linear time and in O(1) space.
32 | ```
33 |
34 | Hint:
35 | ==========================
36 | ```
37 | How many majority elements could it possibly have?
38 | Do you have a better hint? Suggest it!
39 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D22 Majority Element II/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D22 Majority Element II/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D22 Majority Element II/d22_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Majority Element II
4 | Author: Ayushi Rawat
5 | Date: 22-09-2020
6 | '''
7 | def majorityElement(self, nums: List[int]) -> List[int]:
8 | if not nums:
9 | return []
10 |
11 | count1, count2, candidate1, candidate2 = 0, 0, None, None
12 | for n in nums:
13 | if candidate1 == n:
14 | count1 += 1
15 | elif candidate2 == n:
16 | count2 += 1
17 | elif count1 == 0:
18 | candidate1 = n
19 | count1 += 1
20 | elif count2 == 0:
21 | candidate2 = n
22 | count2 += 1
23 | else:
24 | count1 -= 1
25 | count2 -= 1
26 |
27 | res = []
28 | for c in [candidate1, candidate2]:
29 | if nums.count(c) > len(nums)//3:
30 | res.append(c)
31 |
32 | return res
33 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D23 Gas Station/README.md:
--------------------------------------------------------------------------------
1 | Gas Station
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | There are N gas stations along a circular route, where the amount of gas at station i is gas[i].
13 |
14 | You have a car with an unlimited gas tank and it costs cost[i] of gas to travel from station i to its next station (i+1). You begin the journey with an empty tank at one of the gas stations.
15 |
16 | Return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1.
17 |
18 | Example 1:
19 | ==========================
20 | ```
21 | Input:
22 | gas = [1,2,3,4,5]
23 | cost = [3,4,5,1,2]
24 |
25 | Output: 3
26 |
27 | Explanation:
28 | Start at station 3 (index 3) and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
29 |
30 | Travel to station 4. Your tank = 4 - 1 + 5 = 8
31 |
32 | Travel to station 0. Your tank = 8 - 2 + 1 = 7
33 |
34 | Travel to station 1. Your tank = 7 - 3 + 2 = 6
35 |
36 | Travel to station 2. Your tank = 6 - 4 + 3 = 5
37 |
38 | Travel to station 3. The cost is 5. Your gas is just enough to travel back to station 3.
39 |
40 | Therefore, return 3 as the starting index.
41 | ```
42 |
43 | Example 2:
44 | ==========================
45 | ```
46 | Input:
47 | gas = [2,3,4]
48 | cost = [3,4,3]
49 |
50 | Output: -1
51 |
52 | Explanation:
53 | You can't start at station 0 or 1, as there is not enough gas to travel to the next station.
54 | Let's start at station 2 and fill up with 4 unit of gas. Your tank = 0 + 4 = 4
55 | Travel to station 0. Your tank = 4 - 3 + 2 = 3
56 | Travel to station 1. Your tank = 3 - 3 + 3 = 3
57 | You cannot travel back to station 2, as it requires 4 unit of gas but you only have 3.
58 | Therefore, you can't travel around the circuit once no matter where you start.
59 | ```
60 |
61 | Note:
62 | ==========================
63 | ```
64 | If there exists a solution, it is guaranteed to be unique.
65 |
66 | Both input arrays are non-empty and have the same length.
67 |
68 | Each element in the input arrays is a non-negative integer.
69 | ```
70 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D23 Gas Station/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D23 Gas Station/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D23 Gas Station/d23_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Gas Station
4 | Author: Ayushi Rawat
5 | Date: 23-09-2020
6 | '''
7 | def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
8 | tank = 0
9 | index = -1
10 |
11 | cost1 = sum(cost) - sum(gas)
12 | l = len(gas)
13 |
14 | if cost1 > 0:
15 | return -1
16 |
17 | for i in range(l):
18 | temp = tank + gas[i]
19 |
20 | if temp >= cost[i]:
21 | if tank == 0:
22 | index = i
23 |
24 | temp2 = gas[i] - cost[i]
25 | tank += temp2
26 | else:
27 | tank = 0
28 | index = -1
29 |
30 | return index
31 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D24 Find the Difference/README.md:
--------------------------------------------------------------------------------
1 | Gas Station
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given two strings s and t which consist of only lowercase letters.
13 |
14 | String t is generated by random shuffling string s and then add one more letter at a random position.
15 |
16 | Find the letter that was added in t.
17 |
18 | Example 1:
19 | ==========================
20 | ```
21 | Input:
22 | s = "abcd"
23 | t = "abcde"
24 |
25 | Output:
26 | e
27 |
28 | Explanation:
29 | 'e' is the letter that was added.
30 | ```
31 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D24 Find the Difference/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D24 Find the Difference/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D24 Find the Difference/d24_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Find the Difference
4 | Author: Ayushi Rawat
5 | Date: 24-09-2020
6 | '''
7 | def findTheDifference(self, s: str, t: str) -> str:
8 | t = list(t)
9 |
10 | for i in s:
11 | t.remove(i)
12 |
13 | return t[0]
14 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D25 Largest Number/README.md:
--------------------------------------------------------------------------------
1 | Largest Number
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a list of non negative integers, arrange them such that they form the largest number.
13 |
14 | Example 1:
15 | ==========================
16 | ```
17 | Input: [10,2]
18 | Output: "210"
19 | ```
20 |
21 | Example 2:
22 | ==========================
23 | ```
24 | Input: [3,30,34,5,9]
25 | Output: "9534330"
26 | ```
27 |
28 | Note:
29 | ==========================
30 | ```
31 | The result may be very large, so you need to return a string instead of an integer.
32 | ```
33 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D25 Largest Number/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D25 Largest Number/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D25 Largest Number/d25_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Largest Number
4 | Author: Ayushi Rawat
5 | Date: 25-09-2020
6 | '''
7 | def largestNumber(self, nums: List[int]) -> str:
8 | if len(nums) == 0:
9 | return ' '
10 |
11 | for x in range(0, len(nums)-1):
12 | for y in range(x+1, len(nums)):
13 | i = str(nums[x])
14 | j = str(nums[y])
15 |
16 | if int(i + j) < int(j + i):
17 | temp = nums[x]
18 | nums[x] = nums[y]
19 | nums[y] = temp
20 |
21 | if nums[0] == 0:
22 | return '0'
23 |
24 | res = ''
25 | count = 0
26 |
27 | while count < len(nums):
28 | res += str(nums[count])
29 |
30 | count += 1
31 |
32 | return res
33 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D26 Teemo Attacking/README.md:
--------------------------------------------------------------------------------
1 | Teemo Attacking
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | In LOL world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.
13 |
14 | You may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.
15 |
16 | Example 1:
17 | ==========================
18 | ```
19 | Input: [1,4], 2
20 |
21 | Output: 4
22 |
23 | Explanation:
24 |
25 | At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately.
26 | This poisoned status will last 2 seconds until the end of time point 2.
27 | And at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds.
28 | So you finally need to output 4.
29 | ```
30 |
31 | Example 2:
32 | ==========================
33 | ```
34 | Input: [1,2], 2
35 |
36 | Output: 3
37 |
38 | Explanation:
39 |
40 | At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned.
41 | This poisoned status will last 2 seconds until the end of time point 2.
42 | However, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status.
43 | Since the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3.
44 | So you finally need to output 3.
45 | ```
46 |
47 | Note:
48 | ==========================
49 | ```
50 | You may assume the length of given time series array won't exceed 10000.
51 |
52 | You may assume the numbers in the Teemo's attacking time series and his poisoning time duration per attacking are non-negative integers, which won't exceed 10,000,000.
53 | ```
54 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D26 Teemo Attacking/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D26 Teemo Attacking/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D26 Teemo Attacking/d26_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Teemo Attacking
4 | Author: Ayushi Rawat
5 | Date: 26-09-2020
6 | '''
7 | def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
8 | n = len(timeSeries)
9 |
10 | if n==0:
11 | return 0
12 |
13 | total = 0
14 |
15 | for i in range(n-1):
16 | total += min(timeSeries[i+1] - timeSeries[i], duration)
17 |
18 | return total + duration
19 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D27 Evaluate Division/README.md:
--------------------------------------------------------------------------------
1 | Evaluate Division
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | You are given equations in the format A / B = k, where A and B are variables represented as strings, and k is a real number (floating-point number). Given some queries, return the answers. If the answer does not exist, return -1.0.
13 |
14 | The input is always valid. You may assume that evaluating the queries will result in no division by zero and there is no contradiction.
15 |
16 | Example 1:
17 | ==========================
18 | ```
19 | Input: equations = [["a","b"],["b","c"]], values = [2.0,3.0], queries = [["a","c"],["b","a"],["a","e"],["a","a"],["x","x"]]
20 | Output: [6.00000,0.50000,-1.00000,1.00000,-1.00000]
21 | Explanation:
22 | Given: a / b = 2.0, b / c = 3.0
23 | queries are: a / c = ?, b / a = ?, a / e = ?, a / a = ?, x / x = ?
24 | return: [6.0, 0.5, -1.0, 1.0, -1.0 ]
25 | ```
26 |
27 | Example 2:
28 | ==========================
29 | ```
30 | Input: equations = [["a","b"],["b","c"],["bc","cd"]], values = [1.5,2.5,5.0], queries = [["a","c"],["c","b"],["bc","cd"],["cd","bc"]]
31 | Output: [3.75000,0.40000,5.00000,0.20000]
32 | ```
33 |
34 | Example 3:
35 | ==========================
36 | ```
37 | Input: equations = [["a","b"]], values = [0.5], queries = [["a","b"],["b","a"],["a","c"],["x","y"]]
38 | Output: [0.50000,2.00000,-1.00000,-1.00000]
39 | ```
40 |
41 | Note:
42 | ==========================
43 | ```
44 | 1 <= equations.length <= 20
45 | equations[i].length == 2
46 | 1 <= equations[i][0], equations[i][1] <= 5
47 | values.length == equations.length
48 | 0.0 < values[i] <= 20.0
49 | 1 <= queries.length <= 20
50 | queries[i].length == 2
51 | 1 <= queries[i][0], queries[i][1] <= 5
52 | equations[i][0], equations[i][1], queries[i][0], queries[i][1] consist of lower case English letters and digits.
53 | ```
54 |
55 | Hint:
56 | ==========================
57 | ```
58 | Do you recognize this as a graph problem?
59 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D27 Evaluate Division/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D27 Evaluate Division/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D27 Evaluate Division/d27_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Evaluate Division
4 | Author: Ayushi Rawat
5 | Date: 27-09-2020
6 | '''
7 | def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
8 | adj = {}
9 | for i, var in enumerate(equations):
10 | if var[0] not in adj:
11 | adj[var[0]] = []
12 | if var[1] not in adj:
13 | adj[var[1]] = []
14 |
15 | adj[var[0]].append([var[1], values[i]])
16 | adj[var[1]].append([var[0], 1.0/values[i]])
17 |
18 | output = []
19 |
20 | for q in queries:
21 | if (q[0] not in adj) or (q[1] not in adj):
22 | output.append(-1.0)
23 | elif(q[0] == q[1]):
24 | output.append(1.0)
25 | else:
26 | output.append(self.helper(adj, q[0], q[1]))
27 |
28 | return output
29 |
30 | def helper(self, graph, start, end):
31 | queue = [(start, 1.0)]
32 |
33 | seen = set()
34 |
35 | while queue:
36 | curr, val = queue.pop(0)
37 | seen.add(curr)
38 |
39 | if curr == end:
40 | return val
41 |
42 | for neighbor in graph[curr]:
43 | next, weight = neighbor
44 |
45 | if next not in seen:
46 | queue.append((next, val*weight))
47 | return -1.0
--------------------------------------------------------------------------------
/September Leetcode Challenge/D28 Subarray Product Less Than K/README.md:
--------------------------------------------------------------------------------
1 | Subarray Product Less Than K
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Your are given an array of positive integers nums.
13 |
14 | Count and print the number of (contiguous) subarrays where the product of all the elements in the subarray is less than k.
15 |
16 | Example 1:
17 | ==========================
18 | ```
19 | Input: nums = [10, 5, 2, 6], k = 100
20 | Output: 8
21 | Explanation: The 8 subarrays that have product less than 100 are: [10], [5], [2], [6], [10, 5], [5, 2], [2, 6], [5, 2, 6].
22 | Note that [10, 5, 2] is not included as the product of 100 is not strictly less than k.
23 | ```
24 |
25 | Note:
26 | ==========================
27 | ```
28 | 0 < nums.length <= 50000.
29 | 0 < nums[i] < 1000.
30 | 0 <= k < 10^6.
31 | ```
32 |
33 | Hint:
34 | ==========================
35 | ```
36 | For each j, let opt(j) be the smallest i so that nums[i] * nums[i+1] * ... * nums[j] is less than k. opt is an increasing function.
37 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D28 Subarray Product Less Than K/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D28 Subarray Product Less Than K/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D28 Subarray Product Less Than K/d28_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Subarray Product Less Than K
4 | Author: Ayushi Rawat
5 | Date: 28-09-2020
6 | '''
7 | def numSubarrayProductLessThanK(self, nums: List[int], k: int) -> int:
8 | if k <= 1:
9 | return 0
10 |
11 | prod = 1
12 | res = left = 0
13 |
14 | for right, val in enumerate(nums):
15 | prod *= val
16 |
17 | while prod >= k:
18 | prod /= nums[left]
19 |
20 | left += 1
21 |
22 | res += right - left + 1
23 |
24 | return res
--------------------------------------------------------------------------------
/September Leetcode Challenge/D29 Word Break/README.md:
--------------------------------------------------------------------------------
1 | Word Break
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
13 |
14 | Example 1:
15 | ==========================
16 | ```
17 | Input: s = "leetcode", wordDict = ["leet", "code"]
18 | Output: true
19 | Explanation: Return true because "leetcode" can be segmented as "leet code".
20 | ```
21 |
22 | Example 2:
23 | ==========================
24 | ```
25 | Input: s = "applepenapple", wordDict = ["apple", "pen"]
26 | Output: true
27 | Explanation: Return true because "applepenapple" can be segmented as "apple pen apple".
28 | Note that you are allowed to reuse a dictionary word.
29 | ```
30 |
31 | Example 3:
32 | ==========================
33 | ```
34 | Input: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
35 | Output: false
36 | ```
37 |
38 | Note:
39 | ==========================
40 | ```
41 | The same word in the dictionary may be reused multiple times in the segmentation.
42 | You may assume the dictionary does not contain duplicate words.
43 | ```
--------------------------------------------------------------------------------
/September Leetcode Challenge/D29 Word Break/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D29 Word Break/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D29 Word Break/d29_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: Word Break
4 | Author: Ayushi Rawat
5 | Date: 29-09-2020
6 | '''
7 | def wordBreak(self, s: str, wordDict: List[str]) -> bool:
8 | dp = {}
9 |
10 | def helper(s):
11 | if s == "":
12 | return True
13 |
14 | if s in dp:
15 | return dp[s]
16 |
17 | for i in wordDict:
18 | if i == s[:len(i)] and helper(s[len(i):]):
19 | dp[s] = True
20 |
21 | return True
22 | dp[s] = False
23 |
24 | return helper(s)
--------------------------------------------------------------------------------
/September Leetcode Challenge/D30 First Missing Positive/README.md:
--------------------------------------------------------------------------------
1 | First Missing Positive
2 | ==========================
3 |
4 | 
5 |
6 | Explanation Walkthrough:
7 | ==========================
8 | *You can find a complete step by step explanation walkthrough at my september Leetcode challenge* [Youtube Playlist](https://www.youtube.com/playlist?list=PLjaO05BrsbIP4_rYhYjB95q-IpxoIXmlm)
9 |
10 | Problem Statement:
11 | ==========================
12 | Given an unsorted integer array, find the smallest missing positive integer.
13 |
14 | Example 1:
15 | ==========================
16 | ```
17 | Input: [1,2,0]
18 | Output: 3
19 | ```
20 |
21 | Example 2:
22 | ==========================
23 | ```
24 | Input: [3,4,-1,1]
25 | Output: 2
26 | ```
27 |
28 | Example 3:
29 | ==========================
30 | ```
31 | Input: [7,8,9,11,12]
32 | Output: 1
33 | ```
34 |
35 | Follow Up:
36 | ==========================
37 | ```
38 | Your algorithm should run in O(n) time and uses constant extra space.
39 | ```
40 |
41 | Hint 1:
42 | ==========================
43 | ```
44 | Think about how you would solve the problem in non-constant space. Can you apply that logic to the existing space?
45 | ```
46 |
47 | Hint 2:
48 | ==========================
49 | ```
50 | We don't care about duplicates or non-positive integers
51 | ```
52 |
53 | Hint 3:
54 | ==========================
55 | ```
56 | Remember that O(2n) = O(n)
57 | ```
58 |
--------------------------------------------------------------------------------
/September Leetcode Challenge/D30 First Missing Positive/cover.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ayushi7rawat/LeetCode/30c7a1a4d799dd5584e4c23aa1d27f08aa4e0829/September Leetcode Challenge/D30 First Missing Positive/cover.jpg
--------------------------------------------------------------------------------
/September Leetcode Challenge/D30 First Missing Positive/d30_solution.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | '''
3 | Problem Name: First Missing Positive
4 | Author: Ayushi Rawat
5 | Date: 30-09-2020
6 | '''
7 | def firstMissingPositive(self, nums: List[int]) -> int:
8 | #If given list is not empty, we will found maximum number of list.
9 | if nums:
10 | res = max(nums)
11 | #If given list is empty, our first missing positive number will be 1.
12 | else:
13 | return 1
14 | #If maximum number in given list is less than or equal to 0 then our result will be 1.
15 | if res <= 0:
16 | return 1
17 |
18 | #Otherwise we will iterate from 1 to res + 2, if any number will not be present in given list, we return that number.
19 | for i in range(1, res + 2):
20 | if i not in nums:
21 | return i
22 |
23 |
--------------------------------------------------------------------------------
/Weekly contest/Weekly Contest 255/5850. Find Greatest Common Divisor of Array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | #5850. Find Greatest Common Divisor of Array
3 | def findGCD(self, nums: List[int]) -> int:
4 | first = min(nums)
5 | second = max(nums)
6 | res = 1
7 |
8 | for i in range(1, nums[-1]+1):
9 | if first%i == 0 and second%i == 0:
10 | res = i
11 | return res
12 |
--------------------------------------------------------------------------------
/Weekly contest/Weekly contest 237/5734. Check if the Sentence Is Pangram.py:
--------------------------------------------------------------------------------
1 | '''
2 | 5734. Check if the Sentence Is Pangram
3 | Author: Ayushi Rawat
4 |
5 | A pangram is a sentence where every letter of the English alphabet appears at least once.
6 |
7 | Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise.
8 |
9 |
10 |
11 | Example 1:
12 |
13 | Input: sentence = "thequickbrownfoxjumpsoverthelazydog"
14 | Output: true
15 | Explanation: sentence contains at least one of every letter of the English alphabet.
16 | Example 2:
17 |
18 | Input: sentence = "leetcode"
19 | Output: false
20 |
21 |
22 | Constraints:
23 |
24 | 1 <= sentence.length <= 1000
25 | sentence consists of lowercase English letters.
26 | '''
27 |
28 | class Solution:
29 | def checkIfPangram(self, sentence: str) -> bool:
30 | return len(set(sentence)) == 26
31 |
--------------------------------------------------------------------------------
/Weekly contest/Weekly contest 237/5735. Maximum Ice Cream Bars.py:
--------------------------------------------------------------------------------
1 | '''
2 | 5735. Maximum Ice Cream Bars
3 | Author: Ayushi Rawat
4 |
5 | It is a sweltering summer day, and a boy wants to buy some ice cream bars.
6 | At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
7 | Return the maximum number of ice cream bars the boy can buy with coins coins.
8 |
9 | Note: The boy can buy the ice cream bars in any order.
10 |
11 | Example 1:
12 |
13 | Input: costs = [1,3,2,4,1], coins = 7
14 | Output: 4
15 | Explanation: The boy can buy ice cream bars at indices 0,1,2,4 for a total price of 1 + 3 + 2 + 1 = 7.
16 | Example 2:
17 |
18 | Input: costs = [10,6,8,7,7,8], coins = 5
19 | Output: 0
20 | Explanation: The boy cannot afford any of the ice cream bars.
21 | Example 3:
22 |
23 | Input: costs = [1,6,3,1,2,5], coins = 20
24 | Output: 6
25 | Explanation: The boy can buy all the ice cream bars for a total price of 1 + 6 + 3 + 1 + 2 + 5 = 18.
26 |
27 |
28 | Constraints:
29 |
30 | costs.length == n
31 | 1 <= n <= 105
32 | 1 <= costs[i] <= 105
33 | 1 <= coins <= 108
34 | '''
35 |
36 | class Solution:
37 | def maxIceCream(self, costs: List[int], coins: int) -> int:
38 | costs.sort()
39 | a=0
40 | cnt=0
41 | for c in costs:
42 | a+=c
43 | if a<=coins:
44 | cnt+=1
45 | else:
46 | break
47 | return cnt
48 |
49 |
--------------------------------------------------------------------------------
/Weekly contest/Weekly contest 237/5736. Single-Threaded CPU.py:
--------------------------------------------------------------------------------
1 | '''
2 | 5736. Single-Threaded CPU
3 | Author: Ayushi Rawat
4 |
5 | You are given n tasks labeled from 0 to n - 1 represented by a 2D integer array tasks, where tasks[i] = [enqueueTimei, processingTimei] means that the ith task will be available to process at enqueueTimei and will take processingTimei to finish processing.
6 | You have a single-threaded CPU that can process at most one task at a time and will act in the following way:
7 | If the CPU is idle and there are no available tasks to process, the CPU remains idle.
8 | If the CPU is idle and there are available tasks, the CPU will choose the one with the shortest processing time. If multiple tasks have the same shortest processing time, it will choose the task with the smallest index.
9 | Once a task is started, the CPU will process the entire task without stopping.
10 | The CPU can finish a task then start a new one instantly.
11 | Return the order in which the CPU will process the tasks.
12 |
13 | Constraints:
14 | tasks.length == n
15 | 1 <= n <= 105
16 | 1 <= enqueueTimei, processingTimei <= 109
17 | '''
18 |
19 | class Solution:
20 | def getOrder(self, tasks: List[List[int]]) -> List[int]:
21 | tasks=[ (ent,pt,i) for i,(ent,pt) in enumerate(tasks)]
22 | tasks.sort()
23 | #print(tasks)
24 | heap=[]
25 | #t=tasks[0][0]
26 | i=0
27 | Ans=[]
28 | t=0
29 | while(i int:
35 | A1=[0]*32
36 | A2=[0]*32
37 | for a in arr1:
38 | for i in range(32):
39 | if a&(1< int:
26 | res = []
27 | for i in range(len(nums)):
28 | if nums[i] == target:
29 | # if abs(i - start) < res(min):
30 | res.append(abs(i - start))
31 | return min(res)
32 |
33 |
34 | #second solution:
35 | class Solution:
36 | def getMinDistance(self, nums: List[int], target: int, start: int) -> int:
37 | res = sys.maxsize
38 | for i in range(len(nums)):
39 | if nums[i] == target:
40 | res = min(res,(abs(i - start)))
41 | return res
--------------------------------------------------------------------------------
/Weekly contest/Weekly contest 242/1869. Longer Contiguous Segments of Ones than Zeros.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def checkZeroOnes(self, s: str) -> bool:
3 | '''
4 | 1869. Longer Contiguous Segments of Ones than Zeros
5 | By: Ayushi Rawat
6 | '''
7 | count0, count1, temp0, temp1 = 0, 0, 0, 0
8 |
9 | for number in s:
10 | if number == '0':
11 | temp0 += 1
12 | temp1 = 0
13 | else:
14 | temp1 += 1
15 | temp0 = 0
16 | count0 = max(count0, temp0)
17 | count1 = max(count1, temp1)
18 |
19 | return count1 > count0
20 |
--------------------------------------------------------------------------------
/Weekly contest/weekly contest 228/5676. Minimum Changes To Make Alternating Binary String.py:
--------------------------------------------------------------------------------
1 | '''
2 | You are given a string s consisting only of the characters '0' and '1'. In one operation, you can change any '0' to '1' or vice versa.
3 |
4 | The string is called alternating if no two adjacent characters are equal. For example, the string "010" is alternating, while the string "0100" is not.
5 |
6 | Return the minimum number of operations needed to make s alternating.
7 |
8 |
9 |
10 | Example 1:
11 |
12 | Input: s = "0100"
13 | Output: 1
14 | Explanation: If you change the last character to '1', s will be "0101", which is alternating.
15 | Example 2:
16 |
17 | Input: s = "10"
18 | Output: 0
19 | Explanation: s is already alternating.
20 | Example 3:
21 |
22 | Input: s = "1111"
23 | Output: 2
24 | Explanation: You need two operations to reach "0101" or "1010".
25 |
26 |
27 | Constraints:
28 |
29 | 1 <= s.length <= 104
30 | s[i] is either '0' or '1'.
31 | '''
32 |
33 | class Solution:
34 | #5676. Minimum Changes To Make Alternating Binary String
35 | def minOperations(self, s: str) -> int:
36 | ans = 0
37 | for i in range(0, len(s)):
38 | if i % 2 == 0 and s[i] == '1':
39 | ans += 1
40 |
41 | if i % 2 == 1 and s[i] == '0':
42 | ans += 1
43 |
44 | return min(ans, len(s) - ans)
--------------------------------------------------------------------------------
/Weekly contest/weekly contest 228/5677. Count Number of Homogenous Substrings.py:
--------------------------------------------------------------------------------
1 | '''
2 | Given a string s, return the number of homogenous substrings of s. Since the answer may be too large, return it modulo 109 + 7.
3 |
4 | A string is homogenous if all the characters of the string are the same.
5 |
6 | A substring is a contiguous sequence of characters within a string.
7 |
8 |
9 |
10 | Example 1:
11 |
12 | Input: s = "abbcccaa"
13 | Output: 13
14 | Explanation: The homogenous substrings are listed as below:
15 | "a" appears 3 times.
16 | "aa" appears 1 time.
17 | "b" appears 2 times.
18 | "bb" appears 1 time.
19 | "c" appears 3 times.
20 | "cc" appears 2 times.
21 | "ccc" appears 1 time.
22 | 3 + 1 + 2 + 1 + 3 + 2 + 1 = 13.
23 | Example 2:
24 |
25 | Input: s = "xy"
26 | Output: 2
27 | Explanation: The homogenous substrings are "x" and "y".
28 | Example 3:
29 |
30 | Input: s = "zzzzz"
31 | Output: 15
32 |
33 |
34 | Constraints:
35 |
36 | 1 <= s.length <= 105
37 | s consists of lowercase letters.
38 |
39 | '''
40 |
41 |
42 |
43 | class Solution:
44 | #5677. Count Number of Homogenous Substrings
45 | def countHomogenous(self, s: str) -> int:
46 | n = len(s)
47 | count = 1
48 | res = 0
49 | left = 0
50 | right = 1
51 |
52 | while (right < n):
53 | if (s[left] == s[right]):
54 | count += 1
55 | else:
56 | res += count * (count + 1) // 2
57 | left = right
58 | count = 1
59 | right += 1
60 | res += count * (count + 1) // 2
61 | return res%(10**9 + 7)
62 |
--------------------------------------------------------------------------------
/Weekly contest/weekly contest 236/1822. Sign of the Product of an Array.py:
--------------------------------------------------------------------------------
1 | class Solution:
2 | def arraySign(self, nums: List[int]) -> int:
3 | prod = 1
4 |
5 | for i in range(len(nums)):
6 | prod *= nums[i]
7 |
8 | if prod > 0:
9 | return 1
10 | elif prod == 0:
11 | return 0
12 | else:
13 | return -1
14 |
15 |
16 |
17 |
18 | class Solution:
19 | def arraySign(self, nums: List[int]) -> int:
20 | if 0 in nums:
21 | return 0
22 |
23 | count = 0
24 | for i in nums:
25 | if i < 0:
26 | count += 1
27 | return 1 if count%2 == 0 else -1
28 |
--------------------------------------------------------------------------------