0% found this document useful (0 votes)
15 views

Array

Uploaded by

Anshul Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Array

Uploaded by

Anshul Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

array

October 27, 2024

0.1 Two Sum


Given an array of integers nums and an integer target, return indices of the two
numbers such that they add up to target. You may assume that each input would have
exactly one solution, and you may not use the same element twice. You can return the answer in
any order.
Example 1:
Input: nums = [2,7,11,15], target = 9 Output: [0,1] Explanation: Because nums[0] + nums[1] ==
9, we return [0, 1]. Example 2:
Input: nums = [3,2,4], target = 6 Output: [1,2]

[ ]: class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
index_map = {}
n = len(nums)
for i in range(n):
complement = target - nums[i]
if complement in index_map:
return [i, index_map[complement]]
else:
index_map[nums[i]] = i
return

0.2 Best Time to Buy and Sell Stock


You are given an array prices where prices[i] is the price of a given stock on the ith day. You want
to maximize your profit by choosing a single day to buy one stock and choosing a different day in
the future to sell that stock. Return the maximum profit you can achieve from this transaction. If
you cannot achieve any profit, return 0.
Example 1:
Input: prices = [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5
(price = 6), profit = 6-1 = 5. Note that buying on day 2 and selling on day 1 is not allowed because
you must buy before you sell.
Example 2:

1
Input: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transactions are done and the
max profit = 0.
[ ]: class Solution:
def maxProfit(self, prices: List[int]) -> int:

min_price, max_profit = float('inf'), 0


n = len(prices)

for i in range(n):
min_price = min(min_price, prices[i])
max_profit = max(max_profit, prices[i] - min_price)
return max_profit

0.3 Contains Duplicate


Given an integer array nums, return true if any value appears at least twice in the array, and return
false if every element is distinct.
Example 1:
Input: nums = [1,2,3,1] Output: true
Explanation: The element 1 occurs at the indices 0 and 3.
[ ]: class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return not len(nums) == len(set(nums))

0.4 Product of Array Except Self


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]

[ ]: class Solution:
def productExceptSelf(self, nums: List[int]) -> List[int]:
#initialization

n = len(nums)
l, r = [1]*n, [1]*n
result = [1]*n

for i in range(1, n):


l[i] = l[i-1] * nums[i-1]

2
for i in range(n-2, -1, -1):
r[i] = r[i+1] * nums[i+1]

#updating the resultant array


for i in range(n):
result[i] = l[i] * r[i]
return result

0.5 Maximum Sum Subarray : subarray with the largest sum, and return its
sum.
Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4] Output: 6 Explanation: The subarray [4,-1,2,1] has the largest
sum 6. Example 2:
Input: nums = [1] Output: 1 Explanation: The subarray [1] has the largest sum 1.

[ ]: class Solution:
def maxSubArray(self, nums: List[int]) -> int:
l , r = 0,0
cur_sum, max_sum = nums[0], nums[0]
n = len(nums)

for r in range(1, n):


cur_sum = max(cur_sum + nums[r], nums[r])
max_sum = max(max_sum, cur_sum)
return max_sum

0.6 Maximum Product Subarray


