Prefix/Postfix Flashcards

1
Q
  1. Plates Between Candles
    Solved
    Medium

Topics

Companies Amazon

Hint
There is a long table with a line of plates and candles arranged on top of it. You are given a 0-indexed string s consisting of characters ‘’ and ‘|’ only, where a ‘’ represents a plate and a ‘|’ represents a candle.

You are also given a 0-indexed 2D integer array queries where queries[i] = [lefti, righti] denotes the substring s[lefti…righti] (inclusive). For each query, you need to find the number of plates between candles that are in the substring. A plate is considered between candles if there is at least one candle to its left and at least one candle to its right in the substring.

For example, s = “|||||”, and a query [3, 8] denotes the substring “||**|”. The number of plates between candles in this substring is 2, as each of the two plates has at least one candle in the substring to its left and right.
Return an integer array answer where answer[i] is the answer to the ith query.

Example 1:

ex-1
Input: s = “||***|”, queries = [[2,5],[5,9]]
Output: [2,3]
Explanation:
- queries[0] has two plates between candles.
- queries[1] has three plates between candles.
Example 2:

ex-2
Input: s = “|**||||**|*”, queries = [[1,17],[4,5],[14,17],[5,11],[15,16]]
Output: [9,0,0,0,0]
Explanation:
- queries[0] has nine plates between candles.
- The other queries have zero plates between candles.

Constraints:

3 <= s.length <= 105
s consists of ‘*’ and ‘|’ characters.
1 <= queries.length <= 105
queries[i].length == 2
0 <= lefti <= righti < s.length

https://leetcode.com/problems/plates-between-candles/

A

class Solution(object):
def platesBetweenCandles(self, s, queries):
“””
:type s: str
:type queries: List[List[int]]
:rtype: List[int]
“””
nearestLeftCandle = [-1] * len(s)
nearestRightCandle = [float(‘inf’)] * len(s)
numberOfPlates = [0] * len(s)

    candleIdx = -1
    for i in range(len(s)):
        if s[i] == "|":
            candleIdx = i
        nearestLeftCandle[i] = candleIdx
    
    candleIdx = float('inf')
    for i in reversed(range(len(s))):
        if s[i] == "|":
            candleIdx = i
        nearestRightCandle[i] = candleIdx
    
    plates = 0
    for i in range(len(s)):
        if s[i] == "*" and nearestLeftCandle[i] > -1 and nearestRightCandle[i] > 0:
            plates += 1
            numberOfPlates[i] = plates
        elif s[i] == "|":
            numberOfPlates[i] = plates

    
    ret = [0] * len(queries)

    for idx, query in enumerate(queries):
        l, r = query
        nearestLeftL = nearestLeftCandle[l]
        nearestRightL = nearestRightCandle[l]
        nearestRightR = nearestRightCandle[r]
        nearestLeftR = nearestLeftCandle[r]
        leftBoundary = nearestRightL
        rightBoundary = nearestLeftR
        if leftBoundary <= rightBoundary:
            ret[idx] = numberOfPlates[rightBoundary] - numberOfPlates[leftBoundary]
    return ret
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
  1. Product of Array Except Self
    Solved
    Medium
    Topics
    Companies
    Hint
    Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

You must write an algorithm that runs in O(n) time and without using the division operation.

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]
Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Constraints:

2 <= nums.length <= 105
-30 <= nums[i] <= 30
The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer.

Follow up: Can you solve the problem in O(1) extra space complexity? (The output array does not count as extra space for space complexity analysis.)

A

class Solution(object):
def productExceptSelf(self, nums):
“””
:type nums: List[int]
:rtype: List[int]
“””
output = [1] * len(nums)
prefix = 1
for i in range(len(nums)):
output[i] = prefix
prefix *= nums[i]
postfix = 1
for i in reversed(range(len(nums))):
output[i] = output[i] * postfix
postfix = postfix * nums[i]
return output

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q
  1. Subarray Sum Equals K
    Solved
    Medium
    Topics
    Companies
    Hint
    Given an array of integers nums and an integer k, return the total number of subarrays whose sum equals to k.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: nums = [1,1,1], k = 2
Output: 2
Example 2:

Input: nums = [1,2,3], k = 3
Output: 2

Constraints:

1 <= nums.length <= 2 * 104
-1000 <= nums[i] <= 1000
-107 <= k <= 107

https://leetcode.com/problems/subarray-sum-equals-k/description/

A

from collections import defaultdict
class Solution(object):
def subarraySum(self, nums, k):
“””
:type nums: List[int]
:type k: int
:rtype: int
“””
ret = 0
m = defaultdict(int)
m[0] = 1
prefix = 0
for i in range(len(nums)):
prefix += nums[i]
diff = prefix - k
if diff in m:
ret += m[diff]
m[prefix] += 1
return ret

Concise
from collections import defaultdict

class Solution:
def subarraySum(self, nums: List[int], k: int) -> int:
sumstore = defaultdict(int)
sumstore[0] = 1
prefixSum = 0
ret = 0
for num in nums:
prefixSum += num
ret += sumstore[prefixSum-k]
sumstore[prefixSum] += 1
return ret

Instead of considering all the startstartstart and endendend points and then finding the sum for each subarray corresponding to those points, we can directly find the sum on the go while considering different endendend points. i.e. We can choose a particular startstartstart point and while iterating over the endendend points, we can add the element corresponding to the endendend point to the sum formed till now. Whenever the sumsumsum equals the required kkk value, we can update the countcountcount value. We do so while iterating over all the endendend indices possible for every startstartstart index. Whenever, we update the startstartstart index, we need to reset the sumsumsum value to 0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly