Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
10 views

Array

Uploaded by

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

Array

Uploaded by

krishkdd0
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

def num_identical_pairs(nums):

count = 0

for i in range(len(nums)):

for j in range(i + 1, len(nums)):

if nums[i] == nums[j]:

count += 1

return count

# Example usage:

nums = [1, 2, 3, 1, 1, 3]

print("Number of good pairs:", num_identical_pairs(nums))

ef finalValueAfterOperations(operations):

count = 0

length= len(operations)

for i in range(length):

if(operations[i]=="++x" or operations[i]=="x++"):

count+=1

print(operations[i])

elif(operations[i]=='--x' or operations[i]=='x--'):

count-=1

print(operations[i])

return count

a=['--x','x++','x++']

b=['++x','++x','x++']

res1 = finalValueAfterOperations(a)

res2 = finalValueAfterOperations(b)

print('operation1',res1)

print('operation2',res2)
def shuffleArray(nums,n):

result=[]

for i in range(n):

result.append(nums[i])

result.append(nums[i+n])

return result

num= [2,5,1,3,4,7]

no=3

answer = shuffleArray(num,no)

print(answer)

def findWordsContaining(self,words, x):

res = []

for i in range(len(words)):

if x in words[i]:

res.append(i)

return res

# Example usage:

text = ["abc","bcd","aaaa","cbc"]

char = 'a'

words_with_char = findWordsContaining(text, char)

print("Words containing the character:", words_with_char)


def maxWealth(accounts):

highest_sum=0

for account in accounts:

current_sum = sum(account)

if current_sum>highest_sum:

highest_sum = current_sum

return highest_sum

l1=[[1,5],[7,3],[3,5]]

l2=[[1,2,3],[3,2,1]]

result = maxWealth(l1)

print('max wealth',result)

def targetcount(nums,n):

count = 0

for i in nums:

if i>=n:

count+=1

return count

inp = [1,1,2,4,5]

target = 2

output = targetcount(inp,target)

print(output)

def runningSum(nums):

for i in range(1,len(nums)):

nums[i] = nums[i-1] + nums[i]

return nums

nums = [1,2,3,4]
res=runningSum(nums)

print(res)

def truncateSentence(s,k):

words= s.split(" ")

print(words)

truncated_words=words[:k]

truncated_s=" ".join(truncated_words)

return truncated_s

s="hello how are you gugu"

k=2

result=truncateSentence(s,k)

print(result)

class Solution:

def countPairs(self, nums: list[int], target: int) -> int:

nums.sort() # sort the vector nums

count = 0 # variable to store the count

left = 0 # variable to store the left

right = len(nums)-1 # variable to store the right

while(left < right): # loop until left is less than right

if(nums[left] + nums[right] < target): # if nums[left] + nums[right] is less than target

count += right-left # update the count

left += 1 # increment the left

else: # else

right -= 1 # decrement the right

return count # return the count

nums=[-1,1,2,3,1]
target=2

s=Solution()

res=s.countPairs(nums,target)

print(res)

class Solution:

def maximizeSquareArea(self, m: int, n: int, hFences: List[int], vFences: List[int]) -> int:

mod = (10**9)+7

ans = -1

height = set([m-1])

hFences+=[1,m]

vFences+=[1,n]

for h1 in hFences:

for h2 in hFences:

if h1!=h2:

height.add(abs(h1-h2))

if n-1 in height:

ans = n-1

for v1 in vFences:

for v2 in vFences:

if abs(v1-v2) in height:

ans = max(ans,abs(v1-v2))

return (ans**2)%mod if ans!=-1 else -1


def minimumFinishTime(tires, changeTime, numLaps):

minimum = [] # minimum[i] represents for the min time to complete i + 1 laps without changing a
tire

total = [0] * len(tires)

# the worst case is: fi = 1, ri = 2, changeTime = 10 ** 5

# this while loop will be computed for at most math.ceil(math.log2(10 ** 5 + 1)) = 17 times

while True:

for t in range(len(tires)):

total[t] += tires[t][0]

tires[t][0] *= tires[t][1]

minimum.append(min(total))

# if the minimum cost is greater than changing a new tire, we stop looping