Given an integer array nums, find a subarray that has the largest product, and return the product.
The test cases are generated so that the answer will fit in a 32-bit integer.
Example 1: Input: nums = [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2: Input: nums = [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1]
is not a subarray.
[ ]: class Solution:
def maxProduct(self, nums: List[int]) -> int:
prefix, suffix, max_prod = 1,1, float('-inf')
n = len(nums)
for i in range(n):
if prefix == 0:
prefix = 1
if suffix == 0:
suffix = 1

3
prefix = prefix * nums[i]
suffix = suffix * nums[n-i-1]
max_prod = max(max_prod, max(prefix, suffix))
return max_prod

0.7 Find minimum in Rotated Sorted Array


Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For
example, the array nums = [0,1,2,4,5,6,7] might become: [4,5,6,7,0,1,2] if it was rotated 4 times.
[0,1,2,4,5,6,7] if it was rotated 7 times. Notice that rotating an array [a[0], a[1], a[2], …, a[n-1]] 1
time results in the array [a[n-1], a[0], a[1], a[2], …, a[n-2]]. Given the sorted rotated array nums of
unique elements, return the minimum element of this array.
You must write an algorithm that runs in O(log n) time.
Example 1: Input: nums = [3,4,5,1,2] Output: 1 Explanation: The original array was [1,2,3,4,5]
rotated 3 times.
Example 2: Input: nums = [4,5,6,7,0,1,2] Output: 0 Explanation: The original array was
[0,1,2,4,5,6,7] and it was rotated 4 times.

[ ]: class Solution:
def findMin(self, nums: List[int]) -> int:
start = 0
end = len(nums) - 1

def findmin_helper(nums, start, end):


if start > end:
return float('inf')

# If the subarray is already sorted


if nums[start] <= nums[end]:
return nums[start]

mid = (start + end) // 2

if nums[start] <= nums[mid]:


return min(nums[start] , findmin_helper(nums, mid + 1, end))
else: # Otherwise, the minimum is on the right side
return min(nums[mid] , findmin_helper(nums, start, mid - 1))

return findmin_helper(nums, start, end)

0.8 Search-in-rotated-sorted-array/description
There is an integer array nums sorted in ascending order (with distinct values). Prior to being passed
to your function, nums is possibly rotated at an unknown pivot index k (1 <= k < nums.length) such
that the resulting array is [nums[k], nums[k+1], …, nums[n-1], nums[0], nums[1], …, nums[k-1]] (0-
indexed). For example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0,1,2].

4
Given the array nums after the possible rotation and an integer target, return the index of target
if it is in nums, or -1 if it is not in nums.
You must write an algorithm with O(log n) runtime complexity.
Example 1:
Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2:
Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1

[ ]: class Solution:
def search(self, nums: List[int], target: int) -> int

start = 0
end = len(nums) -1

def search_helper(nums, start, end, target):


if start > end:
return -1

mid = (start + end)//2


if nums[mid] == target:
return mid

if nums[start] <= nums[mid]:


if nums[start] <= target < nums[mid]:
return search_helper(nums, start, mid-1, target)
else:
return search_helper(nums, mid+1, end, target)
else:
if nums[mid] < target <= nums[end]:
return search_helper(nums, mid+1, end, target)
else:
return search_helper(nums, start, mid-1, target)

return search_helper(nums, start, end, target)

0.9 3sum
Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i
!= k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not
contain duplicate triplets.
Example 1:
Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2]
= (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] +
nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order
of the output and the order of the triplets does not matter.

5
Example 2:
Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0.

[ ]: class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
nums.sort()
n = len(nums)
result = []
for i in range(n-2):
if i> 0 and nums[i] == nums[i-1]:
continue
j = i+1
k = n-1
while j < k:
if ((nums[i] + nums[j] + nums[k]) == 0) :
result.append([nums[i], nums[j], nums[k]])

while j < k and nums[j] == nums[j+1]:


j += 1
while j < k and nums[k] == nums[k-1]:
k -= 1

j += 1
k -= 1
elif nums[i] + nums[j] + nums[k] < 0:
j += 1
else:
k -= 1

return result

0.10 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. Notice that you may
not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented
by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can
contain is 49.
Example 2:
Input: height = [1,1] Output: 1

6
[ ]: class Solution:
def maxArea(self, height: List[int]) -> int:
n = len(height)
i = 0
j = n-1
max_area = float('-inf')
while i < j:
curr_max_area = (j-i)*(min(height[i],height[j]))
max_area = max(max_area, curr_max_area)
if height[i] < height[j]:
i +=1
else:
j -=1
return max_area

[ ]:

[ ]:

You might also like