Skip to content

Commit

Permalink
Range Sum Query - Immutable
Browse files Browse the repository at this point in the history
  • Loading branch information
denis-sukhoverkhov committed Sep 18, 2024
1 parent a879e40 commit 732ed6b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
25 changes: 25 additions & 0 deletions python/leetcode/Range Sum Query - Immutable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
from typing import List


class NumArray:

def __init__(self, nums: List[int]):
self.nums = nums

self.sums = [0]
for i in range(0, len(nums)):
self.sums.append(nums[i] + self.sums[i])

def sumRange(self, left: int, right: int) -> int:
right = right + 1
res = self.sums[right] if left == 0 else self.sums[right] - self.sums[left]
return res


if __name__ == "__main__":
obj = NumArray([-2, 0, 3, -5, 2, -1])

assert obj.sumRange(0, 2) == 1
assert obj.sumRange(2, 5) == -1
assert obj.sumRange(0, 5) == -3

29 changes: 29 additions & 0 deletions python/leetcode/Ransom Note.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from collections import Counter


class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
r = Counter(ransomNote)
m = Counter(magazine)

for i in ransomNote:
if r[i] > m.get(i, 0):
return False

return True


if __name__ == "__main__":
obj = Solution()

ransomNote = "a"
magazine = "b"
assert obj.canConstruct(ransomNote, magazine) is False

ransomNote = "aa"
magazine = "ab"
assert obj.canConstruct(ransomNote, magazine) is False

ransomNote = "aa"
magazine = "aab"
assert obj.canConstruct(ransomNote, magazine) is True

0 comments on commit 732ed6b

Please sign in to comment.