DSA - Array

Code Templates

Problems

  • Two Sum
  • Median of two sorted arrays
  • container with most water
  • 3Sum
  • 3Sum Closest
  • 4Sum
  • Remove Duplicates from Sorted Array
  • Remove Element
  • Next Permutation
  • Search in Rotated Sorted Array
  • Find first and last position of element in sorted array
  • search insert position
  • combination sum
  • combination sum II
  • first missing positive
  • trappint rain water
  • jump game II
  • rotate image
  • maximum subarray
  • spiral matrix
  • jump game
  • merge intervals
  • insert interval
  • spiral matrix II
  • unique paths
  • unique paths II
  • minimum path sum
  • plus one
  • set matrix zeroes
  • search a 2D matrix
  • sort colors
  • subsets
  • word search
  • remove duplicates from sorted array II
  • largest rectangle in histogram
  • merge sorted array
  • subsets II
  • construct binary tree from preorder and inorder Traversal
  • construct binary tree from Inorder and Postorder Traversal
  • pscal’s triangle
  • pasal’s triangle II
  • Triangle
  • best time to buy and sell stock
  • best time to buy and sell stock II
  • word ladder II
  • longest consecutive sequence
  • maximum product subarray
  • find minimum in rotated sorted array
  • find minimum in rotated sorted array II
  • find peak element
  • two sum - input array is sorted
  • majority element
  • rotate array
  • minimum size subarray sum
  • combination sum III
  • contains duplicate
  • contains duplicate II
  • summary ranges
  • majority element II
  • missing number
  • move zeroes
  • find the duplicate number
  • third maximum number
  • find all numbers disppeared in an array
  • circular array loop
  • max consecutive ones
  • fibonacci number
  • k-diff pairs in an array
  • array partition I
  • reshape the matrix
  • shortest unsorted continuous subarray
  • can place flowers
  • maximum product of three times
  • maximum product of three numbers
  • maximum average subarray I
  • image smoother
  • non-decreasing array
  • beautiful arrangement II
  • longest continuous increasing subsequence
  • max area of island
  • degree of an array
  • subarray product less than K
  • best time to buy and sell stock with transaction fee
  • 1-bit and 2bit characters
  • maximum length of repeated subarray
  • find pivot index
  • my calendar I
  • min cost climbing stairs
  • toeplitz matrix
  • global and local inversions
  • number of subarrarys with bounded maximum
  • positions of large groups
  • flipping an image
  • transpose matrix
  • advantage shuffle
  • fair candy swap
  • sum of subsequence widths
  • monotonic
  • array
  • sum of sumarray minimums
  • x of a kind in a deck of cards
  • maximum sum circular subarray
  • sort array by parity II
  • pancake sorting
  • squares of a sorted array
  • longest turbulent subarray
  • sum of even numbers after queries
  • add to array-form of integer
  • available captures for rook
  • find common characters
  • capacity to ship packages within D days
  • binary prefix divisible by 5
  • moving stones until consecutive II
  • height checker
  • grumpy bookstore owner
  • number of submatrices that sum to target
  • duplicate zeros
  • relative sort array
  • number of equivalent domino pairs
  • online majority element in subarray
  • find words that can be formed by characters
  • compare string by frequency of the smallest character
  • distance between bus stops
  • day of the week
  • minimum absolute difference
  • smallest string with swaps
  • get equal substrings within budget
  • minimum cost to move chips to the same position
  • check if it is a straight line
  • cells with oodd values in a matrix
  • shift 2d grid
  • minimum time visiting all points
  • find winner on a tic tac toe game
  • element appearing more then 25% in sorted array
  • reaplace elements with greatest element on right side
  • sum of mutated array closest to target
  • find n unique integers sum up to zero
  • decompress run-length encoded list
  • sort the matrix diagonally
  • the K weakest rows in a matrix
  • lucky numbers in a matrix
  • find the distance value between two arrays
  • create target array in the given order
  • maximum points you can obtain from cards
  • check if all 1’s are at least length K places away
  • longest continuous subarray with absolute diff less than or equal to limit
  • count triplets that can form two arrays of equal XOR
  • maximum product of two elements in an array
  • maximum area of a piece of cake after horizontal and vertical cuts
  • shuffle the array
  • running sum of 1d array
  • minimum number of days to make m bouquets
  • XOR operations in an array
  • number of good pairs
  • kth missing positive number
  • matrix diagonal sum
  • special array with x elements greater than or equal x
  • mean of array after removing some elements
  • slowest key
  • sort array by increasing frequency
  • check array formation through concatenation
  • get maximum in generated array
  • defuse the bomb
  • design an ordered stream
  • richest customer wealth
  • number of students unable to eat lunch
  • find the highest altitude
  • find kth largest xor corrdinate value
  • maximum number of balls in a box
  • sum of unique elements
  • check if array is sorted and rotated
  • minimum changes to make alternating binary string

