code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
# Python3 program to find all pairs
# such that a % b = k.
# Utility function to find the divisors
# of n and store in vector v[]
import math as mt
def findDivisors(n):
v = []
# Vector is used to store the divisors
for i in range(1, mt.floor(n**(.5)) + 1):
if (n % i == 0):
# If n is a square number, push
# only one occurrence
if (n / i == i):
v.append(i)
else:
v.append(i)
v.append(n // i)
return v
# Function to find pairs such that (a%b = k)
def printPairs(arr, n, k):
# Store all the elements in the map
# to use map as hash for finding elements
# in O(1) time.
occ = dict()
for i in range(n):
occ[arr[i]] = True
isPairFound = False
for i in range(n):
# Print all the pairs with (a, b) as
# (k, numbers greater than k) as
# k % (num (> k)) = k i.e. 2%4 = 2
if (occ[k] and k < arr[i]):
print("(", k, ",", arr[i], ")", end = " ")
isPairFound = True
# Now check for the current element as 'a'
# how many b exists such that a%b = k
if (arr[i] >= k):
# find all the divisors of (arr[i]-k)
v = findDivisors(arr[i] - k)
# Check for each divisor i.e. arr[i] % b = k
# or not, if yes then print that pair.
for j in range(len(v)):
if (arr[i] % v[j] == k and
arr[i] != v[j] and
occ[v[j]]):
print("(", arr[i], ",", v[j],
")", end = " ")
isPairFound = True
return isPairFound
# Driver Code
arr = [3, 1, 2, 5, 4]
n = len(arr)
k = 2
if (printPairs(arr, n, k) == False):
print("No such pair exists")
# This code is contributed by mohit kumar
|
linear
|
linear
|
# Python3 program to convert an array
# in reduced form
def convert(arr, n):
# Create a temp array and copy contents
# of arr[] to temp
temp = [arr[i] for i in range (n) ]
# Sort temp array
temp.sort()
# create a map
umap = {}
# One by one insert elements of sorted
# temp[] and assign them values from 0
# to n-1
val = 0
for i in range (n):
umap[temp[i]] = val
val += 1
# Convert array by taking positions from umap
for i in range (n):
arr[i] = umap[arr[i]]
def printArr(arr, n):
for i in range(n):
print(arr[i], end = " ")
# Driver Code
if __name__ == "__main__":
arr = [10, 20, 15, 12, 11, 50]
n = len(arr)
print("Given Array is ")
printArr(arr, n)
convert(arr , n)
print("\n\nConverted Array is ")
printArr(arr, n)
# This code is contributed by Abhishek Gupta
|
linear
|
nlogn
|
# Python program to return the maximum occurring character in the input string
ASCII_SIZE = 256
def getMaxOccurringChar(str):
# Create array to keep the count of individual characters
# Initialize the count array to zero
count = [0] * ASCII_SIZE
# Utility variables
max = -1
c = ''
# Traversing through the string and maintaining the count of
# each character
for i in str:
count[ord(i)] += 1
for i in str:
if max < count[ord(i)]:
max = count[ord(i)]
c = i
return c
# Driver program to test the above function
str = "sample string"
print("Max occurring character is", getMaxOccurringChar(str))
# Although this program can be written in atmost 3 lines in Python
# the above program has been written for a better understanding of
# the reader
# Shorter version of the program
# import collections
# str = "sample string"
# print "Max occurring character is " +
# collections.Counter(str).most_common(1)[0][0]
# This code has been contributed by Bhavya Jain
|
constant
|
linear
|
# Python program to print all words that
# have the same unique character set
# Function to group all strings with same characters
from collections import Counter
def groupStrings(input):
# traverse all strings one by one
# dict is an empty dictionary
dict={}
for word in input:
# sort the current string and take it's
# sorted value as key
# sorted return list of sorted characters
# we need to join them to get key as string
# Counter() method returns dictionary with frequency of
# each character as value
wordDict=Counter(word)
# now get list of keys
key = wordDict.keys()
# now sort these keys
key = sorted(key)
# join these characters to produce key string
key = ''.join(key)
# now check if this key already exist in
# dictionary or not
# if exist then simply append current word
# in mapped list on key
# otherwise first assign empty list to key and
# then append current word in it
if key in dict.keys():
dict[key].append(word)
else:
dict[key]=[]
dict[key].append(word)
# now traverse complete dictionary and print
# list of mapped strings in each key separated by ,
for (key,value) in dict.items():
print (','.join(dict[key]))
# Driver program
if __name__ == "__main__":
input=['may','student','students','dog','studentssess','god','cat','act','tab','bat','flow','wolf','lambs','amy','yam','balms','looped','poodle']
groupStrings(input)
|
linear
|
linear
|
# Python3 program to find out the second
# most repeated word
# Function to find the word
def secMostRepeated(seq):
# Store all the words with its occurrence
occ = {}
for i in range(len(seq)):
occ[seq[i]] = occ.get(seq[i], 0) + 1
# Find the second largest occurrence
first_max = -10**8
sec_max = -10**8
for it in occ:
if (occ[it] > first_max):
sec_max = first_max
first_max = occ[it]
elif (occ[it] > sec_max and
occ[it] != first_max):
sec_max = occ[it]
# Return with occurrence equals
# to sec_max
for it in occ:
if (occ[it] == sec_max):
return it
# Driver code
if __name__ == '__main__':
seq = [ "ccc", "aaa", "ccc",
"ddd", "aaa", "aaa" ]
print(secMostRepeated(seq))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
from collections import defaultdict
import sys
# Python program to find the smallest element
# with frequency exactly k.
def smallestKFreq(arr, n, k):
mp = defaultdict(lambda : 0)
# Map is used to store the count of
# elements present in the array
for i in range(n):
mp[arr[i]] += 1
# Traverse the map and find minimum
# element with frequency k.
res = sys.maxsize
res1 = sys.maxsize
for key,values in mp.items():
if values == k:
res = min(res, key)
return res if res != res1 else -1
# Driver code
arr = [2, 2, 1, 3, 1]
k = 2
n = len(arr)
print(smallestKFreq(arr, n, k))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python3 code to find number
# occurring prime number of
# times with frequency >= k
# Function to find number
# with prime occurrences
def primeOccurrences(arr, k):
map = {}
# Insert values and their frequencies
for val in arr:
freq = 0
if val in map :
freq = map[val]
freq += 1
else :
freq = 1
map[val] = freq
# Traverse map and find elements
# with prime frequencies and
# frequency at least k
for entry in map :
value = map[entry]
if isPrime(value) and value >= k:
print(entry)
# Check if the number of occurrences
# are primes or not
def isPrime(n):
if (n > 2 and not n % 2) or n == 1:
return False
for i in range(3, int(n**0.5 + 1), 2):
if not n % i:
return False
return True
# Driver code
arr = [ 11, 11, 11, 23, 11, 37,
37, 51, 51, 51, 51, 51 ]
k = 2
primeOccurrences(arr, k)
# This code is contributed by Ansu Kumari.
|
linear
|
linear
|
# Python3 implementation to find k numbers
# with most occurrences in the given array
# Function to print the k numbers with
# most occurrences
def pr_N_mostFrequentNumber(arr, N, K):
mp = {}
for i in range(N):
if arr[i] in mp:
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
a = [0] * (len(mp))
j = 0
for i in mp:
a[j] = [i, mp[i]]
j += 1
a = sorted(a, key=lambda x: x[0],
reverse=True)
a = sorted(a, key=lambda x: x[1],
reverse=True)
# Display the top k numbers
print(K, "numbers with most occurrences are:")
for i in range(K):
print(a[i][0], end=" ")
# Driver code
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
N = 8
K = 2
# Function call
pr_N_mostFrequentNumber(arr, N, K)
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
|
logn
|
nlogn
|
def print_N_mostFrequentNumber(arr, N, K):
# HashMap to store count of the elements
count = {}
# Array to store the elements according
# to their frequency
freq = [[] for i in range(len(arr) + 1)]
for n in arr:
count[n] = 1 + count.get(n, 0)
for n, c in count.items():
freq.append(n)
res = []
# if K elements have been printed
for i in range(len(freq)-1, 0, -1):
for n in freq[i]:
res.append(n)
if len(res) == K:
return res[-1::-1]
# Driver's code
if __name__ == "__main__":
arr = [3, 1, 4, 4, 5, 2, 6, 1]
N = len(arr)
K = 2
# Function call
print(print_N_mostFrequentNumber(arr, N, K))
|
linear
|
linear
|
# Python3 program to find first repeating
# element in arr[]
# This function prints the first repeating
# element in arr[]
def printFirstRepeating(arr, n):
# Initialize index of first repeating element
Min = -1
# Creates an empty hashset
myset = dict()
# Traverse the input array from right to left
for i in range(n - 1, -1, -1):
# If element is already in hash set,
# update Min
if arr[i] in myset.keys():
Min = i
else: # Else add element to hash set
myset[arr[i]] = 1
# Print the result
if (Min != -1):
print("The first repeating element is",
arr[Min])
else:
print("There are no repeating elements")
# Driver Code
arr = [10, 5, 3, 4, 3, 5, 6]
n = len(arr)
printFirstRepeating(arr, n)
# This code is contributed by Mohit kumar 29
|
linear
|
linear
|
# Python3 program to find first
# repeating element in arr[]
# This function prints the
# first repeating element in arr[]
def printFirstRepeating(arr, n):
# This will set k=1, if any
# repeating element found
k = 0
# max = maximum from (all elements & n)
max = n
for i in range(n):
if (max < arr[i]):
max = arr[i]
# Array a is for storing
# 1st time occurrence of element
# initialized by 0
a = [0 for i in range(max + 1)]
# Store 1 in array b
# if element is duplicate
# initialized by 0
b = [0 for i in range(max + 1)]
for i in range(n):
# Duplicate element found
if (a[arr[i]]):
b[arr[i]] = 1
k = 1
continue
else:
# Storing 1st occurrence of arr[i]
a[arr[i]] = i+1
if (k == 0):
print("No repeating element found")
else:
min = max + 1
for i in range(max + 1):
# Trace array a & find repeating
# element with min index
if (a[i] and (min > (a[i])) and b[i]):
min = a[i]
print(arr[min-1])
# Driver code
arr = [10, 5, 3, 4, 3, 5, 6]
N = len(arr)
printFirstRepeating(arr, N)
# This code is contributed by avanitrachhadiya2155
|
linear
|
linear
|
# Python3 Find the sum of all non-repeated
# elements in an array
# Find the sum of all non-repeated elements
# in an array
def findSum(arr, n):
# sort all elements of array
arr.sort()
sum = arr[0]
for i in range(0,n-1):
if (arr[i] != arr[i+1]):
sum = sum + arr[i+1]
return sum
# Driver code
def main():
arr= [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(findSum(arr, n))
if __name__ == '__main__':
main()
# This code is contributed by 29AjayKumar
|
constant
|
nlogn
|
# Python3 Find the sum of all
# non- repeated elements in an array
# Find the sum of all non-repeated
# elements in an array
def findSum(arr, n):
s = set()
sum = 0
# Hash to store all element
# of array
for i in range(n):
if arr[i] not in s:
s.add(arr[i])
for i in s:
sum = sum + i
return sum
# Driver code
arr = [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(findSum(arr, n))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python program for the above approach
from collections import Counter
# Function to return the sum of distinct elements
def sumOfElements(arr, n):
# Counter function is used to
# calculate frequency of elements of array
freq = Counter(arr)
# Converting keys of freq dictionary to list
lis = list(freq.keys())
# Return sum of list
return sum(lis)
# Driver code
if __name__ == "__main__":
arr = [1, 2, 3, 1, 1, 4, 5, 6]
n = len(arr)
print(sumOfElements(arr, n))
# This code is contributed by vikkycirus
|
linear
|
linear
|
# Python3 program to find first
# non-repeating element.
def firstNonRepeating(arr, n):
# Loop for checking each element
for i in range(n):
j = 0
# Checking if ith element is present in array
while(j < n):
if (i != j and arr[i] == arr[j]):
break
j += 1
# if ith element is not present in array
# except at ith index then return element
if (j == n):
return arr[i]
return -1
# Driver code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
# This code is contributed by Anant Agarwal.
|
constant
|
quadratic
|
# Efficient Python3 program to find first
# non-repeating element.
from collections import defaultdict
def firstNonRepeating(arr, n):
mp = defaultdict(lambda: 0)
# Insert all array elements in hash table
for i in range(n):
mp[arr[i]] += 1
# Traverse array again and return
# first element with count 1.
for i in range(n):
if mp[arr[i]] == 1:
return arr[i]
return -1
# Driver Code
arr = [9, 4, 9, 6, 7, 4]
n = len(arr)
print(firstNonRepeating(arr, n))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python3 program to print k-th distinct
# element in a given array
# Returns k-th distinct
# element in arr.
def printKDistinct(arr, n, k):
dist_count = 0
for i in range(n):
# Check if current element is
# present somewhere else.
j = 0
while j < n:
if (i != j and arr[j] == arr[i]):
break
j += 1
# If element is unique
if (j == n):
dist_count += 1
if (dist_count == k):
return arr[i]
return -1
# Driver Code
ar = [1, 2, 1, 3, 4, 2]
n = len(ar)
k = 2
print(printKDistinct(ar, n, k))
# This code is contributed by Mohit Kumar
|
constant
|
quadratic
|
# Python3 program to print k-th
# distinct element in a given array
def printKDistinct(arr, size, KthIndex):
dict = {}
vect = []
for i in range(size):
if(arr[i] in dict):
dict[arr[i]] = dict[arr[i]] + 1
else:
dict[arr[i]] = 1
for i in range(size):
if(dict[arr[i]] > 1):
continue
else:
KthIndex = KthIndex - 1
if(KthIndex == 0):
return arr[i]
return -1
# Driver Code
arr = [1, 2, 1, 3, 4, 2]
size = len(arr)
print(printKDistinct(arr, size, 2))
# This code is contributed
# by Akhand Pratap Singh
|
linear
|
linear
|
# Simple Python 3 program to find
# pairs of positive and negative
# values present in an array.
# Print pair with negative and
# positive value
def printPairs(arr, n):
v = []
# For each element of array.
for i in range(n):
# Try to find the negative value
# of arr[i] from i + 1 to n
for j in range(i + 1, n):
# If absolute values are
# equal print pair.
if (abs(arr[i]) == abs(arr[j])):
v.append(abs(arr[i]))
# If size of vector is 0, therefore
# there is no element with positive
# negative value, print "0"
if (len(v) == 0):
return
# Print the pair with negative
# positive value.
for i in range(len(v)):
print(-v[i], "", v[i], end=" ")
# Driver Code
if __name__ == "__main__":
arr = [4, 8, 9, -4, 1, -1, -8, -9]
n = len(arr)
# Function call
printPairs(arr, n)
# This code is contributed
# by ChitraNayal
|
linear
|
quadratic
|
# Python3 program to find pairs of
# positive and negative values present in
# an array.
# Print pair with negative and
# positive value
def printPairs(arr, n):
s = set()
ret = []
# For each element of array.
for i in arr:
if abs(i) in s:
ret.append(abs(i))
else:
s.add(abs(i))
ret.sort()
for i in range(0, len(ret)):
print(-ret[i], "", ret[i], end=" ")
# Driver Code
if __name__ == "__main__":
arr = [4, 8, 9, -4, 1, -1, -8, -9]
n = len(arr)
# Function call
printPairs(arr, n)
# This code is contributed by RohitOberoi
|
linear
|
linear
|
# Python3 program to find pairs of
# positive and negative values present in
# an array
def printPairs(arr, n):
hs = set()
ans = []
for i in range(n):
if (arr[i] * -1) in hs:
if (arr[i] < 0):
print(arr[i], end=" ")
print((arr[i] * -1), end=" ")
else:
print((arr[i] * -1), end=" ")
print(arr[i], end=" ")
hs.add(arr[i])
return
# Driver code
arr = [4, 8, 9, -4, 1, -1, -8, -9]
n = len(arr)
# Function call
printPairs(arr, n)
# This code is contributed by shinjanpatra.
|
linear
|
linear
|
# Python3 program to count
# divisible pairs.
def countDivisibles(arr, n) :
res = 0
# Iterate through all pairs
for i in range(0, n) :
for j in range(i+1, n) :
# Increment count if one divides
# other
if (arr[i] % arr[j] == 0 or
arr[j] % arr[i] == 0) :
res+=1
return res
# Driver code
if __name__=='__main__':
a = [1, 2, 3, 9]
n = len(a)
print(countDivisibles(a, n) )
# this code is contributed by
# Smitha Dinesh Semwal
|
constant
|
quadratic
|
# Python program to count divisible pairs.
import math
# Function to return the total count of pairs such
# that arr[i]%arr[j]==0
def total_count(arr, N):
count = 0
# Storing the occurrence of every element in array
# in dictionary
freq = {}
for i in range(0, N):
if arr[i] not in freq:
freq[arr[i]] = 1
else:
freq[arr[i]] += 1
# Iterating through every element and finding all the
# divisors of that element and then checking how many
# of them are present in array arr[]
for i in range(0, N):
for j in range(1, int(math.sqrt(arr[i]))+1):
if arr[i] % j == 0:
if arr[i] == j*j:
# If divisors are equal, then take only
# one as it will be perfect square root
# of arr[i]
count += freq[j]
else:
# Else take both j and arr[i]/j as both
# will be divisors
count += freq[j]+freq[arr[i]/j]
# As all the elements is divisible by itself and
# is counted in freq[] so reducing its count
count = count-1
# returning final count
return count
arr = [1, 2, 3, 9]
N = len(arr)
print(total_count(arr, N))
# This code is contributed by lokesh (lokeshmvs21).
|
constant
|
quadratic
|
# Python3 implementation to find the
# longest subarray with sum divisible by k
# Function to find the longest
# subarray with sum divisible by k
def longestSubarrWthSumDivByK(arr, n, k):
# unordered map 'um' implemented
# as hash table
um = {}
# 'mod_arr[i]' stores (sum[0..i] % k)
mod_arr = [0 for i in range(n)]
max_len = 0
curr_sum = 0
# Traverse arr[] and build up
# the array 'mod_arr[]'
for i in range(n):
curr_sum += arr[i]
# As the sum can be negative,
# taking modulo twice
mod_arr[i] = ((curr_sum % k) + k) % k
# If true then sum(0..i) is
# divisible by k
if (mod_arr[i] == 0):
# Update 'max_len'
max_len = i + 1
# If value 'mod_arr[i]' not present in
# 'um' then store it in 'um' with index
# of its first occurrence
elif (mod_arr[i] not in um):
um[mod_arr[i]] = i
else:
# If true, then update 'max_len'
if (max_len < (i - um[mod_arr[i]])):
max_len = i - um[mod_arr[i]]
# Return the required length of longest subarray
# with sum divisible by 'k'
return max_len
# Driver Code
if __name__ == '__main__':
arr = [2, 7, 6, 1, 4, 5]
n = len(arr)
k = 3
print("Length =",
longestSubarrWthSumDivByK(arr, n, k))
# This code is contributed by Surendra_Gangwar, updated by Kshitij Dwivedi
|
linear
|
linear
|
# function to find the longest subarray
# with sum divisible by k
def longestSubarrWthSumDivByK(arr, n, k):
# unordered map 'um' implemented as
# hash table
um = {}
max_len = 0
curr_sum = 0
for i in range(n):
curr_sum += arr[i]
mod = ((curr_sum % k) + k) % k
# if true then sum(0..i) is divisible by k
if mod == 0:
# update 'max_len'
max_len = i + 1
# if value 'mod_arr[i]' not present in 'um'
# then store it in 'um' with index of its
# first occurrence
elif mod in um.keys():
if max_len < (i - um[mod]):
max_len = i - um[mod]
else:
um[mod] = i
# return the required length of longest subarray with
# sum divisible by 'k'
return max_len
arr = [2, 7, 6, 1, 4, 5]
n = len(arr)
k = 3
print("Length =", longestSubarrWthSumDivByK(arr, n, k))
# This code is contributed by amreshkumar3, and updated by Kshitij Dwivedi
|
linear
|
linear
|
# Python3 Program to find the subarray with
# no pair sum divisible by K
# function to find the subarray with
# no pair sum divisible by k
def subarrayDivisibleByK(arr, n, k) :
# hash table to store the remainders
# obtained on dividing by K
mp = [0] * 1000
# s : starting index of the
# current subarray, e : ending
# index of the current subarray, maxs :
# starting index of the maximum
# size subarray so far, maxe : ending
# index of the maximum size subarray
# so far
s = 0; e = 0; maxs = 0; maxe = 0;
# insert the first element in the set
mp[arr[0] % k] = mp[arr[0] % k] + 1;
for i in range(1, n):
mod = arr[i] % k
# Removing starting elements of current
# subarray while there is an element in
# set which makes a pair with mod[i] such
# that the pair sum is divisible.
while (mp[k - mod] != 0 or (mod == 0
and mp[mod] != 0)) :
mp[arr[s] % k] = mp[arr[s] % k] - 1
s = s + 1
# include the current element in
# the current subarray the ending
# index of the current subarray
# increments by one
mp[mod] = mp[mod] + 1
e = e + 1
# compare the size of the current
# subarray with the maximum size so
# far
if ((e - s) > (maxe - maxs)) :
maxe = e
maxs = s
print ("The maximum size is {} and the "
" subarray is as follows"
.format((maxe - maxs + 1)))
for i in range(maxs, maxe + 1) :
print ("{} ".format(arr[i]), end="")
# Driver Code
k = 3
arr = [5, 10, 15, 20, 25]
n = len(arr)
subarrayDivisibleByK(arr, n, k)
# This code is contributed by
# Manish Shaw (manishshaw1)
|
linear
|
nlogn
|
# Python3 program to find special numbers
# in an array
import math as mt
# Function to find special numbers
def divisibilityCheck(arr, n):
# Storing all array elements in a hash
# and finding maximum element in array
s = dict()
max_ele = -10**9
for i in range(n):
s[arr[i]] = 1
# finding maximum element of array
max_ele = max(max_ele, arr[i])
# traversing array element and storing
# the array multiples that are present
# in s in res.
res = dict()
for i in range(n):
# Check for non-zero values only
if (arr[i] != 0):
# checking the factor of current element
for j in range(arr[i] * 2,
max_ele + 1, arr[i]):
# if factor is already part of
# array element then store it
if (j in s.keys()):
res[j] = 1
# displaying elements that are divisible
# by at least one other in array
for x in res:
print(x, end = " ")
# Driver code
arr = [ 2, 3, 8, 6, 9, 10]
n = len(arr)
divisibilityCheck(arr, n)
# This code is contributed by
# Mohit Kumar 29
|
linear
|
quadratic
|
# Python3 program to find
# three element from different
# three arrays such that
# a + b + c is equal to
# given sum
# Function to check if there
# is an element from each
# array such that sum of the
# three elements is equal to
# given sum.
def findTriplet(a1, a2, a3,
n1, n2, n3, sum):
for i in range(0 , n1):
for j in range(0 , n2):
for k in range(0 , n3):
if (a1[i] + a2[j] +
a3[k] == sum):
return True
return False
# Driver Code
a1 = [ 1 , 2 , 3 , 4 , 5 ]
a2 = [ 2 , 3 , 6 , 1 , 2 ]
a3 = [ 3 , 2 , 4 , 5 , 6 ]
sum = 9
n1 = len(a1)
n2 = len(a2)
n3 = len(a3)
print("Yes") if findTriplet(a1, a2, a3,
n1, n2, n3,
sum) else print("No")
# This code is contributed
# by Smitha
|
constant
|
cubic
|
# Python3 program to find three element
# from different three arrays such
# that a + b + c is equal to
# given sum
# Function to check if there is
# an element from each array such
# that sum of the three elements is
# equal to given sum.
def findTriplet(a1, a2, a3,
n1, n2, n3, sum):
# Store elements of first
# array in hash
s = set()
# sum last two arrays element
# one by one
for i in range(n1):
s.add(a1[i])
for i in range(n2):
for j in range(n3):
# Consider current pair and
# find if there is an element
# in a1[] such that these three
# form a required triplet
if sum - a2[i] - a3[j] in s:
return True
return False
# Driver code
a1 = [1, 2, 3, 4, 5]
a2 = [2, 3, 6, 1, 2]
a3 = [3, 24, 5, 6]
n1 = len(a1)
n2 = len(a2)
n3 = len(a3)
sum = 9
if findTriplet(a1, a2, a3,
n1, n2, n3, sum) == True:
print("Yes")
else:
print("No")
# This code is contributed by Shrikant13
|
linear
|
quadratic
|
# Python program for the above approach
# returns the length
def maxLen(arr):
# initialize result
max_len = 0
# pick a starting point
for i in range(len(arr)):
# initialize sum for every starting point
curr_sum = 0
# try all subarrays starting with 'i'
for j in range(i, len(arr)):
curr_sum += arr[j]
# if curr_sum becomes 0, then update max_len
if curr_sum == 0:
max_len = max(max_len, j-i + 1)
return max_len
# Driver's code
if __name__ == "__main__":
# test array
arr = [15, -2, 2, -8, 1, 7, 10, 13]
# Function call
print ("Length of the longest 0 sum subarray is % d" % maxLen(arr))
|
constant
|
quadratic
|
# Python program for the above approach
# Returns the maximum length
def maxLen(arr):
# NOTE: Dictionary in python is
# implemented as Hash Maps
# Create an empty hash map (dictionary)
hash_map = {}
# Initialize result
max_len = 0
# Initialize sum of elements
curr_sum = 0
# Traverse through the given array
for i in range(len(arr)):
# Add the current element to the sum
curr_sum += arr[i]
if curr_sum == 0:
max_len = i + 1
# NOTE: 'in' operation in dictionary
# to search key takes O(1). Look if
# current sum is seen before
if curr_sum in hash_map:
max_len = max(max_len, i - hash_map[curr_sum])
else:
# else put this sum in dictionary
hash_map[curr_sum] = i
return max_len
# Driver's code
if __name__ == "__main__":
# test array
arr = [15, -2, 2, -8, 1, 7, 10, 13]
# Function call
print("Length of the longest 0 sum subarray is % d" % maxLen(arr))
|
linear
|
linear
|
# Python 3 program to find length of
# the longest increasing subsequence
# whose adjacent element differ by 1
import sys
# function that returns the length
# of the longest increasing subsequence
# whose adjacent element differ by 1
def longestSubsequence(a, n):
# stores the index of elements
mp = {i:0 for i in range(13)}
# stores the length of the longest
# subsequence that ends with a[i]
dp = [0 for i in range(n)]
maximum = -sys.maxsize - 1
# iterate for all element
index = -1
for i in range(n):
# if a[i]-1 is present before
# i-th index
if ((a[i] - 1 ) in mp):
# last index of a[i]-1
lastIndex = mp[a[i] - 1] - 1
# relation
dp[i] = 1 + dp[lastIndex]
else:
dp[i] = 1
# stores the index as 1-index as we
# need to check for occurrence, hence
# 0-th index will not be possible to check
mp[a[i]] = i + 1
# stores the longest length
if (maximum < dp[i]):
maximum = dp[i]
index = i
# We know last element of sequence is
# a[index]. We also know that length
# of subsequence is "maximum". So We
# print these many consecutive elements
# starting from "a[index] - maximum + 1"
# to a[index].
for curr in range(a[index] - maximum + 1,
a[index] + 1, 1):
print(curr, end = " ")
# Driver Code
if __name__ == '__main__':
a = [3, 10, 3, 11, 4, 5,
6, 7, 8, 12]
n = len(a)
longestSubsequence(a, n)
# This code is contributed by
# Surendra_Gangwar
|
linear
|
linear
|
# python program to find length of the
# longest increasing subsequence
# whose adjacent element differ by 1
from collections import defaultdict
import sys
# function that returns the length of the
# longest increasing subsequence
# whose adjacent element differ by 1
def longestSubsequence(a, n):
mp = defaultdict(lambda:0)
# stores the length of the longest
# subsequence that ends with a[i]
dp = [0 for i in range(n)]
maximum = -sys.maxsize
# iterate for all element
for i in range(n):
# if a[i]-1 is present before i-th index
if a[i] - 1 in mp:
# last index of a[i]-1
lastIndex = mp[a[i] - 1] - 1
# relation
dp[i] = 1 + dp[lastIndex]
else:
dp[i] = 1
# stores the index as 1-index as we need to
# check for occurrence, hence 0-th index
# will not be possible to check
mp[a[i]] = i + 1
# stores the longest length
maximum = max(maximum, dp[i])
return maximum
# Driver Code
a = [3, 10, 3, 11, 4, 5, 6, 7, 8, 12]
n = len(a)
print(longestSubsequence(a, n))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python3 implementation to find longest
# subsequence such that difference between
# adjacents is one
from collections import defaultdict
# function to find longest subsequence such
# that difference between adjacents is one
def longLenSub(arr, n):
# hash table to map the array element
# with the length of the longest
# subsequence of which it is a part of
# and is the last element of that subsequence
um = defaultdict(lambda:0)
longLen = 0
for i in range(n):
# / initialize current length
# for element arr[i] as 0
len1 = 0
# if 'arr[i]-1' is in 'um' and its length
# of subsequence is greater than 'len'
if (arr[i - 1] in um and
len1 < um[arr[i] - 1]):
len1 = um[arr[i] - 1]
# f 'arr[i]+1' is in 'um' and its length
# of subsequence is greater than 'len'
if (arr[i] + 1 in um and
len1 < um[arr[i] + 1]):
len1 = um[arr[i] + 1]
# update arr[i] subsequence
# length in 'um'
um[arr[i]] = len1 + 1
# update longest length
if longLen < um[arr[i]]:
longLen = um[arr[i]]
# required longest length
# subsequence
return longLen
# Driver code
arr = [1, 2, 3, 4, 5, 3, 2]
n = len(arr)
print("Longest length subsequence =",
longLenSub(arr, n))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python3 program to find longest
# contiguous subsequence
# Returns length of the longest
# contiguous subsequence
def findLongestConseqSubseq(arr, n):
ans = 0
count = 0
# Sort the array
arr.sort()
v = []
v.append(arr[0])
# Insert repeated elements only
# once in the vector
for i in range(1, n):
if (arr[i] != arr[i - 1]):
v.append(arr[i])
# Find the maximum length
# by traversing the array
for i in range(len(v)):
# Check if the current element is
# equal to previous element +1
if (i > 0 and v[i] == v[i - 1] + 1):
count += 1
# Reset the count
else:
count = 1
# Update the maximum
ans = max(ans, count)
return ans
# Driver code
arr = [1, 2, 2, 3]
n = len(arr)
print("Length of the Longest contiguous subsequence is",
findLongestConseqSubseq(arr, n))
# This code is contributed by avanitrachhadiya2155
|
linear
|
nlogn
|
# Python program to find longest contiguous subsequence
def findLongestConseqSubseq(arr, n):
s = set()
ans = 0
# Hash all the array elements
for ele in arr:
s.add(ele)
# check each possible sequence from the start
# then update optimal length
for i in range(n):
# if current element is the starting
# element of a sequence
if (arr[i]-1) not in s:
# Then check for next elements in the
# sequence
j = arr[i]
while(j in s):
j += 1
# update optimal length if this length
# is more
ans = max(ans, j-arr[i])
return ans
# Driver code
if __name__ == '__main__':
n = 7
arr = [1, 9, 3, 10, 4, 20, 2]
print("Length of the Longest contiguous subsequence is ",
findLongestConseqSubseq(arr, n))
# Contributed by: Harshit Sidhwa
|
linear
|
linear
|
# Python program for the above approach
import bisect
def findLongestConseqSubseq(arr, N):
pq = []
for i in range(N):
# adding element from
# array to PriorityQueue
bisect.insort(pq, arr[i])
# Storing the first element
# of the Priority Queue
# This first element is also
# the smallest element
prev = pq[0]
pq.pop(0)
# Taking a counter variable with value 1
c = 1
# Storing value of max as 1
# as there will always be
# one element
max = 1
while(len(pq)):
# check if current peek
# element minus previous
# element is greater than
# 1 This is done because
# if it's greater than 1
# then the sequence
# doesn't start or is broken here
if(pq[0] - prev > 1):
# Store the value of counter to 1
# As new sequence may begin
c = 1
# Update the previous position with the
# current peek And remove it
prev = pq[0]
pq.pop(0)
# Check if the previous
# element and peek are same
elif(pq[0] - prev == 0):
# Update the previous position with the
# current peek And remove it
prev = pq[0]
pq.pop(0)
# If the difference
# between previous element and peek is 1
else:
# Update the counter
# These are consecutive elements
c = c + 1
# Update the previous position
# with the current peek And remove it
prev = pq[0]
pq.pop(0)
# Check if current longest
# subsequence is the greatest
if(max < c):
# Store the current subsequence count as
# max
max = c
return max
# Driver Code
arr = [1, 9, 3, 10, 4, 20, 2]
n = 7
print("Length of the Longest consecutive subsequence is {}".format(
findLongestConseqSubseq(arr, n)))
# This code is contributed by Pushpesh Raj
|
linear
|
nlogn
|
# Python3 implementation of longest
# continuous increasing subsequence
# Function for LIS
def findLIS(A, n):
hash = dict()
# Initialize result
LIS_size, LIS_index = 1, 0
hash[A[0]] = 1
# iterate through array and find
# end index of LIS and its Size
for i in range(1, n):
# If the desired key is not present
# in dictionary, it will throw key error,
# to avoid this error this is necessary
if A[i] - 1 not in hash:
hash[A[i] - 1] = 0
hash[A[i]] = hash[A[i] - 1] + 1
if LIS_size < hash[A[i]]:
LIS_size = hash[A[i]]
LIS_index = A[i]
# print LIS size
print("LIS_size =", LIS_size)
# print LIS after setting start element
print("LIS : ", end = "")
start = LIS_index - LIS_size + 1
while start <= LIS_index:
print(start, end = " ")
start += 1
# Driver Code
if __name__ == "__main__":
A = [ 2, 5, 3, 7, 4, 8, 5, 13, 6 ]
n = len(A)
findLIS(A, n)
# This code is contributed by sanjeev2552
|
linear
|
linear
|
# python implementation to count subsets having
# even numbers only and all are distinct
#function to count the required subsets
def countSubSets(arr, n):
us = set()
even_count = 0
# inserting even numbers in the set 'us'
# single copy of each number is retained
for i in range(n):
if arr[i] % 2 == 0:
us.add(arr[i])
# counting distinct even numbers
even_count = len(us)
# total count of required subsets
return pow(2, even_count)- 1
# Driver program
arr = [4, 2, 1, 9, 2, 6, 5, 3]
n = len(arr)
print("Numbers of subset=", countSubSets(arr,n))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python3 program to count distinct
# elements in every window of size K
import math as mt
# Counts distinct elements in window
# of size K
def countWindowDistinct(win, K):
dist_count = 0
# Traverse the window
for i in range(K):
# Check if element arr[i] exists
# in arr[0..i-1]
j = 0
while j < i:
if (win[i] == win[j]):
break
else:
j += 1
if (j == i):
dist_count += 1
return dist_count
# Counts distinct elements in all
# windows of size k
def countDistinct(arr, N, K):
# Traverse through every window
for i in range(N - K + 1):
print(countWindowDistinct(arr[i:K + i], K))
# Driver's Code
if __name__=='__main__':
arr = [1, 2, 1, 3, 4, 2, 3]
K = 4
N = len(arr)
# Function call
countDistinct(arr, N, K)
# This code is contributed by
# Mohit kumar 29
|
constant
|
quadratic
|
# An efficient Python program to
# count distinct elements in
# every window of size K
from collections import defaultdict
def countDistinct(arr, K, N):
# Creates an empty hashmap hm
mp = defaultdict(lambda: 0)
# initialize distinct element
# count for current window
dist_count = 0
# Traverse the first window and store count
# of every element in hash map
for i in range(K):
if mp[arr[i]] == 0:
dist_count += 1
mp[arr[i]] += 1
# Print count of first window
print(dist_count)
# Traverse through the remaining array
for i in range(K, N):
# Remove first element of previous window
# If there was only one occurrence,
# then reduce distinct count.
if mp[arr[i - K]] == 1:
dist_count -= 1
mp[arr[i - K]] -= 1
# Add new element of current window
# If this element appears first time,
# increment distinct element count
if mp[arr[i]] == 0:
dist_count += 1
mp[arr[i]] += 1
# Print count of current window
print(dist_count)
# Driver's code
if __name__=='__main__':
arr = [1, 2, 1, 3, 4, 2, 3]
N = len(arr)
K = 4
# Function call
countDistinct(arr, K, N)
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python3 program to find the maximum
# possible sum of a window in one
# array such that elements in same
# window of other array are unique.
# Function to return maximum sum of window
# in B[] according to given constraints.
def returnMaxSum(A, B, n):
# Map is used to store elements
# and their counts.
mp = set()
result = 0 # Initialize result
# calculating the maximum possible
# sum for each subarray containing
# unique elements.
curr_sum = curr_begin = 0
for i in range(0, n):
# Remove all duplicate instances
# of A[i] in current window.
while A[i] in mp:
mp.remove(A[curr_begin])
curr_sum -= B[curr_begin]
curr_begin += 1
# Add current instance of A[i]
# to map and to current sum.
mp.add(A[i])
curr_sum += B[i]
# Update result if current
# sum is more.
result = max(result, curr_sum)
return result
# Driver code
if __name__ == "__main__":
A = [0, 1, 2, 3, 0, 1, 4]
B = [9, 8, 1, 2, 3, 4, 5]
n = len(A)
print(returnMaxSum(A, B, n))
# This code is contributed by Rituraj Jain
|
linear
|
linear
|
# python3 program to find if
# there is a zero sum subarray
def subArrayExists(arr, N):
# traverse through array
# and store prefix sums
n_sum = 0
s = set()
for i in range(N):
n_sum += arr[i]
# If prefix sum is 0 or
# it is already present
if n_sum == 0 or n_sum in s:
return True
s.add(n_sum)
return False
# Driver's code
if __name__ == '__main__':
arr = [-3, 2, 3, 1, 6]
N = len(arr)
# Function call
if subArrayExists(arr, N) == True:
print("Found a sunbarray with 0 sum")
else:
print("No Such sub array exits!")
# This code is contributed by Shrikant13
|
linear
|
linear
|
# User defined pair class
class Pair :
first = 0
second = 0
def __init__(self, a, b) :
self.first = a
self.second = b
class GFG :
@staticmethod
def findSubArrays( arr, n) :
# Array to store all the start and end
# indices of subarrays with 0 sum
out = []
i = 0
while (i < n) :
prefix = 0
j = i
while (j < n) :
prefix += arr[j]
if (prefix == 0) :
out.append(Pair(i, j))
j += 1
i += 1
return out
# Function to print all subarrays with 0 sum
@staticmethod
def print( out) :
i = 0
while (i < len(out)) :
p = out[i]
print("Subarray found from Index " + str(p.first) + " to " + str(p.second))
i += 1
# Driver code
@staticmethod
def main( args) :
# Given array
arr = [6, 3, -1, -3, 4, -2, 2, 4, 6, -12, -7]
n = len(arr)
# Function Call
out = GFG.findSubArrays(arr, n)
# if we didn't find any subarray with 0 sum,
# then subarray doesn't exists
if (len(out) == 0) :
print("No subarray exists")
else :
GFG.print(out)
if __name__=="__main__":
GFG.main([])
# This code is contributed by aadityaburujwale.
|
constant
|
quadratic
|
# Python3 program to print all subarrays
# in the array which has sum 0
# Function to get all subarrays
# in the array which has sum 0
def findSubArrays(arr,n):
# create a python dict
hashMap = {}
# create a python list
# equivalent to ArrayList
out = []
# tracker for sum of elements
sum1 = 0
for i in range(n):
# increment sum by element of array
sum1 += arr[i]
# if sum is 0, we found a subarray starting
# from index 0 and ending at index i
if sum1 == 0:
out.append((0, i))
al = []
# If sum already exists in the map
# there exists at-least one subarray
# ending at index i with 0 sum
if sum1 in hashMap:
# map[sum] stores starting index
# of all subarrays
al = hashMap.get(sum1)
for it in range(len(al)):
out.append((al[it] + 1, i))
al.append(i)
hashMap[sum1] = al
return out
# Utility function to print
# all subarrays with sum 0
def printOutput(output):
for i in output:
print ("Subarray found from Index " +
str(i[0]) + " to " + str(i[1]))
# Driver Code
if __name__ == '__main__':
arr = [6, 3, -1, -3, 4, -2,
2, 4, 6, -12, -7]
n = len(arr)
out = findSubArrays(arr, n)
# if we did not find any subarray with 0 sum,
# then subarray does not exists
if (len(out) == 0):
print ("No subarray exists")
else:
printOutput (out)
# This code is contributed by Vikas Chitturi
|
linear
|
linear
|
# Python3 program to print subarray
# with sum as given sum
# Returns true if the there is a subarray
# of arr[] with sum equal to 'sum' otherwise
# returns false. Also, prints the result */
def subArraySum(arr, n, sum):
# Pick a starting point
for i in range(n):
curr_sum = 0
# try all subarrays starting with 'i'
for j in range(i, n):
curr_sum += arr[j]
if (curr_sum == sum):
print("Sum found between indexes", i, "and", j)
return
print("No subarray found")
# Driver Code
if __name__ == "__main__":
arr = [15, 2, 4, 8, 9, 5, 10, 23]
n = len(arr)
sum = 23
# Function Call
subArraySum(arr, n, sum)
# This code is contributed by phasing17
|
constant
|
quadratic
|
# Python3 program to print subarray with sum as given sum
# Function to print subarray with sum as given sum
def subArraySum(arr, n, Sum):
# create an empty map
Map = {}
# Maintains sum of elements so far
curr_sum = 0
for i in range(0, n):
# add current element to curr_sum
curr_sum = curr_sum + arr[i]
# if curr_sum is equal to target sum
# we found a subarray starting from index 0
# and ending at index i
if curr_sum == Sum:
print("Sum found between indexes 0 to", i)
return
# If curr_sum - sum already exists in map
# we have found a subarray with target sum
if (curr_sum - Sum) in Map:
print("Sum found between indexes",
Map[curr_sum - Sum] + 1, "to", i)
return
Map[curr_sum] = i
# If we reach here, then no subarray exists
print("No subarray with given sum exists")
# Driver code
if __name__ == "__main__":
arr = [10, 2, -2, -20, 10]
n = len(arr)
Sum = -10
# Function call
subArraySum(arr, n, Sum)
# This code is contributed by Rituraj Jain
|
linear
|
linear
|
# Python3 program to find minimum number
# of insertions to make a string
# palindrome
import math as mt
# Function will return number of
# characters to be added
def minInsertion(tr1):
# To store string length
n = len(str1)
# To store number of characters
# occurring odd number of times
res = 0
# To store count of each
# character
count = [0 for i in range(26)]
# To store occurrence of each
# character
for i in range(n):
count[ord(str1[i]) - ord('a')] += 1
# To count characters with odd
# occurrence
for i in range(26):
if (count[i] % 2 == 1):
res += 1
# As one character can be odd return
# res - 1 but if string is already
# palindrome return 0
if (res == 0):
return 0
else:
return res - 1
# Driver Code
str1 = "geeksforgeeks"
print(minInsertion(str1))
# This code is contributed by
# Mohit kumar 29
|
constant
|
linear
|
# Python3 implementation to find maximum
# length subsequence with difference between
# adjacent elements as either 0 or 1
from collections import defaultdict
# Function to find maximum length subsequence with
# difference between adjacent elements as either 0 or 1
def maxLenSub(arr, n):
# hash table to map the array element with the
# length of the longest subsequence of which it is a
# part of and is the last element of that subsequence
um = defaultdict(lambda:0)
# to store the maximum length subsequence
maxLen = 0
# traverse the array elements
for i in range(0, n):
# initialize current length
# for element arr[i] as 0
length = 0
# if 'arr[i]-1' is in 'um' and its length of
# subsequence is greater than 'len'
if (arr[i]-1) in um and length < um[arr[i]-1]:
length = um[arr[i]-1]
# if 'arr[i]' is in 'um' and its length of
# subsequence is greater than 'len'
if arr[i] in um and length < um[arr[i]]:
length = um[arr[i]]
# if 'arr[i]+1' is in 'um' and its length of
# subsequence is greater than 'len'
if (arr[i]+1) in um and length < um[arr[i]+1]:
length = um[arr[i]+1]
# update arr[i] subsequence length in 'um'
um[arr[i]] = length + 1
# update maximum length
if maxLen < um[arr[i]]:
maxLen = um[arr[i]]
# required maximum length subsequence
return maxLen
# Driver program to test above
if __name__ == "__main__":
arr = [2, 5, 6, 3, 7, 6, 5, 8]
n = len(arr)
print("Maximum length subsequence =", maxLenSub(arr, n))
# This code is contributed by Rituraj Jain
|
linear
|
linear
|
# Python program to find maximum difference
# between frequency of any two element
# such that element with greater frequency
# is also greater in value.
from collections import defaultdict
# Return the maximum difference between
# frequencies of any two elements such that
# element with greater frequency is also
# greater in value.
def maxdiff(arr, n):
freq = defaultdict(lambda: 0)
# Finding the frequency of each element.
for i in range(n):
freq[arr[i]] += 1
ans = 0
for i in range(n):
for j in range(n):
# finding difference such that element
# having greater frequency is also
# greater in value.
if freq[arr[i]] > freq[arr[j]] and arr[i] > arr[j]:
ans = max(ans, freq[arr[i]] - freq[arr[j]])
elif freq[arr[i]] < freq[arr[j]] and arr[i] < arr[j]:
ans = max(ans, freq[arr[j]] - freq[arr[i]])
return ans
arr = [3,1,3,2,3,2]
n = len(arr)
print(maxdiff(arr,n))
# This code is contributed by Shrikant13
|
linear
|
quadratic
|
# Efficient Python3 program to find maximum
# difference between frequency of any two
# elements such that element with greater
# frequency is also greater in value.
# Return the maximum difference between
# frequencies of any two elements such that
# element with greater frequency is also
# greater in value.
def maxdiff(arr, n):
freq = {}
dist = [0] * n
# Finding the frequency of each element.
j = 0
for i in range(n):
if (arr[i] not in freq):
dist[j] = arr[i]
j += 1
freq[arr[i]] = 0
if (arr[i] in freq):
freq[arr[i]] += 1
dist = dist[:j]
# Sorting the distinct element
dist.sort()
min_freq = n + 1
# Iterate through all sorted distinct elements.
# For each distinct element, maintaining the
# element with minimum frequency than that
# element and also finding the maximum
# frequency difference
ans = 0
for i in range(j):
cur_freq = freq[dist[i]]
ans = max(ans, cur_freq - min_freq)
min_freq = min(min_freq, cur_freq)
return ans
# Driven Program
arr = [3, 1, 3, 2, 3, 2]
n = len(arr)
print(maxdiff(arr, n))
# This code is contributed by SHUBHAMSINGH10
|
linear
|
nlogn
|
# Python3 code to find the difference
# between highest nd least frequencies
def findDiff(arr, n):
# sort the array
arr.sort()
count = 0; max_count = 0; min_count = n
for i in range(0, (n-1)):
# checking consecutive elements
if arr[i] == arr[i + 1]:
count += 1
continue
else:
max_count = max(max_count, count)
min_count = min(min_count, count)
count = 0
return max_count - min_count
# Driver Code
arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5 ]
n = len(arr)
print (findDiff(arr, n))
# This code is contributed by Shreyanshi Arun.
|
constant
|
nlogn
|
# Python code to find the difference between highest
# and least frequencies
from collections import defaultdict
def findDiff(arr,n):
# Put all elements in a hash map
mp = defaultdict(lambda:0)
for i in range(n):
mp[arr[i]]+=1
# Find counts of maximum and minimum
# frequent elements
max_count=0;min_count=n
for key,values in mp.items():
max_count= max(max_count,values)
min_count = min(min_count,values)
return max_count-min_count
# Driver code
arr = [ 7, 8, 4, 5, 4, 1, 1, 7, 7, 2, 5]
n = len(arr)
print(findDiff(arr,n))
# This code is contributed by Shrikant13
|
linear
|
linear
|
# Python 3 program to find minimum range
# that contains exactly k distinct numbers.
# Prints the minimum range that contains
# exactly k distinct numbers.
def minRange(arr, n, k):
l = 0
r = n
# Consider every element as
# starting point.
for i in range(n):
# Find the smallest window starting
# with arr[i] and containing exactly
# k distinct elements.
s = []
for j in range(i, n) :
s.append(arr[j])
if (len(s) == k):
if ((j - i) < (r - l)) :
r = j
l = i
break
# There are less than k distinct
# elements now, so no need to continue.
if (j == n):
break
# If there was no window with k distinct
# elements (k is greater than total
# distinct elements)
if (l == 0 and r == n):
print("Invalid k")
else:
print(l, r)
# Driver code
if __name__ == "__main__":
arr = [ 1, 2, 3, 4, 5 ]
n = len(arr)
k = 3
minRange(arr, n, k)
# This code is contributed
# by ChitraNayal
|
linear
|
quadratic
|
# Python3 program to find the minimum range
# that contains exactly k distinct numbers.
from collections import defaultdict
# Prints the minimum range that contains
# exactly k distinct numbers.
def minRange(arr, n, k):
# Initially left and right side is -1
# and -1, number of distinct elements
# are zero and range is n.
l, r = 0, n
i = 0
j = -1 # Initialize right side
hm = defaultdict(lambda:0)
while i < n:
while j < n:
# increment right side.
j += 1
# if number of distinct elements less than k.
if len(hm) < k and j < n:
hm[arr[j]] += 1
# if distinct elements are equal to k
# and length is less than previous length.
if len(hm) == k and ((r - l) >= (j - i)):
l, r = i, j
break
# if number of distinct elements less
# than k, then break.
if len(hm) < k:
break
# if distinct elements equals to k then
# try to increment left side.
while len(hm) == k:
if hm[arr[i]] == 1:
del(hm[arr[i]])
else:
hm[arr[i]] -= 1
# increment left side.
i += 1
# it is same as explained in above loop.
if len(hm) == k and (r - l) >= (j - i):
l, r = i, j
if hm[arr[i]] == 1:
del(hm[arr[i]])
else:
hm[arr[i]] -= 1
i += 1
if l == 0 and r == n:
print("Invalid k")
else:
print(l, r)
# Driver code for above function.
if __name__ == "__main__":
arr = [1, 1, 2, 2, 3, 3, 4, 5]
n = len(arr)
k = 3
minRange(arr, n, k)
# This code is contributed by Rituraj Jain
|
constant
|
linear
|
# Python 3 program to find longest
# subarray with k or less distinct elements.
# function to print the longest sub-array
import collections
def longest(a, n, k):
freq = collections.defaultdict(int)
start = 0
end = 0
now = 0
l = 0
for i in range(n):
# mark the element visited
freq[a[i]] += 1
# if its visited first time, then increase
# the counter of distinct elements by 1
if (freq[a[i]] == 1):
now += 1
# When the counter of distinct elements
# increases from k, then reduce it to k
while (now > k) :
# from the left, reduce the number
# of time of visit
freq[a[l]] -= 1
# if the reduced visited time element
# is not present in further segment
# then decrease the count of distinct
# elements
if (freq[a[l]] == 0):
now -= 1
# increase the subsegment mark
l += 1
# check length of longest sub-segment
# when greater than previous best
# then change it
if (i - l + 1 >= end - start + 1):
end = i
start = l
# print the longest sub-segment
for i in range(start, end + 1):
print(a[i], end = " ")
# Driver Code
if __name__ == "__main__":
a = [ 6, 5, 1, 2, 3,
2, 1, 4, 5 ]
n = len(a)
k = 3
longest(a, n, k)
# This code is contributed
# by ChitraNayal
|
linear
|
linear
|
# Python3 program to find number of pairs
# in an array such that their XOR is 0
# Function to calculate the count
def calculate(a) :
# Sorting the list using
# built in function
a.sort()
count = 1
answer = 0
# Traversing through the elements
for i in range(1, len(a)) :
if a[i] == a[i - 1] :
# Counting frequency of each elements
count += 1
else :
# Adding the contribution of
# the frequency to the answer
answer = answer + count * (count - 1) // 2
count = 1
answer = answer + count * (count - 1) // 2
return answer
# Driver Code
if __name__ == '__main__':
a = [1, 2, 1, 2, 4]
# Print the count
print(calculate(a))
|
constant
|
nlogn
|
# Python3 program to find number of pairs
# in an array such that their XOR is 0
# Function to calculate the answer
def calculate(a) :
# Finding the maximum of the array
maximum = max(a)
# Creating frequency array
# With initial value 0
frequency = [0 for x in range(maximum + 1)]
# Traversing through the array
for i in a :
# Counting frequency
frequency[i] += 1
answer = 0
# Traversing through the frequency array
for i in frequency :
# Calculating answer
answer = answer + i * (i - 1) // 2
return answer
# Driver Code
a = [1, 2, 1, 2, 4]
print(calculate(a))
|
linear
|
linear
|
# Python3 program to print the maximum elements
# giving second array higher priority
# Function to maximize array elements
def maximizeArray(arr1, arr2, n):
# Auxiliary array arr3 to store
# elements of arr1 & arr2
arr3 = [0] * (2 * n)
k = 0
for i in range(n):
arr3[k] = arr1[i]
k += 1
for i in range(n):
arr3[k] = arr2[i]
k += 1
# Hash table to store n largest
# unique elements
hash = {}
# Sorting arr3 in decreasing order
arr3 = sorted(arr3)
arr3 = arr3[::-1]
# Finding n largest unique elements
# from arr3 and storing in hash
i = 0
while (len(hash) != n):
# If arr3 element not present in hash,
# then store this element in hash
if (arr3[i] not in hash):
hash[arr3[i]] = 1
i += 1
# Store that elements of arr2 in arr3
# that are present in hash
k = 0
for i in range(n):
# If arr2 element is present in
# hash, store it in arr3
if (arr2[i] in hash):
arr3[k] = arr2[i]
k += 1
del hash[arr2[i]]
# Store that elements of arr1 in arr3
# that are present in hash
for i in range(n):
# If arr1 element is present
# in hash, store it in arr3
if (arr1[i] in hash):
arr3[k] = arr1[i]
k += 1
del hash[arr1[i]]
# Copying 1st n elements of
# arr3 to arr1
for i in range(n):
arr1[i] = arr3[i]
# Function to print array elements
def printArray(arr, n):
for i in arr:
print(i, end = " ")
print()
# Driver Code
if __name__ == '__main__':
array1 = [ 7, 4, 8, 0, 1 ]
array2 = [ 9, 7, 2, 3, 6 ]
size = len(array1)
maximizeArray(array1, array2, size)
printArray(array1, size)
# This code is contributed by mohit kumar 29
|
linear
|
nlogn
|
# Python3 implementation to count
# subarrays with equal number
# of 1's and 0's
# function to count subarrays with
# equal number of 1's and 0's
def countSubarrWithEqualZeroAndOne(arr, n):
# 'um' implemented as hash table
# to store frequency of values
# obtained through cumulative sum
um = dict()
curr_sum = 0
# Traverse original array and compute
# cumulative sum and increase count
# by 1 for this sum in 'um'.
# Adds '-1' when arr[i] == 0
for i in range(n):
curr_sum += (-1 if (arr[i] == 0) else arr[i])
if um.get(curr_sum):
um[curr_sum] += 1
else:
um[curr_sum] = 1
count = 0
# traverse the hash table 'um'
for itr in um:
# If there are more than one
# prefix subarrays with a
# particular sum
if um[itr] > 1:
count += ((um[itr] * int(um[itr] - 1)) / 2)
# add the subarrays starting from
# 1st element and have equal
# number of 1's and 0's
if um.get(0):
count += um[0]
# required count of subarrays
return int(count)
# Driver code to test above
arr = [1, 0, 0, 1, 0, 1, 1]
n = len(arr)
print("Count =",
countSubarrWithEqualZeroAndOne(arr, n))
# This code is contributed by "Sharad_Bhardwaj".
|
linear
|
linear
|
# Python3 implementation to count subarrays
# with equal number of 1's and 0's
def countSubarrWithEqualZeroAndOne(arr, n):
mp = dict()
Sum = 0
count = 0
for i in range(n):
# Replacing 0's in array with -1
if (arr[i] == 0):
arr[i] = -1
Sum += arr[i]
# If Sum = 0, it implies number of
# 0's and 1's are equal from arr[0]..arr[i]
if (Sum == 0):
count += 1
if (Sum in mp.keys()):
count += mp[Sum]
mp[Sum] = mp.get(Sum, 0) + 1
return count
# Driver Code
arr = [1, 0, 0, 1, 0, 1, 1]
n = len(arr)
print("count =",
countSubarrWithEqualZeroAndOne(arr, n))
# This code is contributed by mohit kumar
|
linear
|
linear
|
# Python 3 implementation to find the length of
# longest subarray having count of 1's one
# more than count of 0's
# function to find the length of longest
# subarray having count of 1's one more
# than count of 0's
def lenOfLongSubarr(arr, n):
# unordered_map 'um' implemented as
# hash table
um = {}
sum = 0
maxLen = 0
# traverse the given array
for i in range(n):
# consider '0' as '-1'
if arr[i] == 0:
sum += -1
else:
sum += 1
# when subarray starts form index '0'
if (sum == 1):
maxLen = i + 1
# make an entry for 'sum' if it is
# not present in 'um'
elif (sum not in um):
um[sum] = i
# check if 'sum-1' is present in 'um'
# or not
if ((sum - 1) in um):
# update maxLength
if (maxLen < (i - um[sum - 1])):
maxLen = i - um[sum - 1]
# required maximum length
return maxLen
# Driver code
if __name__ == '__main__':
arr = [0, 1, 1, 0, 0, 1]
n = len(arr)
print("Length =", lenOfLongSubarr(arr, n))
# This code is contributed by
# Surendra_Gangwar
|
linear
|
linear
|
# Python3 program to find substring with equal
# number of 0's, 1's and 2's
# Method to count number of substring which
# has equal 0, 1 and 2
def getSubstringWithEqual012(string):
N = len(string)
# map to store, how many times a difference
# pair has occurred previously
mp = dict()
mp[(0, 0)] = 1
# zc (Count of zeroes), oc(Count of 1s)
# and tc(count of twos)
# In starting all counts are zero
zc, oc, tc = 0, 0, 0
# looping into string
res = 0 # Initialize result
for i in range(N):
# increasing the count of current character
if string[i] == '0':
zc += 1
elif string[i] == '1':
oc += 1
else:
tc += 1 # Assuming that string doesn't contain
# other characters
# making pair of differences (z[i] - o[i],
# z[i] - t[i])
tmp = (zc - oc, zc - tc)
# Count of previous occurrences of above pair
# indicates that the subarrays forming from
# every previous occurrence to this occurrence
# is a subarray with equal number of 0's, 1's
# and 2's
if tmp not in mp:
res += 0
else:
res += mp[tmp]
# increasing the count of current difference
# pair by 1
if tmp in mp:
mp[tmp] += 1
else:
mp[tmp] = 1
return res
# Driver's Code
if __name__ == "__main__":
string = "0102010"
print(getSubstringWithEqual012(string))
# This code is contributed by
# sanjeev2552
|
linear
|
nlogn
|
# Python program to print all
# triplets in given array
# that form Arithmetic
# Progression
# Function to print
# all triplets in
# given sorted array
# that forms AP
def printAllAPTriplets(arr, n) :
s = [];
for i in range(0, n - 1) :
for j in range(i + 1, n) :
# Use hash to find if
# there is a previous
# element with difference
# equal to arr[j] - arr[i]
diff = arr[j] - arr[i];
if ((arr[i] - diff) in arr) :
print ("{} {} {}" .
format((arr[i] - diff),
arr[i], arr[j]),
end = "\n");
s.append(arr[i]);
# Driver code
arr = [2, 6, 9, 12, 17,
22, 31, 32, 35, 42];
n = len(arr);
printAllAPTriplets(arr, n);
# This code is contributed by
# Manish Shaw(manishshaw1)
|
linear
|
quadratic
|
# python 3 program to print all triplets in given
# array that form Arithmetic Progression
# Function to print all triplets in
# given sorted array that forms AP
def printAllAPTriplets(arr, n):
for i in range(1, n - 1):
# Search other two elements of
# AP with arr[i] as middle.
j = i - 1
k = i + 1
while(j >= 0 and k < n ):
# if a triplet is found
if (arr[j] + arr[k] == 2 * arr[i]):
print(arr[j], "", arr[i], "", arr[k])
# Since elements are distinct,
# arr[k] and arr[j] cannot form
# any more triplets with arr[i]
k += 1
j -= 1
# If middle element is more move to
# higher side, else move lower side.
elif (arr[j] + arr[k] < 2 * arr[i]):
k += 1
else:
j -= 1
# Driver code
arr = [ 2, 6, 9, 12, 17,
22, 31, 32, 35, 42 ]
n = len(arr)
printAllAPTriplets(arr, n)
# This article is contributed
# by Smitha Dinesh Semwal
|
constant
|
quadratic
|
# Python program to find unique triplets
# that sum up to a given value.
# Function to find unique triplets that
# sum up to a given value.
def findTriplets(nums, n, Sum):
i = 0
j = 0
k = 0
# list to store all unique triplets.
triplet = []
# list to store already found triplets
# to avoid duplication.
uniqTriplets = []
# Variable used to hold triplet
# converted to string form.
temp = ""
# Variable used to store current
# triplet which is stored in vector
# if it is unique.
newTriplet = [0, 0, 0]
# Sort the input array.
nums.sort()
# Iterate over the array from the
# start and consider it as the
# first element.
for i in range(n - 2):
# index of the first element in
# the remaining elements.
j = i + 1
# index of the last element.
k = n - 1
while(j < k):
# If sum of triplet is equal to
# given value, then check if
# this triplet is unique or not.
# To check uniqueness, convert
# triplet to string form and
# then check if this string is
# present in set or not. If
# triplet is unique, then store
# it in list.
if(nums[i] + nums[j] + nums[k] == Sum):
temp = str(nums[i]) + ":" + str(nums[j]) + ":" + str(nums[k])
if temp not in uniqTriplets:
uniqTriplets.append(temp)
newTriplet[0] = nums[i]
newTriplet[1] = nums[j]
newTriplet[2] = nums[k]
triplet.append(newTriplet)
newTriplet = [0, 0, 0]
# Increment the first index
# and decrement the last
# index of remaining elements.
j += 1
k -= 1
# If sum is greater than given
# value then to reduce sum
# decrement the last index.
elif(nums[i] + nums[j] + nums[k] > Sum):
k -= 1
# If sum is less than given value
# then to increase sum increment
# the first index of remaining
# elements.
else:
j += 1
# If no unique triplet is found, then
# return 0.
if(len(triplet) == 0):
return 0
# Print all unique triplets stored in
# list.
for i in range(len(triplet)):
print(triplet[i], end = ", ")
return 1
# Driver Code
nums = [12, 3, 6, 1, 6, 9]
n = len(nums)
Sum = 24
# Function call
if(not findTriplets(nums, n, Sum)):
print("No triplets can be formed.")
# This code is contributed by rag2127
|
linear
|
quadratic
|
# A simple Python 3 program
# to find three elements whose
# sum is equal to zero
# Prints all triplets in
# arr[] with 0 sum
def findTriplets(arr, n):
found = False
for i in range(0, n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if (arr[i] + arr[j] + arr[k] == 0):
print(arr[i], arr[j], arr[k])
found = True
# If no triplet with 0 sum
# found in array
if (found == False):
print(" not exist ")
# Driver code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
# This code is contributed by Smitha Dinesh Semwal
|
constant
|
cubic
|
# Python3 program to find triplets
# in a given array whose sum is zero
# function to print triplets with 0 sum
def findTriplets(arr, n):
found = False
for i in range(n - 1):
# Find all pairs with sum
# equals to "-arr[i]"
s = set()
for j in range(i + 1, n):
x = -(arr[i] + arr[j])
if x in s:
print(x, arr[i], arr[j])
found = True
else:
s.add(arr[j])
if found == False:
print("No Triplet Found")
# Driver Code
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
# This code is contributed by Shrikant13
|
linear
|
quadratic
|
# python program to find triplets in a given
# array whose sum is zero
# function to print triplets with 0 sum
def findTriplets(arr, n):
found = False
# sort array elements
arr.sort()
for i in range(0, n-1):
# initialize left and right
l = i + 1
r = n - 1
x = arr[i]
while (l < r):
if (x + arr[l] + arr[r] == 0):
# print elements if it's sum is zero
print(x, arr[l], arr[r])
l += 1
r -= 1
found = True
# If sum of three elements is less
# than zero then increment in left
elif (x + arr[l] + arr[r] < 0):
l += 1
# if sum is greater than zero then
# decrement in right side
else:
r -= 1
if (found == False):
print(" No Triplet Found")
# Driven source
arr = [0, -1, 2, -3, 1]
n = len(arr)
findTriplets(arr, n)
# This code is contributed by Smitha Dinesh Semwal
|
constant
|
quadratic
|
# Python3 program to count
# triplets with given product m
# Method to count such triplets
def countTriplets(arr, n, m):
count = 0
# Consider all triplets and count if
# their product is equal to m
for i in range (n - 2):
for j in range (i + 1, n - 1):
for k in range (j + 1, n):
if (arr[i] * arr[j] * arr[k] == m):
count += 1
return count
# Driver code
if __name__ == "__main__":
arr = [1, 4, 6, 2, 3, 8]
m = 24
print(countTriplets(arr,
len(arr), m))
# This code is contributed by Chitranayal
|
constant
|
cubic
|
# Python3 program for the above approach
# Function to find the triplet
def countTriplets(li,product):
flag = 0
count = 0
# Consider all pairs and check
# for a third number so their
# product is equal to product
for i in range(len(li)):
# Check if current pair
# divides product or not
# If yes, then search for
# (product / li[i]*li[j])
if li[i]!= 0 and product % li[i] == 0:
for j in range(i+1, len(li)):
# Check if the third number is present
# in the map and it is not equal to any
# other two elements and also check if
# this triplet is not counted already
# using their indexes
if li[j]!= 0 and product % (li[j]*li[i]) == 0:
if product // (li[j]*li[i]) in li:
n = li.index(product//(li[j]*li[i]))
if n > i and n > j:
flag = 1
count+=1
print(count)
# Driver code
li = [ 1, 4, 6, 2, 3, 8 ]
product = 24
# Function call
countTriplets(li,product)
|
linear
|
quadratic
|
# Python3 program to
# count of pairs with equal
# elements in an array.
# Return the number of
# pairs with equal values.
def countPairs(arr, n):
ans = 0
# for each index i and j
for i in range(0 , n):
for j in range(i + 1, n):
# finding the index
# with same value but
# different index.
if (arr[i] == arr[j]):
ans += 1
return ans
# Driven Code
arr = [1, 1, 2 ]
n = len(arr)
print(countPairs(arr, n))
# This code is contributed
# by Smitha
|
constant
|
quadratic
|
# Python3 program to count of index pairs
# with equal elements in an array.
import math as mt
# Return the number of pairs with
# equal values.
def countPairs(arr, n):
mp = dict()
# Finding frequency of each number.
for i in range(n):
if arr[i] in mp.keys():
mp[arr[i]] += 1
else:
mp[arr[i]] = 1
# Calculating pairs of each value.
ans = 0
for it in mp:
count = mp[it]
ans += (count * (count - 1)) // 2
return ans
# Driver Code
arr = [1, 1, 2]
n = len(arr)
print(countPairs(arr, n))
# This code is contributed by mohit kumar 29
|
linear
|
linear
|
# Python program to find total
# count of an element in a range
# Returns count of element
# in arr[left-1..right-1]
def findFrequency(arr, n, left, right, element):
count = 0
for i in range(left - 1, right):
if (arr[i] == element):
count += 1
return count
# Driver Code
arr = [2, 8, 6, 9, 8, 6, 8, 2, 11]
n = len(arr)
# Print frequency of 2 from position 1 to 6
print("Frequency of 2 from 1 to 6 = ",
findFrequency(arr, n, 1, 6, 2))
# Print frequency of 8 from position 4 to 9
print("Frequency of 8 from 4 to 9 = ",
findFrequency(arr, n, 4, 9, 8))
# This code is contributed by Anant Agarwal.
|
constant
|
linear
|
# python program for above implementation
# Function to count numbers to be added
def countNum(arr, n):
count = 0
# Sort the array
arr.sort()
# Check if elements are consecutive
# or not. If not, update count
for i in range(0, n-1):
if (arr[i] != arr[i+1] and
arr[i] != arr[i + 1] - 1):
count += arr[i + 1] - arr[i] - 1;
return count
# Drivers code
arr = [ 3, 5, 8, 6 ]
n = len(arr)
print(countNum(arr, n))
# This code is contributed by Sam007
|
constant
|
nlogn
|
# Function to count numbers to be added
def countNum(arr, n):
s = dict()
count, maxm, minm = 0, -10**9, 10**9
# Make a hash of elements and store
# minimum and maximum element
for i in range(n):
s[arr[i]] = 1
if (arr[i] < minm):
minm = arr[i]
if (arr[i] > maxm):
maxm = arr[i]
# Traverse all elements from minimum
# to maximum and count if it is not
# in the hash
for i in range(minm, maxm + 1):
if i not in s.keys():
count += 1
return count
# Driver code
arr = [3, 5, 8, 6 ]
n = len(arr)
print(countNum(arr, n))
# This code is contributed by mohit kumar
|
constant
|
linear
|
# Python 3 program to calculate sum of
# lengths of subarrays of distinct elements.
# Returns sum of lengths of all subarrays
# with distinct elements.
def sumoflength(arr, n):
# For maintaining distinct elements.
s = []
# Initialize ending point and result
j = 0
ans = 0
# Fix starting point
for i in range(n):
# Find ending point for current
# subarray with distinct elements.
while (j < n and (arr[j] not in s)):
s.append(arr[j])
j += 1
# Calculating and adding all possible
# length subarrays in arr[i..j]
ans += ((j - i) * (j - i + 1)) // 2
# Remove arr[i] as we pick new
# starting point from next
s.remove(arr[i])
return ans
# Driven Code
if __name__=="__main__":
arr = [1, 2, 3, 4]
n = len(arr)
print(sumoflength(arr, n))
# This code is contributed by ita_c
|
linear
|
linear
|
# Python3 program Count total number of
# sub-arrays having total distinct elements
# same as that original array.
# Function to calculate distinct sub-array
def countDistictSubarray(arr, n):
# Count distinct elements in whole array
vis = dict()
for i in range(n):
vis[arr[i]] = 1
k = len(vis)
# Reset the container by removing
# all elements
vid = dict()
# Use sliding window concept to find
# count of subarrays having k distinct
# elements.
ans = 0
right = 0
window = 0
for left in range(n):
while (right < n and window < k):
if arr[right] in vid.keys():
vid[ arr[right] ] += 1
else:
vid[ arr[right] ] = 1
if (vid[ arr[right] ] == 1):
window += 1
right += 1
# If window size equals to array distinct
# element size, then update answer
if (window == k):
ans += (n - right + 1)
# Decrease the frequency of previous
# element for next sliding window
vid[ arr[left] ] -= 1
# If frequency is zero then decrease
# the window size
if (vid[ arr[left] ] == 0):
window -= 1
return ans
# Driver code
arr = [2, 1, 3, 2, 3]
n = len(arr)
print(countDistictSubarray(arr, n))
# This code is contributed by
# mohit kumar 29
|
linear
|
linear
|
# Python3 program to find largest consecutive
# numbers present in arr.
def findLongestConseqSubseq(arr, n):
'''We insert all the array elements into unordered set.'''
S = set();
for i in range(n):
S.add(arr[i]);
# check each possible sequence from the start
# then update optimal length
ans = 0;
for i in range(n):
# if current element is the starting
# element of a sequence
if S.__contains__(arr[i]):
# Then check for next elements in the
# sequence
j = arr[i];
# increment the value of array element
# and repeat search in the set
while(S.__contains__(j)):
j += 1;
# Update optimal length if this length
# is more. To get the length as it is
# incremented one by one
ans = max(ans, j - arr[i]);
return ans;
# Driver code
if __name__ == '__main__':
arr = [ 1, 94, 93, 1000, 5, 92, 78 ];
n = len(arr);
print(findLongestConseqSubseq(arr, n));
# This code is contributed by 29AjayKumar
|
linear
|
quadratic
|
# Python3 program to implement the
# above approach
# Make a set of maximum elements
# from two arrays A[] and B[]
from collections import defaultdict
def maximizeTheFirstArray(A, B, n):
# Create copies of A[] and B[]
# and sort the copies in
# descending order.
temp1 = A.copy()
temp2 = B.copy()
temp1.sort(reverse = True)
temp2.sort(reverse = True)
# Put maximum n distinct
# elements of both sorted
# arrays in a map.
m = defaultdict(int)
i = 0
j = 0;
while (len(m) < n):
if (temp1[i] >= temp2[j]):
m[temp1[i]] += 1
i += 1
else:
m[temp2[j]] += 1
j += 1
# Copy elements of A[] to that
# are present in hash m.
res = []
for i in range (n):
if (A[i] in m):
res.append(A[i])
# Copy elements of B[] to that
# are present in hash m. This time
# we also check if the element did
# not appear twice.
for i in range (n):
if (B[i] in m and
m[B[i]] == 1):
res.append(B[i])
# Print result
for i in range (n):
print (res[i], end = " ")
# Driver code
if __name__ == "__main__":
A = [9, 7, 2, 3, 6]
B = [7, 4, 8, 0, 1]
n = len(A)
maximizeTheFirstArray(A, B, n);
# This code is contributed by Chitranayal
|
linear
|
nlogn
|
# Python3 implementation to
# find the maximum number
# of chocolates to be
# distributed equally
# among k students
# function to find the
# maximum number of chocolates
# to be distributed equally
# among k students
def maxNumOfChocolates(arr, n, k):
um, curr_rem, maxSum = {}, 0, 0
# 'sm[]' to store cumulative sm,
# where sm[i] = sm(arr[0]+..arr[i])
sm = [0]*n
sm[0] = arr[0]
# building up 'sm[]'
for i in range(1, n):
sm[i] = sm[i - 1] + arr[i]
# traversing 'sm[]'
for i in range(n):
# finding current remainder
curr_rem = sm[i] % k
if (not curr_rem and maxSum < sm[i]) :
maxSum = sm[i]
elif (not curr_rem in um) :
um[curr_rem] = i
elif (maxSum < (sm[i] - sm[um[curr_rem]])):
maxSum = sm[i] - sm[um[curr_rem]]
return maxSum//k
# Driver program to test above
arr = [ 2, 7, 6, 1, 4, 5 ]
n, k = len(arr), 3
print("Maximum number of chocolates: " +
str(maxNumOfChocolates(arr, n, k)))
# This code is contributed by Ansu Kumari
|
linear
|
linear
|
# Python 3 program to print n-th
# number in Recaman's sequence
# Prints first n terms of Recaman
# sequence
def recaman(n):
# Create an array to store terms
arr = [0] * n
# First term of the sequence
# is always 0
arr[0] = 0
print(arr[0], end=", ")
# Fill remaining terms using
# recursive formula.
for i in range(1, n):
curr = arr[i-1] - i
for j in range(0, i):
# If arr[i-1] - i is
# negative or already
# exists.
if ((arr[j] == curr) or curr < 0):
curr = arr[i-1] + i
break
arr[i] = curr
print(arr[i], end=", ")
# Driver code
n = 17
recaman(n)
# This code is contributed by Smitha.
|
linear
|
quadratic
|
# Python3 program to print n-th number in
# Recaman's sequence
# Prints first n terms of Recaman sequence
def recaman(n):
if(n <= 0):
return
# Print first term and store it in a hash
print(0, ",", end='')
s = set([])
s.add(0)
# Print remaining terms using recursive
# formula.
prev = 0
for i in range(1, n):
curr = prev - i
# If arr[i-1] - i is negative or
# already exists.
if(curr < 0 or curr in s):
curr = prev + i
s.add(curr)
print(curr, ",", end='')
prev = curr
# Driver code
if __name__=='__main__':
n = 17
recaman(n)
# This code is contributed by
# Sanjit_Prasad
|
linear
|
linear
|
# python3 program to find largest Fibonacci subset
# Prints largest subset of an array whose
# all elements are fibonacci numbers
def findFibSubset(arr, n):
#Now iterate through all elements of the array..
for i in range(n):
#we are using the property of fibonacci series to check arr[i] is a
# fib number or not by checking whether any one out of 5(n^2)+4 and 5(n^2)-4
# is a perfect square or not.
fact1=5*(arr[i]**2)+4
fact2=5*(arr[i]**2)-4
if int(fact1**(.5))**2==fact1 or int(fact2**(.5))**2==fact2:
print(arr[i],end=" ")
return None
# Driver code
if __name__ == "__main__":
arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]
n = len(arr)
findFibSubset(arr, n)
# This code is contributed by Rajat Kumar (GLA University)
|
constant
|
linear
|
# python3 program to find largest Fibonacci subset
# Prints largest subset of an array whose
# all elements are fibonacci numbers
def findFibSubset(arr, n):
# Find maximum element in arr[]
m= max(arr)
# Generate all Fibonacci numbers till
# max and store them in hash.
a = 0
b = 1
hash = []
hash.append(a)
hash.append(b)
while (b < m):
c = a + b
a = b
b = c
hash.append(b)
# Npw iterate through all numbers and
# quickly check for Fibonacci using
# hash.
for i in range (n):
if arr[i] in hash :
print( arr[i],end=" ")
# Driver code
if __name__ == "__main__":
arr = [4, 2, 8, 5, 20, 1, 40, 13, 23]
n = len(arr)
findFibSubset(arr, n)
|
linear
|
linear
|
# Python3 program to find averages of
# all levels in a binary tree.
# Helper function that allocates a
# new node with the given data and
# None left and right pointers.
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
def inorder(node, m):
if (not node):
return ""
Str = "("
Str += inorder(node.left, m)
Str += str(node.data)
Str += inorder(node.right, m)
Str += ")"
# Subtree already present (Note that
# we use unordered_map instead of
# unordered_set because we want to print
# multiple duplicates only once, consider
# example of 4 in above subtree, it
# should be printed only once.
if (Str in m and m[Str] == 1):
print(node.data, end = " ")
if Str in m:
m[Str] += 1
else:
m[Str] = 1
return Str
# Wrapper over inorder()
def printAllDups(root):
m = {}
inorder(root, m)
# Driver code
if __name__ == '__main__':
root = None
root = newNode(1)
root.left = newNode(2)
root.right = newNode(3)
root.left.left = newNode(4)
root.right.left = newNode(2)
root.right.left.left = newNode(4)
root.right.right = newNode(4)
printAllDups(root)
# This code is contributed by PranchalK
|
quadratic
|
quadratic
|
# A brute force approach based Python3 program to
# find if there is a rectangle with 1 as corners.
# Returns true if there is a rectangle
# with 1 as corners.
def isRectangle(m):
# finding row and column size
rows = len(m)
if (rows == 0):
return False
columns = len(m[0])
# scanning the matrix
for y1 in range(rows):
for x1 in range(columns):
# if any index found 1 then
# try for all rectangles
if (m[y1][x1] == 1):
for y2 in range(y1 + 1, rows):
for x2 in range(x1 + 1, columns):
if (m[y1][x2] == 1 and
m[y2][x1] == 1 and
m[y2][x2] == 1):
return True
return False
# Driver code
mat = [[1, 0, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 1]]
if (isRectangle(mat)):
print("Yes")
else:
print("No")
# This code is contributed
# by mohit kumar 29
|
constant
|
quadratic
|
# An efficient approach based Python program
# to find if there is a rectangle with 1 as
# corners.
# Returns true if there is a rectangle
# with 1 as corners.
def isRectangle(matrix):
# finding row and column size
rows = len(matrix)
if (rows == 0):
return False
columns = len(matrix[0])
# map for storing the index of
# combination of 2 1's
table = {}
# scanning from top to bottom
# line by line
for i in range(rows):
for j in range(columns - 1):
for k in range(j + 1, columns):
# if found two 1's in a column
if (matrix[i][j] == 1 and
matrix[i][k] == 1):
# check if there exists 1's in same
# row previously then return true
if (j in table and k in table[j]):
return True
if (k in table and j in table[k]):
return True
# store the indexes in hashset
if j not in table:
table[j] = set()
if k not in table:
table[k] = set()
table[j].add(k)
table[k].add(j)
return False
# Driver Code
if __name__ == '__main__':
mat = [[ 1, 0, 0, 1, 0 ],
[ 0, 0, 1, 0, 1 ],
[ 0, 0, 0, 1, 0 ],
[ 1, 0, 1, 0, 1 ]]
if (isRectangle(mat)):
print("Yes")
else:
print("No")
# This code is contributed
# by SHUBHAMSINGH10
|
quadratic
|
quadratic
|
# Python3 implementation comes from:
# https:#github.com/MichaelWehar/FourCornersProblem
# Written by Niteesh Kumar and Michael Wehar
# References:
# [1] F. Mráz, D. Prusa, and M. Wehar.
# Two-dimensional Pattern Matching against
# Basic Picture Languages. CIAA 2019.
# [2] D. Prusa and M. Wehar. Complexity of
# Searching for 2 by 2 Submatrices in Boolean
# Matrices. DLT 2020.
def searchForRectangle( rows, cols, mat) :
# Make sure that matrix is non-trivial
if (rows < 2 or cols < 2) :
return False;
# Create map
adjsList = dict();
if (rows >= cols):
# Row-wise
num_of_keys = rows;
# Convert each row into vector of col indexes
for i in range(rows):
for j in range(cols):
if (mat[i][j]):
if i not in adjsList:
adjsList[i] = []
adjsList[i].append(j);
else :
# Col-wise
num_of_keys = cols;
# Convert each col into vector of row indexes
for i in range(rows):
for j in range(cols):
if (mat[i][j] == 1) :
if j not in adjsList:
adjsList[j] = []
adjsList[j].append(i);
# Search for a rectangle whose four corners are 1's
pairs = dict();
for i in range(num_of_keys):
values = adjsList[i];
size = len(values)
for j in range(size - 1):
for k in range(j + 1, size):
temp = (values[j], values[k]);
if temp in pairs:
return True;
else:
pairs[temp] = i;
return False;
# Driver code
mat = [[ 1, 0, 0, 1, 0 ], [ 0, 1, 1, 1, 1 ], [ 0, 0, 0, 1, 0 ], [ 1, 1, 1, 1, 0 ]];
if (searchForRectangle(4, 5, mat)):
print("Yes");
else:
print("No")
# This code is contributed by phasing17.
|
quadratic
|
quadratic
|
# Python3 program for finding
# maximum area possible of
# a rectangle
# function for finding
# max area
def findArea(arr, n):
# sort array in
# non-increasing order
arr.sort(reverse = True)
# Initialize two
# sides of rectangle
dimension = [0, 0]
# traverse through array
i = 0
j = 0
while(i < n - 1 and j < 2):
# if any element occurs twice
# store that as dimension
if (arr[i] == arr[i + 1]):
dimension[j] = arr[i]
j += 1
i += 1
i += 1
# return the product
# of dimensions
return (dimension[0] *
dimension[1])
# Driver code
arr = [4, 2, 1, 4, 6, 6, 2, 5]
n = len(arr)
print(findArea(arr, n))
# This code is contributed
# by Smitha
|
constant
|
nlogn
|
# Python 3 program for finding maximum
# area possible of a rectangle
# function for finding max area
def findArea(arr, n):
s = []
# traverse through array
first = 0
second = 0
for i in range(n) :
# If this is first occurrence of
# arr[i], simply insert and continue
if arr[i] not in s:
s.append(arr[i])
continue
# If this is second (or more) occurrence,
# update first and second maximum values.
if (arr[i] > first) :
second = first
first = arr[i]
else if (arr[i] > second):
second = arr[i]
# return the product of dimensions
return (first * second)
# Driver Code
if __name__ == "__main__":
arr = [ 4, 2, 1, 4, 6, 6, 2, 5 ]
n = len(arr)
print(findArea(arr, n))
# This code is contributed by ita_c
|
linear
|
linear
|
# Python3 implementation to find length of
# longest strict bitonic subsequence
# function to find length of longest
# strict bitonic subsequence
def longLenStrictBitonicSub(arr, n):
# hash table to map the array element
# with the length of the longest subsequence
# of which it is a part of and is the
# last/first element of that subsequence
inc, dcr = dict(), dict()
# arrays to store the length of increasing
# and decreasing subsequences which end at
# them or start from them
len_inc, len_dcr = [0] * n, [0] * n
# to store the length of longest strict
# bitonic subsequence
longLen = 0
# traverse the array elements
# from left to right
for i in range(n):
# initialize current length
# for element arr[i] as 0
len = 0
# if 'arr[i]-1' is in 'inc'
if inc.get(arr[i] - 1) in inc.values():
len = inc.get(arr[i] - 1)
# update arr[i] subsequence length in 'inc'
# and in len_inc[]
inc[arr[i]] = len_inc[i] = len + 1
# traverse the array elements
# from right to left
for i in range(n - 1, -1, -1):
# initialize current length
# for element arr[i] as 0
len = 0
# if 'arr[i]-1' is in 'dcr'
if dcr.get(arr[i] - 1) in dcr.values():
len = dcr.get(arr[i] - 1)
# update arr[i] subsequence length
# in 'dcr' and in len_dcr[]
dcr[arr[i]] = len_dcr[i] = len + 1
# calculating the length of
# all the strict bitonic subsequence
for i in range(n):
if longLen < (len_inc[i] + len_dcr[i] - 1):
longLen = len_inc[i] + len_dcr[i] - 1
# required longest length strict
# bitonic subsequence
return longLen
# Driver Code
if __name__ == "__main__":
arr = [1, 5, 2, 3, 4, 5, 3, 2]
n = len(arr)
print("Longest length strict bitonic subsequence =",
longLenStrictBitonicSub(arr, n))
# This code is contributed by sanjeev2552
|
linear
|
linear
|
# Python3 program to find last seen
# element in an array.
import sys;
# Returns last seen element in arr[]
def lastSeenElement(a, n):
# Store last occurrence index of
# every element
hash = {}
for i in range(n):
hash[a[i]] = i
# Find an element in hash with minimum
# index value
res_ind = sys.maxsize
res = 0
for x, y in hash.items():
if y < res_ind:
res_ind = y
res = x
return res
# Driver code
if __name__=="__main__":
a = [ 2, 1, 2, 2, 4, 1 ]
n = len(a)
print(lastSeenElement(a,n))
# This code is contributed by rutvik_56
|
linear
|
linear
|
# Python program to delete a node in a linked list
# at a given position
# Node class
class Node:
# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
# Constructor to initialize head
def __init__(self):
self.head = None
# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
# Given a reference to the head of a list
# and a position, delete the node at a given position
# This delete function code is contributed by Arabin Islam
def deleteNodeAtGivenPosition(self, position):
if self.head is None:
return
index = 0
current = self.head
while current.next and index < position:
previous = current
current = current.next
index += 1
if index < position:
print("\nIndex is out of range.")
elif index == 0:
self.head = self.head.next
else:
previous.next = current.next
# current = None #Optional statement
# Utility function to print the LinkedList
def printList(self):
temp = self.head
while(temp):
print(" %d " % (temp.data), end=" ")
temp = temp.next
# Driver program to test above function
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
llist.push(8)
print("Created Linked List: ")
llist.printList()
llist.deleteNodeAtGivenPosition(4)
print("\nLinked List after Deletion at position 4: ")
llist.printList()
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
|
constant
|
linear
|
# Python3 program to delete all
# the nodes of singly linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Constructor to initialize the node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
def deleteList(self):
# initialize the current node
current = self.head
while current:
next_to_current = current.next # move next node
# delete the current node
del current.data
# set current equals prev node
current = next_to_current
# In python garbage collection happens
# therefore, only
# self.head = None
# would also delete the link list
# push function to add node in front of llist
def push(self, new_data):
# Allocate the Node &
# Put in the data
new_node = Node(new_data)
# Make next of new Node as head
new_node.next = self.head
# Move the head to point to new Node
self.head = new_node
# Use push() to construct below
# list 1-> 12-> 1-> 4-> 1
if __name__ == '__main__':
llist = LinkedList()
llist.push(1)
llist.push(4)
llist.push(1)
llist.push(12)
llist.push(1)
print("Deleting linked list")
llist.deleteList()
print("Linked list deleted")
# This article is provided by Shrikant13
|
constant
|
linear
|
# A complete working Python program to find length of a
# Linked List iteratively
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# This function is in LinkedList class. It inserts
# a new node at the beginning of Linked List.
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This function counts number of nodes in Linked List
# iteratively, given 'node' as starting node.
def getCount(self):
temp = self.head # Initialise temp
count = 0 # Initialise count
# Loop while end of linked list is not reached
while (temp):
count += 1
temp = temp.next
return count
# Driver code
if __name__ == '__main__':
llist = LinkedList()
llist.push(1)
llist.push(3)
llist.push(1)
llist.push(2)
llist.push(1)
# Function call
print("Count of nodes is :", llist.getCount())
|
constant
|
linear
|
# A complete working Python program to find length of a
# Linked List recursively
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# This function is in LinkedList class. It inserts
# a new node at the beginning of Linked List.
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This function counts number of nodes in Linked List
# recursively, given 'node' as starting node.
def getCountRec(self, node):
if (not node): # Base case
return 0
else:
return 1 + self.getCountRec(node.next)
# A wrapper over getCountRec()
def getCount(self):
return self.getCountRec(self.head)
# Code execution starts here
if __name__ == '__main__':
llist = LinkedList()
llist.push(1)
llist.push(3)
llist.push(1)
llist.push(2)
llist.push(1)
print('Count of nodes is :', llist.getCount())
|
linear
|
linear
|
# A complete working Python3 program to find length of a
# Linked List using Tail recursion.
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class contains a Node object
class LinkedList:
# Function to initialize head
def __init__(self):
self.head = None
# This function is in LinkedList class. It inserts
# a new node at the beginning of Linked List.
def push(self, new_data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This function counts number of nodes in Linked List
# recursively, given 'node' as starting node using Tail Recursion.
def getCountRec(self, node, count=0):
if (not node): # Base case
return count
else:
return self.getCountRec(node.next, count+1)
# A wrapper over getCountRec()
def getCount(self):
return self.getCountRec(self.head)
# Driver code
if __name__ == '__main__':
llist = LinkedList()
llist.push(1)
llist.push(3)
llist.push(1)
llist.push(2)
llist.push(1)
# Function call
print('Count of nodes is :', llist.getCount())
# This code is contributed by garinesrija.
|
constant
|
linear
|
# Iterative Python3 program to search an element
# in linked list
# Node class
class Node:
# Function to initialise the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class
class LinkedList:
def __init__(self):
self.head = None # Initialize head as None
# This function insert a new node at the
# beginning of the linked list
def push(self, new_data):
# Create a new Node
new_node = Node(new_data)
# 3. Make next of new Node as head
new_node.next = self.head
# 4. Move the head to point to new Node
self.head = new_node
# This Function checks whether the value
# x present in the linked list
def search(self, x):
# Initialize current to head
current = self.head
# loop till current not equal to None
while current != None:
if current.data == x:
return True # data found
current = current.next
return False # Data Not found
# Driver code
if __name__ == '__main__':
# Start with the empty list
llist = LinkedList()
''' Use push() to construct below list
14->21->11->30->10 '''
llist.push(10)
llist.push(30)
llist.push(11)
llist.push(21)
llist.push(14)
# Function call
if llist.search(21):
print("Yes")
else:
print("No")
# This code is contributed by Ravi Shankar
|
constant
|
linear
|
# Recursive Python program to
# search an element in linked list
# Node class
class Node:
# Function to initialise
# the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
class LinkedList:
def __init__(self):
self.head = None # Initialize head as None
# This function insert a new node at
# the beginning of the linked list
def push(self, new_data):
# Create a new Node
new_node = Node(new_data)
# Make next of new Node as head
new_node.next = self.head
# Move the head to
# point to new Node
self.head = new_node
# Checks whether the value key
# is present in linked list
def search(self, li, key):
# Base case
if(not li):
return False
# If key is present in
# current node, return true
if(li.data == key):
return True
# Recur for remaining list
return self.search(li.next, key)
# Driver Code
if __name__ == '__main__':
li = LinkedList()
li.push(1)
li.push(2)
li.push(3)
li.push(4)
key = 4
# Function call
if li.search(li.head, key):
print("Yes")
else:
print("No")
# This code is contributed
# by Manoj Sharma
|
linear
|
linear
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.