Array/String¶

Important point:¶

  • Transfer list into string: ```python ''.join(list)
  • String could be added, multiplied, but not subtracted or divided.
    'a' + 'b' = 'ab'
    'a' * 3 = 'aaa'
    'a' - 'b' = Error
    'a' / 'b' = Error
    
  • We could use append to add element to list, but not string.
    list.append('a')
    string.append('a') = Error
    

151. Reserse Words in a String¶

Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single space.

Note that s may contain leading or trailing spaces or multiple spaces between two words. The returned string should only have a single space separating the words. Do not include any extra spaces.

Example 1:

Input: s = "the sky is blue"

Output: "blue is sky the"

Example 2:

Input: s = " hello world "

Output: "world hello"

Explanation: Your reversed string should not contain leading or trailing spaces.

Example 3:

Input: s = "a good example"

Output: "example good a"

Explanation: You need to reduce multiple spaces between two words to a single space in the reversed string.

In [5]:
# How to reverse the sring in python
def reverseWords(self, s: str, delimiter = " ") -> str:
        s = list(s.split())
        s = s[::-1]
        return (" ".join(s))

334. Increasing Triplet Subsequence¶

Given an integer array nums, return true if there exists a triple of indices (i, j, k) such that i < j < k and nums[i] < nums[j] < nums[k]. If no such indices exists, return false.

Example 1:

Input: nums = [1,2,3,4,5]

Output: true

Explanation: Any triplet where i < j < k is valid.

Example 2:

Input: nums = [5,4,3,2,1]

Output: false

Explanation: No triplet exists.

Example 3:

Input: nums = [2,1,5,0,4,6]

Output: true

Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.

In [6]:
# inf = float("inf")
# We could use inf to initialize the distance array
# 334. Increasing Triplet Subsequence
def increasingTriplet(self, nums) -> bool:
        first = second = float('inf')
        for i in nums:
            if i <= first:
                first = i
            elif i <= second:
                second = i
            else:
                return True
        return False

443. String Compression¶

Given an array of characters chars, compress it using the following algorithm:

Begin with an empty string s. For each group of consecutive repeating characters in chars:

If the group's length is 1, append the character to s. Otherwise, append the character followed by the group's length. The compressed string s should not be returned separately, but instead, be stored in the input character array chars. Note that group lengths that are 10 or longer will be split into multiple characters in chars.

After you are done modifying the input array, return the new length of the array.

You must write an algorithm that uses only constant extra space.

Example 1:

Input: chars = ["a","a","b","b","c","c","c"]

Output: Return 6, and the first 6 characters of the input array should be: ["a","2","b","2","c","3"]

Explanation: The groups are "aa", "bb", and "ccc". This compresses to "a2b2c3".

Example 2:

Input: chars = ["a"]

Output: Return 1, and the first character of the input array should be: ["a"]

Explanation: The only group is "a", which remains uncompressed since it's a single character.

Example 3:

Input: chars = ["a","b","b","b","b","b","b","b","b","b","b","b","b"]

Output: Return 4, and the first 4 characters of the input array should be: ["a","b","1","2"].

Explanation: The groups are "a" and "bbbbbbbbbbbb". This compresses to "ab12".

In [7]:
# 443. String Compression
def compress(self, chars) -> int:
        ans = 0
        i = 0
        while i < len(chars):
            letter = chars[i]
            count = 0
            while i < len(chars) and chars[i] == letter:
                count += 1
                i += 1
            chars[ans] = letter
            ans += 1
            if count > 1:
                for c in str(count):
                    chars[ans] = c
                    ans += 1
        return ans

Two Pointers¶

283. Move Zeroes¶

Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.

Note that you must do this in-place without making a copy of the array.

Example 1:

Input: nums = [0,1,0,3,12]

Output: [1,3,12,0,0]

Example 2:

Input: nums = [0]

Output: [0]

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

392. Is Subsequence¶

Given two strings s and t, return true if s is a subsequence of t, or false otherwise.

A subsequence of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., "ace" is a subsequence of "abcde" while "aec" is not).

Example 1:

Input: s = "abc", t = "ahbgdc"

Output: true

Example 2:

Input: s = "axc", t = "ahbgdc"

Output: false

In [11]:
def isSubsequence(self, s: str, t: str) -> bool:
    count = 0
    for char in t:
        if count == len(s):
                return True
        if s[count] == char:
                count += 1
    return count == len(s)

11. Container With Most Water¶

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).

Find two lines that together with the x-axis form a container, such that the container contains the most water.

Return the maximum amount of water a container can store.

In [13]:
def maxArea(self, height) -> int:
    left = 0
    right = len(height) - 1
    maxArea = 0

    while left < right:
        minimum = min(height[left], height[right])
        width = right - left
        currArea = minimum * width
        maxArea = max(currArea, maxArea)

        if height[left] < height[right]:
            left += 1
        else:
            right -= 1
    return maxArea

1679. Max Number of K-Sum Pairs¶

You are given an integer array nums and an integer k.

In one operation, you can pick two numbers from the array whose sum equals k and remove them from the array.

Return the maximum number of operations you can perform on the array.

Example 1:

Input: nums = [1,2,3,4], k = 5

Output: 2

Explanation: Starting with nums = [1,2,3,4]:

  • Remove numbers 1 and 4, then nums = [2,3]
  • Remove numbers 2 and 3, then nums = [] There are no more pairs that sum up to 5, hence a total of 2 operations.

Example 2:

Input: nums = [3,1,3,4,3], k = 6

Output: 1

Explanation: Starting with nums = [3,1,3,4,3]:

  • Remove the first two 3's, then nums = [1,4,3] There are no more pairs that sum up to 6, hence a total of 1 operation.
In [15]:
def maxOperations(self, nums, k: int) -> int:
        nums.sort()
        l, r = 0, len(nums) - 1
        count = 0
        while l < r:
            sums = nums[l] + nums[r]
            if sums == k:
                l += 1
                r -= 1
                count += 1
            elif sums < k:
                l += 1
            else:
                r -= 1
        return count

Sliding Window¶

643. Maximum Average Subarray I¶

You are given an integer array nums consisting of n elements, and an integer k.

Find a contiguous subarray whose length is equal to k that has the maximum average value and return this value. Any answer with a calculation error less than 10-5 will be accepted.

Example 1:

Input: nums = [1,12,-5,-6,50,3], k = 4

Output: 12.75000

Explanation: Maximum average is (12 - 5 - 6 + 50) / 4 = 51 / 4 = 12.75

Example 2:

Input: nums = [5], k = 1

Output: 5.00000

In [16]:
def findMaxAverage(self, nums, k: int) -> float:
        currSum = maxSum = sum(nums[:k])
        for i in range(k, len(nums)):
            currSum += nums[i] - nums[i - k]
            maxSum = max(maxSum, currSum)
        return maxSum / k

1456. Maximum Number of Vowels in a Substring of Given Length¶

Given a string s and an integer k, return the maximum number of vowel letters in any substring of s with length k.

Vowel letters in English are 'a', 'e', 'i', 'o', and 'u'.

Example 1:

Input: s = "abciiidef", k = 3

Output: 3

Explanation: The substring "iii" contains 3 vowel letters.

Example 2:

Input: s = "aeiou", k = 2

Output: 2

Explanation: Any substring of length 2 contains 2 vowels.

Example 3:

Input: s = "leetcode", k = 3 Output: 2

Explanation: "lee", "eet" and "ode" contain 2 vowels.

In [1]:
def maxVowels(self, s: str, k: int) -> int:
    vowels = {'a', 'e', 'i', 'o' ,'u', 'A', 'E', 'I' ,'O', 'U'}
    max_vowels = curr_vowels = l = 0
    for r in range(len(s)):
        if s[r] in vowels:
                    curr_vowels += 1
        if r - l + 1 > k:
            if s[l] in vowels:
                curr_vowels -= 1
                l += 1
                
        max_vowels = max(max_vowels, curr_vowels)

    return max_vowels