two pointers

  • longest substring without repeating characters
  • container with most water
  • 3Sum
  • 3Sum Closest
  • 4Sum
  • remove Nth node from end of list
  • remove duplicate from sorted array
  • remove element
  • implement strStr()
  • substring with concatenation of all words
  • trapping rain water
  • rotate list
  • sort colors
  • minimum window substring
  • remove duplicates from sorted array II
  • partition list
  • merge sorted array
  • valid palindrome
  • linked list cycle
  • linked list cycle II
  • longest substring with at most two distinct characters
  • two sum II - input array is sorted
  • minimum size subarray sum
  • palindrome linked list
  • 3Sum smaller
  • move zeroes
  • find the duplicate number
  • reverse string
  • reverse vowels of a string
  • intersection of two arrays
  • intersection of two arrays II
  • sort transformed array
  • longest repeating chracter replacement
  • circular array loop
  • max consecutive ones II
  • longtest word in dictionary through deleting
  • k-diff pairs in an array
  • permutation in string
  • smallest range covering elements from k lists
  • subarray product less than k
  • candy crush
  • partition labels
  • most profit assigning work
  • unique letter string
  • push dominoes
  • backspace string compare
  • longest mountain in array
  • boats to save people
  • fruit into baskets
  • 3sum with multiplicity
  • long pressed name
  • binary subarrays with sum
  • squares of a sorted array
  • interval list intersections
  • subarrays with k different integers
  • max consecutive ones III
  • statistics from a large sample
  • replace the substring for balanced string
  • minimum operations to reduce x to zero

Solutions

move zeroes

1
2
3
4
5
6
7
8
class Solution:
  def move_zeroes(self, nums: List[int]) -> List[int]:
    j = 0
    for i in range(len(nums)):
      if nums[i] != 0:
        nums[i], nums[j] = nums[j], nums[i]
        j+=1
    return nums

container with most water

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution:
  def container(self, nums: List[int]) -> int:
    n = len(nums)
    l, r = 0, n - 1
    max_ = 0
    while l < r:
      max_ = max(max_, (r-l)*min(nums[l], nums[r]))
      if nums[l] < nums[r]:
        l += 1
      else:
        r -= 1
    return max_

rotate array

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
  def rotate(self, nums: List[int], k: int) -> None:
    """
    make an extra copy and then rotate
    """
    n = len(nums)
    cp = copy.deepcopy(nums)
    for i in range(n):
      nums[(i+k)%n] = cp[i]

  def rotate(self, nums: List[int], k: int) -> None:
    """
    Reverse the first n - k elements, the last k elements, and then all the n elements.
    """
    n = len(nums)
    k = k % n
    # reverse, inclusive
    def rev(nums, i, j):
      while i < j:
        nums[i], nums[j] = nums[j], nums[i]
        i+=1
        j-=1
    rev(nums, 0, n-1)
    rev(nums, 0, k-1)
    rev(nums, k, n-1)
Licensed under CC BY-NC-SA 4.0
Get Things Done
Built with Hugo
Theme Stack designed by Jimmy