0% found this document useful (0 votes)
4 views

Leetcode 75 Blind - Part 2

The document presents solutions to various dynamic programming and algorithmic problems, including climbing stairs, coin change, longest increasing subsequence, and more. Each problem includes a brief description, a Python code implementation, and an explanation of the approach used. The solutions emphasize efficiency and space optimization techniques.

Uploaded by

abbhi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Leetcode 75 Blind - Part 2

The document presents solutions to various dynamic programming and algorithmic problems, including climbing stairs, coin change, longest increasing subsequence, and more. Each problem includes a brief description, a Python code implementation, and an explanation of the approach used. The solutions emphasize efficiency and space optimization techniques.

Uploaded by

abbhi2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Leetcode 75 Blind - part 2

16.Climbing Stairs

Question:

You are climbing a staircase. It takes n steps to reach the top. Each time you can climb 1 or 2
steps. How many distinct ways can you climb to the top?

Solution:

Classic DP problem. Number of ways to reach step n = ways to reach step n-1 + ways to reach
step n-2.

Code (Python):

def climbStairs(n):
if n <= 2:
return n
first, second = 1, 2
for _ in range(3, n + 1):
first, second = second, first + second
return second

Explanation:

This is identical to Fibonacci numbers. We use two variables to reduce space complexity to
O(1).

17.Coin Change

Question:

Given coins of different denominations and a total amount, return the minimum number of coins
that make up that amount. Return -1 if it cannot be done.

Solution:

Use dynamic programming. dp[x] = min(dp[x], dp[x - coin] + 1) for every coin.

Code (Python):
def coinChange(coins, amount):
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1

Explanation:

We build up solutions for every value up to amount. We check all coin combinations efficiently.

18.Longest Increasing Subsequence

Question:

Given an array of integers, find the length of the longest strictly increasing subsequence.

Solution:

Use dynamic programming: For each element, look back and find the longest sequence it can
extend.

Code (Python):

def lengthOfLIS(nums):
dp = [1] * len(nums)
for i in range(len(nums)):
for j in range(i):
if nums[i] > nums[j]:
dp[i] = max(dp[i], dp[j] + 1)
return max(dp)

Explanation:

Each position holds the length of the longest increasing subsequence ending at that index. Time
complexity is O(n²).

19.Longest Common Subsequence


Question:

Given two strings, return the length of their longest common subsequence.

Solution:

Classic 2D DP table. If characters match, add 1 to the diagonal value.

Code (Python):

def longestCommonSubsequence(text1, text2):


m, n = len(text1), len(text2)
dp = [[0]*(n+1) for _ in range(m+1)]
for i in range(m):
for j in range(n):
if text1[i] == text2[j]:
dp[i+1][j+1] = dp[i][j] + 1
else:
dp[i+1][j+1] = max(dp[i][j+1], dp[i+1][j])
return dp[m][n]

Explanation:

We compare characters and propagate the maximum value of adjacent cells if there’s no match.
Space complexity is O(m*n).

20.Word Break

Question:

Given a string s and a dictionary of strings wordDict, determine if s can be segmented into a
space-separated sequence of one or more dictionary words.

Solution:

Use a DP array where dp[i] is True if s[:i] can be segmented.

Code (Python):

def wordBreak(s, wordDict):


wordSet = set(wordDict)
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(1, len(s) + 1):
for j in range(i):
if dp[j] and s[j:i] in wordSet:
dp[i] = True
break
return dp[-1]

Explanation:

We iterate through every possible partition and check if both parts exist in our dictionary.
Efficient due to set lookup.

21.Combination Sum

Question:

Given an array of distinct integers candidates and a target integer target, return all unique
combinations of candidates where the chosen numbers sum to target. Numbers can be chosen
unlimited times.

Solution:

Use backtracking to explore all possibilities.

Code (Python):

def combinationSum(candidates, target):


res = []
def backtrack(start, target, path):
if target == 0:
res.append(path)
return
for i in range(start, len(candidates)):
if candidates[i] <= target:
backtrack(i, target - candidates[i], path + [candidates[i]])
backtrack(0, target, [])
return res

Explanation:

We explore each candidate recursively. The same element can be used multiple times, so
backtrack does not advance start.
22.House Robber

Question:

You are a professional robber. Each house has a certain amount of money. Rob houses such
that no two adjacent houses are robbed. Return the maximum amount you can rob.

Solution:

DP relation: dp[i] = max(dp[i - 1], dp[i - 2] + nums[i])

Code (Python):

def rob(nums):
if not nums:
return 0
if len(nums) <= 2:
return max(nums)
first, second = nums[0], max(nums[0], nums[1])
for i in range(2, len(nums)):
first, second = second, max(second, first + nums[i])
return second

Explanation:

At each step, decide whether to rob the current house and add its value to dp[i - 2] or skip it and
take dp[i - 1].

23.House Robber II

Question:

Same as House Robber, but houses are arranged in a circle. First and last houses cannot both
be robbed.

Solution:

Run House Robber twice: once excluding the first house and once excluding the last house.

Code (Python):

def rob(nums):
def rob_line(houses):
first, second = 0, 0
for h in houses:
first, second = second, max(second, first + h)
return second
if len(nums) == 1:
return nums[0]
return max(rob_line(nums[1:]), rob_line(nums[:-1]))

Explanation:

We split the problem into two linear subproblems to handle the circular constraint.

24.Decode Ways

Question:

A message containing letters A-Z is encoded as ‘1’ = A, …, ‘26’ = Z. Given a string of digits,
return the number of ways to decode it.

Solution:

DP: dp[i] = dp[i-1] if s[i-1] != '0' + dp[i-2] if valid two-digit number.

Code (Python):

def numDecodings(s):
if not s or s[0] == '0':
return 0
dp = [1, 1]
for i in range(1, len(s)):
dp.append(0)
if s[i] != '0':
dp[-1] += dp[-2]
if 10 <= int(s[i-1:i+1]) <= 26:
dp[-1] += dp[-3]
dp.pop(0)
return dp[-1]

Explanation:
Check for valid single-digit and two-digit decodings at each position. We only keep the last two
results to save space.

25.Unique Paths

Question:

A robot is located at the top-left corner of an m x n grid. It can only move right or down. Find
how many possible unique paths exist to the bottom-right corner.

Solution:

Dynamic programming grid fill: dp[i][j] = dp[i-1][j] + dp[i][j-1].

Code (Python):

def uniquePaths(m, n):


dp = [[1]*n for _ in range(m)]
for i in range(1, m):
for j in range(1, n):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
return dp[-1][-1]

Explanation:

Each cell represents the number of ways to get there, which is the sum of the ways from the cell
above and the cell to the left.

26.Jump Game

Question:

Given an array nums, where nums[i] represents the maximum jump length at index i, return true
if you can reach the last index.

Solution:

Greedy approach: keep track of the furthest reachable index.

Code (Python):

def canJump(nums):
max_reach = 0
for i, jump in enumerate(nums):
if i > max_reach:
return False
max_reach = max(max_reach, i + jump)
return True

Explanation:

At each step, update the farthest index you can reach. If at any point the current index exceeds
this reach, return False.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy