0% found this document useful (0 votes)
2 views3 pages

Array Questions Python Codes-2

The document presents solutions to the top 10 array coding questions using Python. Each question includes a brief description and a corresponding function implementation. The topics covered include finding sums, maximizing profits, handling duplicates, and more.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views3 pages

Array Questions Python Codes-2

The document presents solutions to the top 10 array coding questions using Python. Each question includes a brief description and a corresponding function implementation. The topics covered include finding sums, maximizing profits, handling duplicates, and more.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Top 10 Array Coding Questions with Python

Solutions
1. Two Sum

def twoSum(nums, target):


d={}
for i,num in enumerate(nums):
diff=target-num
if diff in d:
return [d[diff],i]
d[num]=i

2. Best Time to Buy and Sell Stock

def maxProfit(prices):
min_price=prices[0]
profit=0
for price in prices:
min_price=min(min_price,price)
profit=max(profit,price-min_price)
return profit

3. Maximum Subarray (Kadane)

def maxSubArray(nums):
cur=mx=nums[0]
for x in nums[1:]:
cur=max(x,cur+x)
mx=max(mx,cur)
return mx

4. Merge Sorted Array

def merge(nums1,m,nums2,n):
nums1[m:]=nums2
[Link]()

5. Move Zeroes
def moveZeroes(nums):
j=0
for i in range(len(nums)):
if nums[i]!=0:
nums[j],nums[i]=nums[i],nums[j]
j+=1

6. Rotate Array

def rotate(nums,k):
k%=len(nums)
nums[:]=nums[-k:]+nums[:-k]

7. Remove Duplicates from Sorted Array

def removeDuplicates(nums):
if not nums: return 0
j=1
for i in range(1,len(nums)):
if nums[i]!=nums[i-1]:
nums[j]=nums[i]
j+=1
return j

8. Product of Array Except Self

def productExceptSelf(nums):
n=len(nums)
ans=[1]*n
p=1
for i in range(n):
ans[i]=p
p*=nums[i]
s=1
for i in range(n-1,-1,-1):
ans[i]*=s
s*=nums[i]
return ans

9. Majority Element
def majorityElement(nums):
count=0
cand=None
for x in nums:
if count==0:
cand=x
count += 1 if x==cand else -1
return cand

10. Missing Number

def missingNumber(nums):
n=len(nums)
return n*(n+1)//2 - sum(nums)

You might also like