Skip to content
Open

Array-2 #1840

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 51 additions & 0 deletions game_of_life.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
time - o(n)
space - o(1)
we follow the rules and change 0 to 1 and 1 to 0, however, this causes information
loss. So we represent 0 -> 1 change as 2 and 1 -> 0 change as 3
"""

from typing import List


class Solution:
def get_score(self, board, i, j):
direction = [
(0, -1),
(-1, -1),
(-1, 0),
(-1, 1),
(0, 1),
(1, 1),
(1, 0),
(1, -1),
]
score = 0
for d in direction:
if 0 <= i + d[0] < len(board) and 0 <= j + d[1] < len(board[0]):
val = board[i + d[0]][j + d[1]]
if val < 2:
score += val
elif val == 3:
score += 1
return score

def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
# 0 -> 1 = 2 and 1 -> 0 = 3
for i in range(len(board)):
for j in range(len(board[0])):
score = self.get_score(board, i, j)
if (score < 2 or score > 3) and board[i][j] == 1:
board[i][j] = 3
elif score == 3 and board[i][j] == 0:
board[i][j] = 2

for i in range(len(board)):
for j in range(len(board[0])):
if board[i][j] == 2:
board[i][j] = 1
if board[i][j] == 3:
board[i][j] = 0
19 changes: 19 additions & 0 deletions missing_numbers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"""
time - o(n)
space - o(1)
we take each number in the array and head to the array[number] (using the number as an index)
we make this number as negative, any number that is missing will have array[number] as positive
"""

from typing import List


class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
for i in range(len(nums)):
nums[abs(nums[i]) - 1] *= -1 if nums[abs(nums[i]) - 1] > 0 else 1
result = []
for i in range(len(nums)):
if nums[i] > 0:
result.append(i + 1)
return result