Skip to content
Merged
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
34 changes: 34 additions & 0 deletions climbing-stairs/yerim01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# Goal: Given n steps, return the number of distinct ways you can climb to the top.
# Constraints:
# - You can climb either 1 or 2 steps at each time.
# - 1 <= n <= 45
# Approach:
# f(n) = number of ways to reach step n.
# The last move must be from step n-1 or step n-2.
# Therefore, f(n) = f(n-1) + f(n-2).
# Base case - f(1) = 1, f(2) = 2.
# Use two variables prev1&prev2 to track the number of of f(n-1)&f(n-2).
# Iterate a loop, staring from 3.
# Store prev1 into temp.
# Update prev1&prev2.
# Return prev1.

# Time complexity: O(n)
# - We iterate once
# Space complexity: O(1)
# - Only using variables

class Solution:
def climbStairs(self, n: int) -> int:
if n <= 2:
return n

prev1 = 2
prev2 = 1

for i in range(3, n+1):
temp = prev1
prev1 = prev2 + prev1
prev2 = temp

return prev1
30 changes: 30 additions & 0 deletions product-of-array-except-self/yerim01.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Goal: Return an array answer that product of all elements except nums[i].
#
# Approach:
# Use prefix&suffix arrays to store cumulative products
# - prefix: product of elements to the left of i
# - suffix: product of elements to the right of i
# Calculate the result[i] by multipying prefix[i] and suffix[i]
#
# Time Complexity: O(n)
# - We Iterate the array to compute prefix, suffix and result.
# Space Complexity: O(n)
# - We use extra arrays for prefix&suffix.
class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
n = len(nums)

prefix = [1] * n
suffix = [1] * n
result = [1] * n

for i in range(1, n):
prefix[i] = prefix[i-1] * nums[i-1]

for i in range(n-2, -1, -1):
suffix[i] = suffix[i+1] * nums[i+1]

for i in range(len(nums)):
result[i] = prefix[i] * suffix[i]

return result
Loading