if minimum[-1] > changeTime + minimum[0]: break

# dp

dp = [float('inf')] * numLaps

for l in range(numLaps):

for pre in range(len(minimum)):

if l - pre - 1 < 0:

dp[l] = min(dp[l], minimum[pre])

break

dp[l] = min(dp[l], minimum[pre] + dp[l - pre - 1] + changeTime)

return dp[-1]

tires = [[2,3],[3,4]]

changeTime = 5

numLaps = 4

res=minimumFinishTime(tires, changeTime, numLaps)

print(res)
class Solution:

def firstPalindrome(self,words):

for word in words:

if word==word[::-1]:

return word

return ""

words = ["abc","car","racecar","cool"]

s=Solution()

res=s.firstPalindrome(words)

print(res)

class Solution:

def stringIndices(self, wordsContainer, wordsQuery):

trie = {}

for i,word in enumerate(wordsContainer):

spot = trie

if None not in spot or spot[None][1] > len(word):

spot[None] = (i,len(word))

for c in reversed(word):

if c not in spot:

spot[c] = {}

spot = spot[c]

if None not in spot or spot[None][1] > len(word):

spot[None] = (i,len(word))

ans = []

for word in wordsQuery:

spot = trie

for c in reversed(word):

if c not in spot:
break

spot = spot[c]

ans.append(spot[None][0])

return ans

wordsContainer = ["abcd","bcd","xbcd"]

wordsQuery = ["cd","bcd","xyz"]

s=Solution()

result=s.stringIndices(wordsContainer, wordsQuery)

print(result)

class MajorityChecker(object):

def __init__(self, arr):

self.arr = arr

def query(self, left, right, threshold):

candidate = 0

count = 0

for i in range(left, right+1):

if count == 0:

candidate = self.arr[i]

count = 1

elif candidate == self.arr[i]:

count += 1

else:

count -= 1

count = 0

for i in range(left, right+1):


if candidate == self.arr[i]:

count += 1

if count >= threshold:

return candidate

return -1

s=MajorityChecker.query(2, 3, 2)

print(s)

class Solution:

def minMovesToCaptureTheQueen(self, a, b, c, d, e, f):

# rock and queen in the same row or col

if a == e: # same row

if a == c and (d - b) * (d - f) < 0: # bishop on the same row and between rock and queen

return 2

else:

return 1

elif b == f: # same col

if b == d and (c - a) * (c - e) < 0:

return 2

else:

return 1

# bishop and queen in the same diagonal

elif c - e == d - f: # \ diagonal

if a - e == b - f and (a - c) * (a - e) < 0:

return 2

else:

return 1

elif c - e == f - d: # / diagonal

if a - e == f - b and (a - c) * (a - e) < 0:
return 2

else:

return 1

return 2

a,b,c,d,e,f = 1,1,8,8,2,3

s=Solution()

res=s.minMovesToCaptureTheQueen(a,b,c,d,e,f)

print(res)

class Solution:

def totalSteps(self, nums):

st = []

ans = 0

for i in nums:

t=0

while st and st[-1][0] <= i:

t = max(t, st.pop()[1])

x=0

if st:

x = t+1

st.append([i, x])

ans = max(ans, x)

return ans

nums = [4,7,3,6,11,8,5,11]

s=Solution()

res=s.totalSteps(nums)

print(res)
class Solution:

def arrayStringsAreEqual(self, word1: List[str], word2: List[str]) -> bool:

a=''.join(word1)

b=''.join(word2)

return a==b

class Solution:

def maxWidthOfVerticalArea(self, points: list[list[int]]) -> int:

x_coordinates = sorted(set(point[0] for point in points))

max_diff = 0

prev_x = None

for x in x_coordinates:

if prev_x is not None:

max_diff = max(max_diff, x - prev_x)

prev_x = x

return max_diff

def countPairs( nums, target) :

nums.sort()

count = 0

left = 0

right = len(nums)-1

while(left < right):

if(nums[left] + nums[right] < target):

count += 1 # update the count


print(count)

left += 1 # increment the left

else: # else

right -= 1 # decrement the right

return count

nums = [-1,1,2,3,1]

target = 2

result=countPairs(nums,target)

print(result)

You might also like