diff --git a/challenege-13/number-1-bits.py b/challenege-13/number-1-bits.py new file mode 100644 index 0000000..6ba0f92 --- /dev/null +++ b/challenege-13/number-1-bits.py @@ -0,0 +1,14 @@ +class Solution: + def hammingWeight(self, n: int) -> int: + binn = [] + while n > 0 : + bit = n % 2 + binn.append(str(bit)) + n //=2 + binn.reverse() + s = "".join(binn) + ans = 0 + for i in s: + if i == "1": + ans +=1 + return ans \ No newline at end of file diff --git a/challenege-20/longest-common-subseqence.py b/challenege-20/longest-common-subseqence.py new file mode 100644 index 0000000..6e66fa3 --- /dev/null +++ b/challenege-20/longest-common-subseqence.py @@ -0,0 +1,18 @@ +class Solution: + def longestCommonSubsequence(self, text1: str, text2: str) -> int: + memo = {} + + def dfs(i, j): + if i == len(text1) or j == len(text2): + return 0 + if (i, j) in memo: + return memo[(i, j)] + + if text1[i] == text2[j]: + memo[(i, j)] = 1 + dfs(i + 1, j + 1) + else: + memo[(i, j)] = max(dfs(i + 1, j), dfs(i, j + 1)) + + return memo[(i, j)] + + return dfs(0, 0) \ No newline at end of file diff --git a/challenege-22/combination-sum-IV.py b/challenege-22/combination-sum-IV.py new file mode 100644 index 0000000..c18abb4 --- /dev/null +++ b/challenege-22/combination-sum-IV.py @@ -0,0 +1,10 @@ +class Solution: + def combinationSum4(self, nums: List[int], target: int) -> int: + dp = [0] * (target + 1) + dp[0] = 1 + for currentSum in range(1, target + 1): + for numIndex in range(0, len(nums)): + currentNum = nums[numIndex] + if currentSum - currentNum >= 0: + dp[currentSum] += dp[currentSum - currentNum] + return dp[target] \ No newline at end of file diff --git a/challenege-23/house-robber.py b/challenege-23/house-robber.py new file mode 100644 index 0000000..542b8ef --- /dev/null +++ b/challenege-23/house-robber.py @@ -0,0 +1,19 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + dp = [-1] * (len(nums)+1) + def helper (nums , ind): + if ind == 0: + return nums[0] + if ind < 0: + return 0 + if dp[ind] == -1: + pick = nums[ind] + helper(nums , ind-2) + notPick = 0 + helper(nums,ind-1) + dp[ind] = max(pick ,notPick) + return dp[ind] + return helper(nums,len(nums)-1) + + + + + \ No newline at end of file diff --git a/challenege-24/house-robber-2.py b/challenege-24/house-robber-2.py new file mode 100644 index 0000000..756b965 --- /dev/null +++ b/challenege-24/house-robber-2.py @@ -0,0 +1,11 @@ +class Solution: + def rob(self, nums: List[int]) -> int: + + def helper(ls): + temp , prevMax = 0 , 0 + for n in ls: + newMax = max(temp+n,prevMax) + temp = prevMax + prevMax = newMax + return prevMax + return max(nums[0] , helper(nums[1:]) , helper(nums[:-1])) diff --git a/challenege-27/jump-game.py b/challenege-27/jump-game.py new file mode 100644 index 0000000..9815f96 --- /dev/null +++ b/challenege-27/jump-game.py @@ -0,0 +1,7 @@ +class Solution: + def canJump(self, nums: List[int]) -> bool: + g = len(nums) -1 + for i in range(len(nums)-1,-1,-1): + if i+nums[i] >= g: + g = i + return True if g==0 else False diff --git a/challenege-28/clone-graph.py b/challenege-28/clone-graph.py new file mode 100644 index 0000000..73f4fb6 --- /dev/null +++ b/challenege-28/clone-graph.py @@ -0,0 +1,23 @@ +""" +# Definition for a Node. +class Node: + def __init__(self, val = 0, neighbors = None): + self.val = val + self.neighbors = neighbors if neighbors is not None else [] +""" + +from typing import Optional +class Solution: + def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: + hm = {} + def clone(node): + if node in hm: + return hm[node] + copy = Node(node.val) + hm[node] = copy + for n in node.neighbors: + copy.neighbors.append(clone(n)) + return copy + return clone(node) if node else None + + \ No newline at end of file diff --git a/challenege-31/number-of-islands.py b/challenege-31/number-of-islands.py new file mode 100644 index 0000000..6f0e960 --- /dev/null +++ b/challenege-31/number-of-islands.py @@ -0,0 +1,23 @@ +class Solution: + def numIslands(self, grid: List[List[str]]) -> int: + directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] + ROWS, COLS = len(grid), len(grid[0]) + islands = 0 + + def dfs(r, c): + if (r < 0 or c < 0 or r >= ROWS or + c >= COLS or grid[r][c] == "0" + ): + return + + grid[r][c] = "0" + for dr, dc in directions: + dfs(r + dr, c + dc) + + for r in range(ROWS): + for c in range(COLS): + if grid[r][c] == "1": + dfs(r, c) + islands += 1 + + return islands \ No newline at end of file diff --git a/challenege-32/longest-consective-sequence.java b/challenege-32/longest-consective-sequence.java new file mode 100644 index 0000000..d1b3e78 --- /dev/null +++ b/challenege-32/longest-consective-sequence.java @@ -0,0 +1,20 @@ +import java.util.*; +class Solution { + public int longestConsecutive(int[] nums) { + int l = 0; + HashSet hs = new HashSet(); + for (int n: nums){ + hs.add(n); + } + for (int n :hs){ + if(!hs.contains(n-1)){ + int t = 0; + while (hs.contains(n + t)) { + t++; + } + l = Math.max(t, l); + } + } + return l; + } +} \ No newline at end of file diff --git a/challenege-33/FInd-building-where-alice-and-bob-meet.py b/challenege-33/FInd-building-where-alice-and-bob-meet.py new file mode 100644 index 0000000..0fc5633 --- /dev/null +++ b/challenege-33/FInd-building-where-alice-and-bob-meet.py @@ -0,0 +1,13 @@ +class Solution: + def leftmostBuildingQueries(self, h: List[int], q: List[List[int]]) -> List[int]: + res = [-1] * len(q) + for i,k in enumerate(q): + l,r = sorted(k) + if l == r or h[l] < h[r]: + res[i] = r + continue + for j in range(r+1,len(h)): + if h[j] > max(h[l],h[r]): + res[i] = j + break + return res diff --git a/challenege-38/non-overlapping-intervals.py b/challenege-38/non-overlapping-intervals.py new file mode 100644 index 0000000..156d49b --- /dev/null +++ b/challenege-38/non-overlapping-intervals.py @@ -0,0 +1,14 @@ +class Solution: + def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: + intervals.sort() + + res = 0 + prev = intervals[0][1] + for s,e in intervals[1:]: + if s >= prev: + prev = e + else: + res+=1 + prev = min(prev,e) + return res + \ No newline at end of file diff --git a/challenege-40/meeting-rooms-2.py b/challenege-40/meeting-rooms-2.py new file mode 100644 index 0000000..c46dedb --- /dev/null +++ b/challenege-40/meeting-rooms-2.py @@ -0,0 +1,19 @@ +""" +Definition of Interval: +class Interval(object): + def __init__(self, start, end): + self.start = start + self.end = end +""" + +class Solution: + def minMeetingRooms(self, intervals: List[Interval]) -> int: + intervals.sort(key=lambda x: x.start) + min_heap = [] + + for interval in intervals: + if min_heap and min_heap[0] <= interval.start: + heapq.heappop(min_heap) + heapq.heappush(min_heap, interval.end) + + return len(min_heap) \ No newline at end of file diff --git a/challenege-42/detect-cycle-in-linked-list.java b/challenege-42/detect-cycle-in-linked-list.java new file mode 100644 index 0000000..455c3b8 --- /dev/null +++ b/challenege-42/detect-cycle-in-linked-list.java @@ -0,0 +1,27 @@ +/** + * Definition for singly-linked list. + * class ListNode { + * int val; + * ListNode next; + * ListNode(int x) { + * val = x; + * next = null; + * } + * } + */ +public class Solution { + public boolean hasCycle(ListNode head) { + if(head==null){ + return false; + } + ListNode slow = head, fast = head.next; + while(fast!=null && fast.next!=null){ + if(slow == fast){ + return true; + } + slow = slow.next; + fast = fast.next.next; + } + return false; + } +} \ No newline at end of file diff --git a/challenege-43/merge-two-sorted-list.py b/challenege-43/merge-two-sorted-list.py new file mode 100644 index 0000000..8830025 --- /dev/null +++ b/challenege-43/merge-two-sorted-list.py @@ -0,0 +1,18 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: + if list1 is None: + return list2 + if list2 is None: + return list1 + if list1.val <= list2.val: + list1.next = self.mergeTwoLists(list1.next, list2) + return list1 + else: + list2.next = self.mergeTwoLists(list1, list2.next) + return list2 \ No newline at end of file diff --git a/challenege-45/remove-nth-node-from-end-of-list.py b/challenege-45/remove-nth-node-from-end-of-list.py new file mode 100644 index 0000000..f65c53e --- /dev/null +++ b/challenege-45/remove-nth-node-from-end-of-list.py @@ -0,0 +1,20 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: + nodes = [] + cur = head + while cur: + nodes.append(cur) + cur = cur.next + + removeIndex = len(nodes) - n + if removeIndex == 0: + return head.next + + nodes[removeIndex - 1].next = nodes[removeIndex].next + return head \ No newline at end of file diff --git a/challenege-46/reorder-list.py b/challenege-46/reorder-list.py new file mode 100644 index 0000000..c588e1b --- /dev/null +++ b/challenege-46/reorder-list.py @@ -0,0 +1,27 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def reorderList(self, head: Optional[ListNode]) -> None: + slow, fast = head, head.next + while fast and fast.next: + slow = slow.next + fast = fast.next.next + + second = slow.next + prev = slow.next = None + while second: + tmp = second.next + second.next = prev + prev = second + second = tmp + + first, second = head, prev + while second: + tmp1, tmp2 = first.next, second.next + first.next = second + second.next = tmp1 + first, second = tmp1, tmp2 \ No newline at end of file diff --git a/challenege-47/set-zero.py b/challenege-47/set-zero.py new file mode 100644 index 0000000..26690d9 --- /dev/null +++ b/challenege-47/set-zero.py @@ -0,0 +1,16 @@ +class Solution: + def setZeroes(self, matrix: List[List[int]]) -> None: + ROWS, COLS = len(matrix), len(matrix[0]) + mark = [[matrix[r][c] for c in range(COLS)] for r in range(ROWS)] + + for r in range(ROWS): + for c in range(COLS): + if matrix[r][c] == 0: + for col in range(COLS): + mark[r][col] = 0 + for row in range(ROWS): + mark[row][c] = 0 + + for r in range(ROWS): + for c in range(COLS): + matrix[r][c] = mark[r][c] \ No newline at end of file diff --git a/challenege-48/spiral-matrix.py b/challenege-48/spiral-matrix.py new file mode 100644 index 0000000..9be1a52 --- /dev/null +++ b/challenege-48/spiral-matrix.py @@ -0,0 +1,23 @@ +class Solution: + def spiralOrder(self, matrix: List[List[int]]) -> List[int]: + res = [] + left, right = 0, len(matrix[0]) + top, bottom = 0, len(matrix) + + while left < right and top < bottom: + for i in range(left, right): + res.append(matrix[top][i]) + top += 1 + for i in range(top, bottom): + res.append(matrix[i][right - 1]) + right -= 1 + if not (left < right and top < bottom): + break + for i in range(right - 1, left - 1, -1): + res.append(matrix[bottom - 1][i]) + bottom -= 1 + for i in range(bottom - 1, top - 1, -1): + res.append(matrix[i][left]) + left += 1 + + return res \ No newline at end of file diff --git a/challenege-50/word-search.py b/challenege-50/word-search.py new file mode 100644 index 0000000..480d4fb --- /dev/null +++ b/challenege-50/word-search.py @@ -0,0 +1,25 @@ +class Solution: + def exist(self, board: List[List[str]], word: str) -> bool: + ROWS, COLS = len(board), len(board[0]) + visited = [[False for _ in range(COLS)] for _ in range(ROWS)] + + def dfs(r, c, i): + if i == len(word): + return True + if (r < 0 or c < 0 or r >= ROWS or c >= COLS or + word[i] != board[r][c] or visited[r][c]): + return False + + visited[r][c] = True + res = (dfs(r + 1, c, i + 1) or + dfs(r - 1, c, i + 1) or + dfs(r, c + 1, i + 1) or + dfs(r, c - 1, i + 1)) + visited[r][c] = False + return res + + for r in range(ROWS): + for c in range(COLS): + if dfs(r, c, 0): + return True + return False \ No newline at end of file diff --git a/challenege-51/longest-substring-without-repeating-character.py b/challenege-51/longest-substring-without-repeating-character.py new file mode 100644 index 0000000..b280664 --- /dev/null +++ b/challenege-51/longest-substring-without-repeating-character.py @@ -0,0 +1,12 @@ +class Solution: + def lengthOfLongestSubstring(self, s: str) -> int: + charset = set() + l = 0 + res = 0 + for r in range(len(s)): + while s[r] in charset: + charset.remove(s[l]) + l+=1 + charset.add(s[r]) + res = max(res, r-l + 1) + return res \ No newline at end of file diff --git a/challenege-52/longest-repeating-char-replacement.py b/challenege-52/longest-repeating-char-replacement.py new file mode 100644 index 0000000..002406f --- /dev/null +++ b/challenege-52/longest-repeating-char-replacement.py @@ -0,0 +1,13 @@ +class Solution: + def characterReplacement(self, s: str, k: int) -> int: + count = {} + l= 0 + res = 0 + for r in range(len(s)): + count[s[r]] = 1 + count.get(s[r],0) + while (r-l+1) - max(count.values()) > k: + count[s[l]] -= 1 + l+=1 + res = max(res,r-l+1) + return res + \ No newline at end of file diff --git a/challenege-54/valid-anagram.py b/challenege-54/valid-anagram.py new file mode 100644 index 0000000..cd32ca9 --- /dev/null +++ b/challenege-54/valid-anagram.py @@ -0,0 +1,11 @@ +class Solution: + def isAnagram(self, s: str, t: str) -> bool: + if len(s) != len(t): + return False + countS = {} + countT = {} + for i in range(len(s)): + countS[s[i]] = 1 + countS.get(s[i],0) + countT[t[i]] = 1 + countT.get(t[i],0) + return countS == countT + \ No newline at end of file diff --git a/challenege-57/valid-palindrome.py b/challenege-57/valid-palindrome.py new file mode 100644 index 0000000..00fa3f8 --- /dev/null +++ b/challenege-57/valid-palindrome.py @@ -0,0 +1,16 @@ +class Solution: + def isPalindrome(self, s: str) -> bool: + l,r=0,len(s)-1 + while l l and not self.alphaNum(s[r]): + r -= 1 + if s[l].lower() != s[r].lower(): + return False + l, r = l + 1, r - 1 + return True + def alphaNum(self, c): + return (ord('A') <= ord(c) <= ord('Z') or + ord('a') <= ord(c) <= ord('z') or + ord('0') <= ord(c) <= ord('9')) \ No newline at end of file diff --git a/challenege-58/longest-palindrome-substring.py b/challenege-58/longest-palindrome-substring.py new file mode 100644 index 0000000..5852deb --- /dev/null +++ b/challenege-58/longest-palindrome-substring.py @@ -0,0 +1,16 @@ +class Solution: + def longestPalindrome(self, s: str) -> str: + resIdx, resLen = 0, 0 + n = len(s) + + dp = [[False] * n for _ in range(n)] + + for i in range(n - 1, -1, -1): + for j in range(i, n): + if s[i] == s[j] and (j - i <= 2 or dp[i + 1][j - 1]): + dp[i][j] = True + if resLen < (j - i + 1): + resIdx = i + resLen = j - i + 1 + + return s[resIdx : resIdx + resLen] \ No newline at end of file diff --git a/challenege-59/palindromic-substring.py b/challenege-59/palindromic-substring.py new file mode 100644 index 0000000..bc6b0d4 --- /dev/null +++ b/challenege-59/palindromic-substring.py @@ -0,0 +1,12 @@ +class Solution: + def countSubstrings(self, s: str) -> int: + n, res = len(s), 0 + dp = [[False] * n for _ in range(n)] + + for i in range(n - 1, -1, -1): + for j in range(i, n): + if s[i] == s[j] and (j - i <= 2 or dp[i + 1][j - 1]): + dp[i][j] = True + res += 1 + + return res \ No newline at end of file diff --git a/challenege-60/encode-and-decode-string.py b/challenege-60/encode-and-decode-string.py new file mode 100644 index 0000000..1e266a1 --- /dev/null +++ b/challenege-60/encode-and-decode-string.py @@ -0,0 +1,22 @@ +class Solution: + + def encode(self, strs: List[str]) -> str: + ans = '' + for i in strs: + l = len(i) + ans += (str(l)+"#"+str(i)) + return ans + def decode(self, s: str) -> List[str]: + ls = [] + i = 0 + while i < len(s): + l = 0 + while s[i] != '#': + l = (l*10) +int(s[i]) + i+=1 + i+=1 + print(s[i: (i+l)]) + ls.append(s[i: (i+l)]) + i = i+l + return ls + diff --git a/challenege-61/max-depth-bin-tree.py b/challenege-61/max-depth-bin-tree.py new file mode 100644 index 0000000..80947b4 --- /dev/null +++ b/challenege-61/max-depth-bin-tree.py @@ -0,0 +1,23 @@ +# Definition for a binary tree node. +# class TreeNode: +# def __init__(self, val=0, left=None, right=None): +# self.val = val +# self.left = left +# self.right = right + +class Solution: + def maxDepth(self, root: Optional[TreeNode]) -> int: + q = deque() + if root: + q.append(root) + + level = 0 + while q: + for i in range(len(q)): + node = q.popleft() + if node.left: + q.append(node.left) + if node.right: + q.append(node.right) + level += 1 + return level \ No newline at end of file diff --git a/challenge-1/readme.md b/challenge-1/readme.md new file mode 100644 index 0000000..a0f0255 --- /dev/null +++ b/challenge-1/readme.md @@ -0,0 +1,4 @@ +arjun a chandran +arjun43250@gmail.com + +https://docs.google.com/spreadsheets/d/17S7OZYJUf5Sm7HgbGBgq5Fc0sIC8_A0kymL4ijSYbCQ/edit \ No newline at end of file diff --git a/challenge-10/search-in-rotated-array.py b/challenge-10/search-in-rotated-array.py new file mode 100644 index 0000000..9120610 --- /dev/null +++ b/challenge-10/search-in-rotated-array.py @@ -0,0 +1,29 @@ +class Solution: + def search(self, nums: List[int], target: int) -> int: + l, r = 0, len(nums) - 1 + + while l < r: + m = (l + r) // 2 + if nums[m] > nums[r]: + l = m + 1 + else: + r = m + + pivot = l + + def binary_search(left: int, right: int) -> int: + while left <= right: + mid = (left + right) // 2 + if nums[mid] == target: + return mid + elif nums[mid] < target: + left = mid + 1 + else: + right = mid - 1 + return -1 + + result = binary_search(0, pivot - 1) + if result != -1: + return result + + return binary_search(pivot, len(nums) - 1) \ No newline at end of file diff --git a/challenge-11/3sum.py b/challenge-11/3sum.py new file mode 100644 index 0000000..e4d726c --- /dev/null +++ b/challenge-11/3sum.py @@ -0,0 +1,24 @@ +class Solution: + def threeSum(self, nums: List[int]) -> List[List[int]]: + nums.sort() + count = defaultdict(int) + for num in nums: + count[num] += 1 + + res = [] + for i in range(len(nums)): + count[nums[i]] -= 1 + if i and nums[i] == nums[i - 1]: + continue + + for j in range(i + 1, len(nums)): + count[nums[j]] -= 1 + if j - 1 > i and nums[j] == nums[j - 1]: + continue + target = -(nums[i] + nums[j]) + if count[target] > 0: + res.append([nums[i], nums[j], target]) + + for j in range(i + 1, len(nums)): + count[nums[j]] += 1 + return res \ No newline at end of file diff --git a/challenge-12/contains-most-water.py b/challenge-12/contains-most-water.py new file mode 100644 index 0000000..8d81426 --- /dev/null +++ b/challenge-12/contains-most-water.py @@ -0,0 +1,12 @@ +class Solution: + def maxArea(self, h: List[int]) -> int: + l,r = 0,len(h)-1 + ma = 0 + while l List[int]: + ans = [0] * (n+1) + for i in range(n+1): + ans[i] = self.c(i) + return ans + def c(self , n:int) -> int: + res = 0 + while n > 0: + res += n&1 + n = n>>1 + return res \ No newline at end of file diff --git a/challenge-15/missing-number.py b/challenge-15/missing-number.py new file mode 100644 index 0000000..388a101 --- /dev/null +++ b/challenge-15/missing-number.py @@ -0,0 +1,8 @@ +class Solution: + def missingNumber(self, nums: List[int]) -> int: + s = set(nums) + for i in range(len(nums)): + if i not in s: + return i + return len(nums) + \ No newline at end of file diff --git a/challenge-16/reverse-bits.py b/challenge-16/reverse-bits.py new file mode 100644 index 0000000..13db012 --- /dev/null +++ b/challenge-16/reverse-bits.py @@ -0,0 +1,7 @@ +class Solution: + def reverseBits(self, n: int) -> int: + res = 0 + for i in range(32): + bit = (n >> i) & 1 + res += (bit << (31 - i)) + return res \ No newline at end of file diff --git a/challenge-17/climbing-stairs.py b/challenge-17/climbing-stairs.py new file mode 100644 index 0000000..3c5d497 --- /dev/null +++ b/challenge-17/climbing-stairs.py @@ -0,0 +1,11 @@ +class Solution: + def climbStairs(self, n: int) -> int: + cache = [-1] * n + def dfs(i): + if i >= n: + return i == n + if cache[i] != -1: + return cache[i] + cache[i] = dfs(i+1) + dfs(i+2) + return cache[i] + return dfs(0) \ No newline at end of file diff --git a/challenge-18/coin-change.py b/challenge-18/coin-change.py new file mode 100644 index 0000000..0752ebc --- /dev/null +++ b/challenge-18/coin-change.py @@ -0,0 +1,10 @@ +class Solution: + def coinChange(self, coins: List[int], amount: int) -> int: + dp = [amount + 1] * (amount + 1) + dp[0] = 0 + + for a in range(1, amount + 1): + for c in coins: + if a - c >= 0: + dp[a] = min(dp[a], 1 + dp[a - c]) + return dp[amount] if dp[amount] != amount + 1 else -1 \ No newline at end of file diff --git a/challenge-19/longest-increasing-subseqence.py b/challenge-19/longest-increasing-subseqence.py new file mode 100644 index 0000000..243969e --- /dev/null +++ b/challenge-19/longest-increasing-subseqence.py @@ -0,0 +1,15 @@ +class Solution: + def lengthOfLIS(self, nums): + n = len(nums) + dp = [[0] * (n + 1) for _ in range(n + 1)] + + for i in range(n - 1, -1, -1): + for j in range(i - 1, -2, -1): + LIS = dp[i + 1][j + 1] + + if j == -1 or nums[j] < nums[i]: + LIS = max(LIS, 1 + dp[i + 1][i + 1]) + + dp[i][j + 1] = LIS + + return dp[0][0] \ No newline at end of file diff --git a/challenge-2/twosum.py b/challenge-2/twosum.py new file mode 100644 index 0000000..d119b72 --- /dev/null +++ b/challenge-2/twosum.py @@ -0,0 +1,12 @@ +ls = list(map(int,input().split())) +t = int(input()) + + +#using hashmap + +hm = {} +for i,n in enumerate(ls): + if (t-n) in hm: + print ([hm[t-n],i]) + else: + hm[n] = i diff --git a/challenge-21/work-break.py b/challenge-21/work-break.py new file mode 100644 index 0000000..781c612 --- /dev/null +++ b/challenge-21/work-break.py @@ -0,0 +1,15 @@ +class Solution: + def wordBreak(self, s: str, wordDict: List[str]) -> bool: + wordSet = set(wordDict) + + def dfs(i): + if i == len(s): + return True + + for j in range(i, len(s)): + if s[i : j + 1] in wordSet: + if dfs(j + 1): + return True + return False + + return dfs(0) \ No newline at end of file diff --git a/challenge-25/decodeWays.py b/challenge-25/decodeWays.py new file mode 100644 index 0000000..b3add58 --- /dev/null +++ b/challenge-25/decodeWays.py @@ -0,0 +1,20 @@ +class Solution: + def numDecodings(self, s: str) -> int: + dp = {len(s) : 1} + + def dfs(i): + if i in dp: + return dp[i] + if s[i] == "0": + return 0 + + res = dfs(i + 1) + if i + 1 < len(s) and ( + s[i] == "1" or s[i] == "2" and + s[i + 1] in "0123456" + ): + res += dfs(i + 2) + dp[i] = res + return res + + return dfs(0) \ No newline at end of file diff --git a/challenge-29/course-shedule.py b/challenge-29/course-shedule.py new file mode 100644 index 0000000..d6fe70e --- /dev/null +++ b/challenge-29/course-shedule.py @@ -0,0 +1,23 @@ +class Solution: + def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool: + preM = {i : [] for i in range(numCourses)} + for crs,pre in prerequisites: + preM[crs].append(pre) + + visited = set() + def dfs(crs): + if crs in visited: + return False + if preM[crs] == []: + return True + visited.add(crs) + for pre in preM[crs]: + if not dfs(pre): + return False + visited.remove(crs) + preM[crs] = [] + return True + for c in range(numCourses): + if not dfs(c): + return False + return True \ No newline at end of file diff --git a/challenge-3/best-time-to-buy-and-sell-stock.py b/challenge-3/best-time-to-buy-and-sell-stock.py new file mode 100644 index 0000000..2fcf205 --- /dev/null +++ b/challenge-3/best-time-to-buy-and-sell-stock.py @@ -0,0 +1,15 @@ +stocks = list(map(int,intpu().split())) + +# using sliding window +l = 0 +r = 1 +ans = 0 + +while r < len(stocks): + if stocks[l] < stocks[r] : + if ans < stocks[r] - stocks[l]: + ans = stocks[r] - stocks[l] + else: + l = r + r+=1 +print (ans) \ No newline at end of file diff --git a/challenge-30/atlantic-pacific.py b/challenge-30/atlantic-pacific.py new file mode 100644 index 0000000..ba2fa60 --- /dev/null +++ b/challenge-30/atlantic-pacific.py @@ -0,0 +1,39 @@ +class Solution: + def pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: + ROWS, COLS = len(heights), len(heights[0]) + directions = [(1, 0), (-1, 0), (0, 1), (0, -1)] + pac = [[False] * COLS for _ in range(ROWS)] + atl = [[False] * COLS for _ in range(ROWS)] + + def bfs(source, ocean): + q = deque(source) + while q: + r, c = q.popleft() + ocean[r][c] = True + for dr, dc in directions: + nr, nc = r + dr, c + dc + if (0 <= nr < ROWS and 0 <= nc < COLS and + not ocean[nr][nc] and + heights[nr][nc] >= heights[r][c] + ): + q.append((nr, nc)) + + pacific = [] + atlantic = [] + for c in range(COLS): + pacific.append((0, c)) + atlantic.append((ROWS - 1, c)) + + for r in range(ROWS): + pacific.append((r, 0)) + atlantic.append((r, COLS - 1)) + + bfs(pacific, pac) + bfs(atlantic, atl) + + res = [] + for r in range(ROWS): + for c in range(COLS): + if pac[r][c] and atl[r][c]: + res.append([r, c]) + return res \ No newline at end of file diff --git a/challenge-34/maximum-star-sum-of-graph.py b/challenge-34/maximum-star-sum-of-graph.py new file mode 100644 index 0000000..58cf392 --- /dev/null +++ b/challenge-34/maximum-star-sum-of-graph.py @@ -0,0 +1,15 @@ +class Solution: + def maxStarSum(self, vals: List[int], edges: List[List[int]], k: int) -> int: + graph = defaultdict(set) + for i,j in edges: + if vals[i] > 0 : graph[j].add(i) + if vals[j] > 0 : graph[i].add(j) + + stars = [] + for i,v in enumerate(vals): + vv = [vals[j] for j in graph[i]] + vv.sort(reverse=True) + stars.append(v + sum(vv[0:k])) + + return max(stars) + \ No newline at end of file diff --git a/challenge-35/Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph.py b/challenge-35/Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph.py new file mode 100644 index 0000000..31df20d --- /dev/null +++ b/challenge-35/Count-Unreachable-Pairs-of-Nodes-in-an-Undirected-Graph.py @@ -0,0 +1,34 @@ +class UnionFind: + def __init__(self, size): + self.root = [i for i in range(size)] + self.rank = [1] * size + + def find(self, node): + if node != self.root[node]: + self.root[node] = self.find(self.root[node]) + return self.root[node] + + def union(self, node1, node2): + root1 = self.find(node1) + root2 = self.find(node2) + if root1 != root2: + if self.rank[root1] > self.rank[root2]: + self.root[root2] = root1 + elif self.rank[root1] < self.rank[root2]: + self.root[root1] = root2 + else: + self.root[root2] = root1 + self.rank[root1] += 1 + +class Solution: + def countPairs(self, n: int, edges: List[List[int]]) -> int: + uf = UnionFind(n) + for node1, node2 in edges: + uf.union(node1 - 1, node2 - 1) + group_sizes = list(Counter([uf.find(i) for i in range(n)]).values()) + ans = 0 + first_group_size = group_sizes[0] + for i in range(1, len(group_sizes)): + ans += first_group_size * group_sizes[i] + first_group_size += group_sizes[i] + return ans \ No newline at end of file diff --git a/challenge-36/insert-interval.py b/challenge-36/insert-interval.py new file mode 100644 index 0000000..79c6c01 --- /dev/null +++ b/challenge-36/insert-interval.py @@ -0,0 +1,21 @@ +class Solution: + def insert(self, intervals: List[List[int]], newInterval: List[int]) -> List[List[int]]: + n = len(intervals) + i = 0 + res = [] + + while i < n and intervals[i][1] < newInterval[0]: + res.append(intervals[i]) + i += 1 + + while i < n and newInterval[1] >= intervals[i][0]: + newInterval[0] = min(newInterval[0], intervals[i][0]) + newInterval[1] = max(newInterval[1], intervals[i][1]) + i += 1 + res.append(newInterval) + + while i < n: + res.append(intervals[i]) + i += 1 + + return res \ No newline at end of file diff --git a/challenge-37/merge-interval.py b/challenge-37/merge-interval.py new file mode 100644 index 0000000..b4da019 --- /dev/null +++ b/challenge-37/merge-interval.py @@ -0,0 +1,13 @@ +class Solution: + def merge(self, intervals: List[List[int]]) -> List[List[int]]: + intervals.sort(key=lambda pair: pair[0]) + output = [intervals[0]] + + for start, end in intervals: + lastEnd = output[-1][1] + + if start <= lastEnd: + output[-1][1] = max(lastEnd, end) + else: + output.append([start, end]) + return output \ No newline at end of file diff --git a/challenge-4/contains-duplicate.py b/challenge-4/contains-duplicate.py new file mode 100644 index 0000000..a6fb1ae --- /dev/null +++ b/challenge-4/contains-duplicate.py @@ -0,0 +1,10 @@ +list = list(map(int,input().split())) + +hs= set() +for i,val in enumerate(list): + if val in hs: + print(True) + else: + hs.add(val) + +print(False) diff --git a/challenge-41/reverse-linkedlist.py b/challenge-41/reverse-linkedlist.py new file mode 100644 index 0000000..36dbc78 --- /dev/null +++ b/challenge-41/reverse-linkedlist.py @@ -0,0 +1,22 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next +class Solution: + def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]: + ls = [] + temp = head + while temp: + ls.append(temp.val) + temp = temp.next + temp = head + n = len(ls)-1 + while temp: + temp.val = ls[n] + n-=1 + temp = temp.next + return head + + + \ No newline at end of file diff --git a/challenge-44/merge-k-sorted-list.py b/challenge-44/merge-k-sorted-list.py new file mode 100644 index 0000000..cf9a1b7 --- /dev/null +++ b/challenge-44/merge-k-sorted-list.py @@ -0,0 +1,21 @@ +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, val=0, next=None): +# self.val = val +# self.next = next + +class Solution: + def mergeKLists(self, lists: List[Optional[ListNode]]) -> Optional[ListNode]: + nodes = [] + for lst in lists: + while lst: + nodes.append(lst.val) + lst = lst.next + nodes.sort() + + res = ListNode(0) + cur = res + for node in nodes: + cur.next = ListNode(node) + cur = cur.next + return res.next \ No newline at end of file diff --git a/challenge-49/rotate-image.py b/challenge-49/rotate-image.py new file mode 100644 index 0000000..afcba1e --- /dev/null +++ b/challenge-49/rotate-image.py @@ -0,0 +1,12 @@ +class Solution: + def rotate(self, matrix: List[List[int]]) -> None: + n = len(matrix) + rotated = [[0] * n for _ in range(n)] + + for i in range(n): + for j in range(n): + rotated[j][n - 1 - i] = matrix[i][j] + + for i in range(n): + for j in range(n): + matrix[i][j] = rotated[i][j] \ No newline at end of file diff --git a/challenge-5/sum-of-two-integer.java b/challenge-5/sum-of-two-integer.java new file mode 100644 index 0000000..d6f55d7 --- /dev/null +++ b/challenge-5/sum-of-two-integer.java @@ -0,0 +1,14 @@ +import java.util.*; +public class Main{ + public static void main(String args[]){ + Scanner in = new Scanner(System.in); + int a = in.nextInt(); + int b = in.nextInt(); + while (b != 0){ + int t = (a&b)<<1; + a = a^b; + b = t + } + System.out.println(b); + } +} \ No newline at end of file diff --git a/challenge-53/minimum-string-window.py b/challenge-53/minimum-string-window.py new file mode 100644 index 0000000..8ba7d86 --- /dev/null +++ b/challenge-53/minimum-string-window.py @@ -0,0 +1,30 @@ +class Solution: + def minWindow(self, s: str, t: str) -> str: + if t == "": + return "" + + countT, window = {}, {} + for c in t: + countT[c] = 1 + countT.get(c, 0) + + have, need = 0, len(countT) + res, resLen = [-1, -1], float("infinity") + l = 0 + for r in range(len(s)): + c = s[r] + window[c] = 1 + window.get(c, 0) + + if c in countT and window[c] == countT[c]: + have += 1 + + while have == need: + if (r - l + 1) < resLen: + res = [l, r] + resLen = r - l + 1 + + window[s[l]] -= 1 + if s[l] in countT and window[s[l]] < countT[s[l]]: + have -= 1 + l += 1 + l, r = res + return s[l : r + 1] if resLen != float("infinity") else "" \ No newline at end of file diff --git a/challenge-55/group-anagram.py b/challenge-55/group-anagram.py new file mode 100644 index 0000000..6c290c1 --- /dev/null +++ b/challenge-55/group-anagram.py @@ -0,0 +1,18 @@ +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + hm = { + ")" : "(", + "]" : "[", + "}" : "{", + } + for c in s: + if c in hm: + if stack and stack[-1] == hm[c]: + stack.pop() + else: + return False + else: + stack.append(c) + return True if not stack else False + \ No newline at end of file diff --git a/challenge-56/valid-paranthesis.py b/challenge-56/valid-paranthesis.py new file mode 100644 index 0000000..6c290c1 --- /dev/null +++ b/challenge-56/valid-paranthesis.py @@ -0,0 +1,18 @@ +class Solution: + def isValid(self, s: str) -> bool: + stack = [] + hm = { + ")" : "(", + "]" : "[", + "}" : "{", + } + for c in s: + if c in hm: + if stack and stack[-1] == hm[c]: + stack.pop() + else: + return False + else: + stack.append(c) + return True if not stack else False + \ No newline at end of file diff --git a/challenge-6/products-of-array-execpt-self.py b/challenge-6/products-of-array-execpt-self.py new file mode 100644 index 0000000..9f3749b --- /dev/null +++ b/challenge-6/products-of-array-execpt-self.py @@ -0,0 +1,16 @@ +ls = list(map(int,input().split())) + +n = len(ls) + +pre = [1] *n +pos = [1] *n + +pre[0] = pos[n-1] = 1 + +for i in range(1,n): + pre[i] = ls[i-1] * pre[i-1] +for i in range(n-2,-1,-1): + pos[i] = ls[i+1] * pos[i+1] +for i in range(n): + ls[i] = pre[i] * pos[i] +print(ls) \ No newline at end of file diff --git a/challenge-7/max-sum-array.py b/challenge-7/max-sum-array.py new file mode 100644 index 0000000..4d66cf8 --- /dev/null +++ b/challenge-7/max-sum-array.py @@ -0,0 +1,9 @@ +class Solution: + def maxSubArray(self, nums: List[int]) -> int: + res = nums[0] + for i in range(len(nums)): + currmax = 0 + for j in range(i,len(nums)): + currmax += nums[j] + res = max(currmax,res) + return res \ No newline at end of file diff --git a/challenge-8/max-product-array.py b/challenge-8/max-product-array.py new file mode 100644 index 0000000..84e7470 --- /dev/null +++ b/challenge-8/max-product-array.py @@ -0,0 +1,19 @@ +class Solution: + def maxProduct(self, nums: List[int]) -> int: + res = nums[0] + curMin, curMax = 1, 1 + + for num in nums: + tmp = curMax * num + curMax = max(num * curMax, num * curMin, num) + curMin = min(tmp, num * curMin, num) + res = max(res, curMax) + return res + + + + + + + + \ No newline at end of file diff --git a/challenge-9/min-rotated-sorted-array.py b/challenge-9/min-rotated-sorted-array.py new file mode 100644 index 0000000..a30a65a --- /dev/null +++ b/challenge-9/min-rotated-sorted-array.py @@ -0,0 +1,10 @@ +class Solution: + def findMin(self, nums: List[int]) -> int: + l, r = 0, len(nums) - 1 + while l < r: + m = l + (r - l) // 2 + if nums[m] < nums[r]: + r = m + else: + l = m + 1 + return nums[l] \ No newline at end of file diff --git a/chellenege-26/uniqurePath.py b/chellenege-26/uniqurePath.py new file mode 100644 index 0000000..3317515 --- /dev/null +++ b/chellenege-26/uniqurePath.py @@ -0,0 +1,18 @@ +class Solution: + def uniquePaths(self, m: int, n: int) -> int: + dp = [[-1 for _ in range(n)] for _ in range(m)] + def helper(m,n,x,y,dp): + if x==m-1 and y==n-1: + return 1 + if dp[x][y] != -1: + return dp[x][y] + if x==m-1: + dp[x][y] = helper(m,n,x,y+1,dp) + elif y==n-1: + dp[x][y] = helper(m,n,x+1,y,dp) + else : + left = helper(m,n,x+1,y,dp) + right = helper(m,n,x,y+1,dp) + dp[x][y] = left+right + return dp[x][y] + return helper(m,n,0,0,dp)