Maximum Subarray Python

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        max_sum = nums[0]
        
        for i in range(1,len(nums)):
            if nums[i-1] > 0:
                nums[i] += nums[i-1]
            max_sum = max(max_sum,nums[i])
        return max_sum
       



Maximum Subarray Python

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4],
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
Greedy Approach:
class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if nums is None:
            return None        maxValue = nums[0]
        maxSubArrayValue = nums[0]
        for i in range(1, len(nums)):
            maxValue = max(nums[i], maxValue + nums[i])
            maxSubArrayValue = max(maxValue, maxSubArrayValue)
        return maxSubArrayValue

Time Complexity : O(n)
Space Complexity : O(1)

Valid Parentheses Python

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.
An input string is valid if:
  1. Open brackets must be closed by the same type of brackets.
  2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
class Solution:
    def isValid(self, s: str) -> bool:
        stack = []
        mapping = {"}": "{", "]": "[", ")": "("}
        for char in s:
            if char in mapping:
                top_element = stack.pop() if stack else "$"
                if top_element != mapping[char]:
                    return False
            else:
                stack.append(char)
        return not stack

Time Complexity : O(n)
Space Complexity : O(n)




Missing Number Python

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        nums.sort()
        if nums[0] != 0:
            return 0        elif nums[-1] != len(nums):
            return len(nums)

        for i in range(0, len(nums)):
            if i != nums[i]:
                return i


Time Complexity : O(nlogn) // sorting
Space Complexity : O(1)

Missing Number Python

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?

// Using Extra space Hash set

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        seen_set = set(nums)
        for i in range(0,len(nums)+1):
            if i not in seen_set:
                return i



Time Complexity : O(n)
Space Complexity : O(n)



Missing Number Python

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity?
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        missing = len(nums)
        for i in range(0,len(nums)):
            missing ^= i ^ nums[i]
        return missing



Time Complexity : O(n)
Space Complexity : O(1)

Note : Here array starts with 0 not 1 so n = len(nums) 
if it starts with 1 like natural numbers then n = len(nums)+1

Missing Number Python

Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.
Example 1:
Input: [3,0,1]
Output: 2
Example 2:
Input: [9,6,4,2,3,5,7,0,1]
Output: 8
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity ?
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        total_sum = int((n*(n+1))/2)
        for i in nums:
            total_sum-=i
        return total_sum


Time Complexity : O(n)
Space Complexity : O(1)

Note : Here array starts with 0 not 1 so n = len(nums) 
if it starts with 1 like natural numbers then n = len(nums)+1

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...