Move Zeroes Python

Move Zeroes
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
  1. You must do this in-place without making a copy of the array.
  2. Minimize the total number of operations.
// Two Pointer Technique 
// Slow pointer and fast pointer technique


class Solution:
    def moveZeroes(self, nums: List[int]) -> None:
        """        Do not return anything, modify nums in-place instead.        """        i, j = 0, 0        for i in range(0, len(nums)):
            if nums[i] != 0:
                nums[i], nums[j] = nums[j], nums[i]
                j += 1

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

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

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...