Code3 0
Code3 0
max_so_far = arr[0]
max_ending_here = arr[0]
for i in range(0,len(arr)):
max_ending_here = max(arr[i],max_ending_here+arr[i])
max_so_far = max(max_so_far,max_ending_here)
print(max_so_far)
#alternate:
maxhere,maxsofar = 0,float("-inf")
for i in range(len(arr)):
maxhere = maxhere + arr[i]
maxsofar = max(maxsofar,maxhere)
if maxhere <0:
maxhere = 0
print(maxsofar)
def kthlargestelement(arr,l,r,k):
if (k > 0 and k <= r-l+1):
pos = partition(arr,l,r)
if pos-l == k-1:
return arr[pos]
##reverse a int
n=123
rev = 0
while n!=0:
a = n%10
rev = rev*10 + a
n = n//10
print(rev)
#reverse string
s = ["h","e","l","l","o"]
str = ""
for i in s:
str = i+str
print(f"reverse string {str}")
left = 0
right = len(s)-1
s = "momo"
def reverse(s):
str = ""
for i in s:
str = i+str
return s
if reverse(s) == s:
print("yes")
else:
print("no")
check_string = "hello"
count = {}
for s in check_string:
if s in count:
count[s] += 1
else:
count[s] = 1
#TWO SUMS
nums = [2,3,4]
target = 6
ans = []
for i in range(len(nums)):
x = target - nums[i]
if x in nums:
x_index = nums.index(x)
if i != x_index:
ans.append(i)
ans.append(x_index)
print(f"Two sum:{ans}")
break
else:
i = i+1
#Given a list of words, can you find out the frequency of each word?
from collections import Counter as c
from typing import Counter
lst = ['w','t','t']
lst1 = c(lst)
print(lst1)
for k,v in lst1.items():
print(f"for key {k} : {v} no of occurance")
#Given a list of numbers [1,2,3,4,5,6,7,8,9], print all the pairs for which the
summation of index positions is equal to 10
array = [1,2,3,4,5,6,7,8,9]
sum_of_index = 10
for i in range(int(sum_of_index/2)):
print(i)
if i < len(array) and sum_of_index-i-1 < len(array):
print((array[i], array[sum_of_index-i-1]))
s = "aa"
t="a"
len_s =len(s)
len_t =len(t)
s = c(s)
t = c(t)
lst = [2,4,3,5,2,6,3]
list_count= Counter(lst)
max_value = max(list_count.values())
print(list_count)
for k,v in list_count.items():
if v == max_value:
print(k)
print("-"*10)
#Given Two Arrays. Identify the common elements or not common element within them
A= [3, 2, 1]
B=[1, 4, 2]
A =Counter(A)
B= Counter(B)
#common
# not common
K = [k for k,v in A.items() if k not in B]
print(K)
print('-'*20)
#Given a string s, find the length of the longest substring without repeating
characters.
s = 'abcabcbc'
res = 0
word = ''
for i in s:
if i not in word:
word = word+i
if len(word) > res:
res = len(word)
else:
word = word[word.find(i): ] + i
print
print(res)
#Closest Sum
MAX_VAL = 1000000000
#Given an array nums containing n distinct numbers in the range [0, n],
# return the only number in the range that is missing from the array.
nums = [3,0,1]
n = len(nums)
print(f"here: {n * (n+1) / 2 - sum(nums)}")
#2nd method
s = 0
s1 = 0
for i in range(len(nums)+1):
s = s+i
for i in nums:
s1 = s1 + i
print(s-s1)
print('-'*20)
#Given a string s, find the first non-repeating character in it and return its
index.
# If it does not exist, return -1.
s = "aab"
raw = {}
rep = {}
for i in range(len(s)):
if s[i] not in rep:
if s[i] not in raw:
raw[s[i]] = i
else:
raw.pop(s[i])
rep[s[i]] = 1
print(raw)
if len(raw) > 0:
print(min(raw.values()))
else:
print(-1)
#Given a string paragraph and a string array of the banned words banned, return
the most frequent word that is not banned.
# It is guaranteed there is at least one word that is not banned, and that the
answer is unique.
import re
paragraph = "Bob hit a ball, the hit BALL flew far after it was hit."
banned = ["hit"]
paragraph=re.split('\W+',paragraph.lower())
words=Counter(paragraph)
for word in words.most_common():
if word[0] not in banned:
print(word[0])
break
# stack = []
# for char in s:
# if char in "({[":
# stack.append(char)
# elif char in ")}]":
# if stack == []:
# return False
# else:
# token = stack.pop(-1)
# if token == "(" and char != ")":
# return False
# elif token == "{" and char != "}":
# return False
# elif token == "[" and char != "]":
# return False
#Given two sorted arrays nums1 and nums2 of size m and n respectively, return the
median of the two sorted arrays.
#Using merge_sort
nums1 = [1,3]
nums2 = [2]
store = []
i = j = 0
k = len(nums1)
l = len(nums2)
while i < k:
store.append(nums1[i])
i = i+1
while j < l:
store.append(nums2[j])
j = j+1
ln = len(store)
if ln%2 !=0:
print(int(store[ln//2])/1.0)
else:
print(int(store[ln//2]) + int(store[ln-1//2]))/2.0
# # carry = 0
# # while l1 or l2 or carry: # not none
# # if l1 is not None:
# # carry += l1.val
# # l1 = l1.next #increase value of l1
# # if l2 is not None:
# # carry+= l2.val
# # l2 = l2.next
# # curr.next = ListNode(carry%10) #retur remainder of division
# # curr = curr.next
# # carry = carry//10 #returns floor value of division
# # return resultlist.next
# dummy = ListNode(0)
# cur = dummy
# while l1 and l2:
# if l1.val <= l2.val:
# cur.next = l1
# l1 = l1.next
# else:
# cur.next = l2
# l2 = l2.next
# cur = cur.next
# cur.next = l1 or l2
# return dummy.next
#Return the maximum profit you can achieve from this transaction. If you cannot
achieve any profit, return 0.
prices = [7,1,5,3,6,4]
n=len(prices)
for i in range(n-1):
prices[i]=prices[i+1]-prices[i]
print(prices)
# kadane Algo
MaxSum=0
Sum=0
for i in range(n-1):
Sum+=prices[i]
MaxSum=max(MaxSum,Sum)
if Sum<0:
Sum=0
if MaxSum<=0:
print("0")
print(MaxSum)
freq = Counter(nums)
degree = max(freq.values())
print(degree)
if degree == 1:
print('1')
solution = [n for n in freq if freq[n] == degree]
print(solution)
s = "aba"
if s == s[::-1]:
print('True')
begin = 0
end = len(s) - 1
else:
left_removal = s[begin+1:end+1]
right_removal = s[begin:end]
def helper(s, l, r) :
while l >= 0 and r < len(s) and s[l] == s[r] :
l -= 1
r += 1
return s[l+1:r]
ans = ''
for i in range(len(s)):
temp = helper(s, i, i)
if len(temp) > len(ans):
ans = temp
temp = helper(s, i, i+1)
if len(temp) > len(ans):
ans = temp
print(f"palindromic:{ans}")
#Write a function to find the longest common prefix string amongst an array of
strings.
#If there is no common prefix, return an empty string "".
# Input: strs = ["flower","flow","flight"]
# Output: "fl"
strs = ["flower","flow","flight"]
letters = list(zip(*strs)) # here we bring sequence of our strings to the
following format: [('f', 'f', 'f'), ...] - for sequence ["football", "fight",
"four"]
longest = [] # variable for the future result
for el in letters:
if len(set(el)) == 1: # if the length of a set is 1, then we admit that all
letters are the same
longest.append(el[0]) # use list, not string cause string will be
recreated again ang again and algorithm will take O(n*n) instead of O(n)
else: # if our letters are not equal, we are breaking from "for loop"
break
print(''.join(longest)) if longest else print('') # if longest is not empty - we
join it and return otherwise we return ""
# res = ""
# for i in range(len(min(strs))):
# for s in strs:
# if s[i] != strs[0][i]:
# print(res)
# break
# res += strs[0][i]
# print(res)
l = r = 1
#Remove Element
nums = [3,2,2,3]
val = 3
nums = [5,7,7,8,8,10]
target = 8
l = 0
r = len(nums)-1
while(l<=r):
if nums[l] != target:
l +=1
if nums[r] != target:
r -=1
#if not found
#print([-1,-1])
nums = [1,3,5,6]
target = 5
left = 0
right = len(nums)-1
while left <= right:
pivot = left + (right - left)//2
if nums[pivot]==target:
print(pivot)
break
elif nums[pivot] > target and nums[pivot-1]< target:
print(pivot)
break
elif nums[pivot] > target:
right = pivot-1
else:
left = pivot+1
#print(right+1)
arr = [4,3,1,2,3,4,5,7,5,3,2,4]
N = 4
newarr = []
for i in range(len(arr)-1):
if(arr[i]+1 == arr[i+1]):
newarr += [arr[i]]
if(len(newarr) == N):
break
else:
newarr = []
print(newarr)
#find mejority
print(m)
count = 0
for key in m:
# Function calling
findMajority(arr, n)
# Driver code
list1 = [1,2,5]
list2 = [2,4,6]
# Function calling
merge_lists(list1, list2)
def missing_number(nums):
n = len(nums)
total = n*(n+1)/2
sum_nums = sum(nums)
if total == sum_nums:
return 0
else:
return (total - sum_nums)
# Driver code
nums = [0,1,2,4,5]
# Function calling
print(missing_number(nums))
def find_repeat(w):
if len(w) == 0:
return None
if w[0] in w[1:]:
return w[0]
find_repeat(w[1:])
# Driver code
input = "interviewquery"
# Function calling
print(find_repeat(input))
#String Mapping
m = dict()#create dictionary
for c1, c2 in zip(string1, string2):
if c1 not in m.keys():
m[c1] = c2
elif m[c1] != c2:
return False
return True
# Driver code
string1 = 'qwe'
string2 = 'asd'
# Function calling
print(str_map(string1, string2))
#shift string
return False
# Driver code
a = 'abcde'
b = 'cdeab'
# Function calling
print(can_shift(a, b))
def palindrome(input):
dict = {}
for i in input:
if i in dict:
dict[i]+= 1
else:
dict[i] = 1
flag = 0
for i in dict.values():
if i%2 != 0:
flag += 1
if flag > 1:
return False
return True
# Driver code
str = 'carerac'
# Function calling
print(palindrome(str))
#Array Partition
# Input: nums = [1,4,3,2]
# Output: 4
# Explanation: All possible pairings (ignoring the ordering of elements) are:
# 1. (1, 4), (2, 3) -> min(1, 4) + min(2, 3) = 1 + 2 = 3
# 2. (1, 3), (2, 4) -> min(1, 3) + min(2, 4) = 1 + 2 = 3
# 3. (1, 2), (3, 4) -> min(1, 2) + min(3, 4) = 1 + 3 = 4
# So the maximum possible sum is 4.
nums = [1,4,3,2]
print(sum(sorted(nums)[::2]))
l = 0
r = len(numbers)-1
while l < r:
if numbers[l]+numbers[r] == target:
print(l+1,r+1)
break
if numbers[l] + numbers[r] < target:
l = l+1
else:
r=r-1
#Remove Element
# Input: nums = [0,1,2,2,3,0,4,2], val = 2
# Output: 5, nums = [0,1,4,0,3,_,_,_]
nums = [0,1,2,2,3,0,4,2]
val = 2
k = 0
for i in range(len(nums)):
if nums[i] != val:
nums[k] = nums[i]
k+=1
print(k)
# Input: s = "00110011"
# Output: 6
# Explanation: There are 6 substrings that have equal number of consecutive 1's
and 0's: "0011", "01", "1100", "10", "0011", and "01".
# Notice that some of these substrings repeat and are counted the number of times
they occur.
# Also, "00110011" is not a valid substring because all the 0's (and 1's) are not
grouped together.
s = "00110011"
acc = 1
occ=[]
res=0
for i in range(1,len(s)):
if s[i] == s[i-1]:
acc += 1
else:
occ.append(acc)
acc = 1
occ.append(acc)
print(occ)
for i in range(1,len(occ)):
res += min(occ[i],occ[i-1])
print(res)
#Given a string s, reverse only all the vowels in the string and return it.
s = "hello"
vow = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
s = list(s)
left = 0
right = len(s)-1
arr = [2,4,5,0,0,1,3,4,0,0,6]
temp_num = []
temp_zero = []
inti = 0
for i in range(len(arr)):
if arr[i] == 0:
temp_zero.append(arr[i])
inti +=1
else:
temp_num.append(arr[i])
inti +=1
for i in range(len(temp_num)):
temp_zero.append(temp_num[i])
print(temp_zero)
temp = c(string)
print(temp)
# print(total)
# item +=1
# break
# print(item)
item_cnt = 0
total = 0
print(enumerate(prices))
for i , v in enumerate(prices):
print(i)
print(v)
if total < budget and budget > v:
total += v
item_cnt += 1
print(item_cnt)
print("67")
count = {}
input = [1,3,4,2,1,4,1]
list1 = Counter(input)
maxv = max(list1.values())
print({k:maxv-v for k,v in list1.items() if v < maxv})
word1= "Mmississippi"
c = 's'
count1 = {}
for i in word1:
if i in count1:
count1[i] += 1
else:
count1[i] = 1
input_lst=[1,None,2,3,None,None,5,None]
left = 0
for i in range(len(input_lst)):
if input_lst[i] is None:
input_lst[i] = input_lst[left-1]
left+=1
else:
left+=1
print(input_lst)
#String is made of a-j and 0-9 where alphabets marks the opening and numbers as
closing
def solution(string):
ref =
{'0':'a','1':'b','2':'c','3':'d','4':'e','5':'f','6':'g','7':'h','8':'i','9':'j'}
stk = []
cnt = 0
for i in string:
if i in ref and ref[i] in stk:
stk.pop(stk.index(ref[i]))
elif i in ref and ref[i] not in stk:
cnt+=1
else:
stk.append(i)
# Driver code
string = 'ab00a'
# Function calling
print(solution(string))
def subString(string):
n = len(string)
return n*(n+1)/2
string = 'abc'
print(subString(string))
def count(s,c):
count1 = {}
for i in s:
if i in count1:
count1[i] += 1
else:
count1[i] = 1
if c in count1:
for k,v in count1.items():
if k==c:
return v
else:
pass
else:
return 0
word= "Mississippi"
c= "s"
print(count(word,c))
def return_missing_balanced_numbers(input):
my_dict = {}
for i in input:
if i in my_dict:
my_dict[i] += 1
else:
my_dict[i] = 1
return {a:max(my_dict.values())-b for (a,b) in my_dict.items() if b!=
max(my_dict.values())}
def remove_dupes(ip_list):
op_dict={}
op_list=[]
for i in ip_list:
if i not in op_dict.keys():
op_dict[i] = 1
op_list.append(i)
return op_list
ip_list=[1,1,1,2,2]
print(remove_dupes(ip_list))
def nth_lowest(inp,n):
return sorted(inp.items(), key=lambda x: (-x[1], x[0]))[n - 1][0]
dic = collections.defaultdict(list)
h =[]
def calc(names ,n ) :
for k ,v in names.items() :
dic[v].append(k)
if v not in h :
heappush(h , v )
def monotonic(arr):
inc=0
dec=0
for i in range(1,len(arr)):
if arr[i-1]< arr[i]:
inc += 1
elif arr[i-1]> arr[i]:
dec += 1
else:
inc += 1
dec += 1
if inc + 1 ==len(arr) or dec +1 ==len(arr):
return('Monotonic')
else:
return('Non-Monotonic')
lst = [7,9,5,2]
print(monotonic(lst))
def avgWordLength(words):
sum = 0
for i in range(len(words)):
sum += len(words[i])
string = "missisipi"
ctr_dict1=Counter(list1)
ctr_dict2=Counter(list2)
print(ctr_dict1)
print(ctr_dict2)
res=list((Counter(ctr_dict1) - Counter(ctr_dict2)).elements()) +
list((Counter(ctr_dict2) - Counter(ctr_dict1)).elements())
return res
lst = [None]
target = 30
srtl = sorted(lst)
sum = 0
count = 0
for i in range(len(srtl)):
sum += srtl[i]
if sum <= target:
count +=1
print(count)
array=[['D'],['A','B'],['A','C'],['C','A']]
def find_followers(arr):
dict = {}
for i in arr:
if i[0] not in dict:
dict[i[0]] = len(i)-1
else:
dict[i[0]] += len(i)-1
return dict
print(find_followers(array))
def validate(ip):
valid_digit=set('0123456789')
a=ip.split('.')
if len(a)!=4:
return False
for x in a:
if not x.isdigit():
return False
i=int(x)
if i < 0 or i> 255:
return False
return True
print(validate('127.0.0.0'))