code
stringlengths 195
7.9k
| space_complexity
stringclasses 6
values | time_complexity
stringclasses 7
values |
|---|---|---|
# Python program to update every array element with
# multiplication of previous and next numbers in array
def modify(arr, n):
# Nothing to do when array size is 1
if n <= 1:
return
# store current value of arr[0] and update it
prev = arr[0]
arr[0] = arr[0] * arr[1]
# Update rest of the array elements
for i in range(1, n-1):
# Store current value of next interaction
curr = arr[i];
# Update current value using previous value
arr[i] = prev * arr[i+1]
# Update previous value
prev = curr
# Update last array element
arr[n-1] = prev * arr[n-1]
# Driver program
arr = [2, 3, 4, 5, 6]
n = len(arr)
modify(arr, n)
for i in range (0, n):
print(arr[i],end=" ")
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
linear
|
# Python Program to shuffle a given array
from random import randint
# A function to generate a random permutation of arr[]
def randomize (arr, n):
# Start from the last element and swap one by one. We don't
# need to run for the first element that's why i > 0
for i in range(n-1,0,-1):
# Pick a random index from 0 to i
j = randint(0,i+1)
# Swap arr[i] with the element at random index
arr[i],arr[j] = arr[j],arr[i]
return arr
# Driver program to test above function.
arr = [1, 2, 3, 4, 5, 6, 7, 8]
n = len(arr)
print(randomize(arr, n))
# This code is contributed by Pratik Chhajer
|
constant
|
linear
|
# Python3 implementation of the above approach
def arrayEvenAndOdd(arr, n):
index = 0;
a = [0 for i in range(n)]
for i in range(n):
if (arr[i] % 2 == 0):
a[index] = arr[i]
ind += 1
for i in range(n):
if (arr[i] % 2 != 0):
a[index] = arr[i]
ind += 1
for i in range(n):
print(a[i], end = " ")
print()
# Driver code
arr = [ 1, 3, 2, 4, 7, 6, 9, 10 ]
n = len(arr)
# Function call
arrayEvenAndOdd(arr, n)
# This code is contributed by rohitsingh07052
|
linear
|
linear
|
# Python3 code to segregate even odd
# numbers in an array
# Function to segregate even odd numbers
def arrayEvenAndOdd(arr,n):
i = -1
j= 0
while (j!=n):
if (arr[j] % 2 ==0):
i = i+1
# Swapping even and odd numbers
arr[i],arr[j] = arr[j],arr[i]
j = j+1
# Printing segregated array
for i in arr:
print (str(i) + " " ,end='')
# Driver Code
if __name__=='__main__':
arr = [ 1 ,3, 2, 4, 7, 6, 9, 10]
n = len(arr)
arrayEvenAndOdd(arr,n)
# This code was contributed by
# Yatin Gupta
|
constant
|
linear
|
# Python3 implementation of above implementation
# This function returns k'th smallest element
# in arr[l..r] using QuickSort based method.
# ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT
from random import randint
def randomPartition(arr, l, r):
n = r - l + 1
pivot = randint(1, 100) % n
arr[l + pivot], arr[r] = arr[l + pivot], arr[r]
return partition(arr, l, r)
def kthSmallest(arr, l, r, k):
# If k is smaller than
# number of elements in array
if (k > 0 and k <= r - l + 1):
# Partition the array around last element and
# get position of pivot element in sorted array
pos = randomPartition(arr, l, r)
# If position is same as k
if (pos - l == k - 1):
return arr[pos]
# If position is more, recur for left subarray
if (pos - l > k - 1):
return kthSmallest(arr, l, pos - 1, k)
# Else recur for right subarray
return kthSmallest(arr, pos + 1, r,
k - pos + l - 1)
# If k is more than number of elements in array
return 10**9
# Standard partition process of QuickSort().
# It considers the last element as pivot and
# moves all smaller element to left of it
# and greater elements to right
def partition(arr, l, r):
x = arr[r]
i = l
for j in range(l, r):
if (arr[j] <= x):
arr[i], arr[j] = arr[j], arr[i]
i += 1
arr[i], arr[r] = arr[r], arr[i]
return i
# Driver Code
arr = [12, 3, 5, 7, 4, 19, 26]
n = len(arr)
k = 3
print("K'th smallest element is",
kthSmallest(arr, 0, n - 1, k))
# This code is contributed by Mohit Kumar
|
constant
|
nlogn
|
# Program for kth largest element in a 2d array
# sorted row-wise and column-wise
from sys import maxsize
# A structure to store an entry of heap.
# The entry contains a value from 2D array,
# row and column numbers of the value
class HeapNode:
def __init__(self, val, r, c):
self.val = val # value to be stored
self.r = r # Row number of value in 2D array
self.c = c # Column number of value in 2D array
# A utility function to minheapify the node harr[i]
# of a heap stored in harr[]
def minHeapify(harr, i, heap_size):
l = i * 2 + 1
r = i * 2 + 2
if(l < heap_size and r<heap_size and harr[l].val < harr[i].val and harr[r].val < harr[i].val):
temp= HeapNode(0,0,0)
temp=harr[r]
harr[r]=harr[i]
harr[i]=harr[l]
harr[l]=temp
minHeapify(harr ,l,heap_size)
minHeapify(harr ,r,heap_size)
if (l < heap_size and harr[l].val < harr[i].val):
temp= HeapNode(0,0,0)
temp=harr[i]
harr[i]=harr[l]
harr[l]=temp
minHeapify(harr ,l,heap_size)
# This function returns kth smallest element
# in a 2D array mat[][]
def kthSmallest(mat, n, k):
# k must be greater than 0 and smaller than n*n
if k < 0 or k > n * n:
return maxsize
# Create a min heap of elements from
# first row of 2D array
harr = [0] * n
for i in range(n):
harr[i] = HeapNode(mat[0][i], 0, i)
hr = HeapNode(0, 0, 0)
for i in range(k):
# Get current heap root
hr = harr[0]
# Get next value from column of root's value.
# If the value stored at root was last value
# in its column, then assign INFINITE as next value
nextval = mat[hr.r + 1][hr.c] if (hr.r < n - 1) else maxsize
# Update heap root with next value
harr[0] = HeapNode(nextval, hr.r + 1, hr.c)
# Heapify root
minHeapify(harr, 0, n)
# Return the value at last extracted root
return hr.val
# Driver Code
if __name__ == "__main__":
mat = [[10, 20, 30, 40],
[15, 25, 35, 45],
[25, 29, 37, 48],
[32, 33, 39, 50]]
print("7th smallest element is",
kthSmallest(mat, 4, 7))
# This code is contributed by Rishabh Chauhan
|
linear
|
nlogn
|
# This returns count of elements in matrix
# less than of equal to num
def getElementsGreaterThanOrEqual(num,n,mat):
ans = 0
for i in range(n):
# if num is less than the first element
# then no more element in matrix
# further are less than or equal to num
if (mat[i][0] > num):
return ans
# if num is greater than last element,
# it is greater than all elements
# in that row
if (mat[i][n - 1] <= num):
ans += n
continue
# This contain the col index of last element
# in matrix less than of equal
# to num
greaterThan = 0
jump = n // 2
while(jump >= 1):
while (greaterThan + jump < n and mat[i][greaterThan + jump] <= num):
greaterThan += jump
jump //= 2
ans += greaterThan + 1
return ans
# returns kth smallest index in the matrix
def kthSmallest(mat, n, k):
# We know the answer lies between
# the first and the last element
# So do a binary search on answer
# based on the number of elements
# our current element is greater than
# the elements in the matrix
l,r = mat[0][0],mat[n - 1][n - 1]
while (l <= r):
mid = l + (r - l) // 2
greaterThanOrEqualMid = getElementsGreaterThanOrEqual(mid, n, mat)
if (greaterThanOrEqualMid >= k):
r = mid - 1
else:
l = mid + 1
return l
# driver code
n = 4
mat = [[10, 20, 30, 40],[15, 25, 35, 45],[25, 29, 37, 48],[32, 33, 39, 50]]
print(f"7th smallest element is {kthSmallest(mat, 4, 7)}")
# This code is contributed by shinjanpatra
|
linear
|
nlogn
|
# Python program to implement above approach
def kthSmallest(mat, n, k):
a = [0 for i in range(n*n)]
v=0
for i in range(n):
for j in range(n):
a[v] = mat[i][j]
v += 1
a.sort()
result = a[k - 1]
return result
# driver program
mat = [ [ 10, 20, 30, 40 ],
[ 15, 25, 35, 45 ],
[ 25, 29, 37, 48 ],
[ 32, 33, 39, 50 ] ]
res = kthSmallest(mat, 4, 7)
print("7th smallest element is "+ str(res))
# This code is contributed by shinjanpatra
|
quadratic
|
quadratic
|
import heapq
def kthSmallest(matrix, k):
# n = size of matrix
n = len(matrix)
# using built-in priority queue which acts as max Heap i.e. largest element will be on top
# Kth smallest element can also be seen as largest element in a priority queue of size k
# By this logic we pop elements from priority queue when its size becomes greater than k
# thus top of priority queue is kth smallest element in matrix
maxH = []
for i in range(n):
for j in range(n):
heapq.heappush(maxH, -matrix[i][j])
if len(maxH) > k:
heapq.heappop(maxH)
return -maxH[0]
matrix = [[1, 5, 9], [10, 11, 13], [12, 13, 15]]
k = 8
print("8th smallest element is", kthSmallest(matrix, k))
# This code is comtributed by Tapesh (tapeshdua420)
|
linear
|
quadratic
|
# Python3 program to find maximum
# in arr[] of size n
# Function to find maximum
# in arr[] of size n
def largest(arr,n):
# Initialize maximum element
mx = arr[0]
# Traverse array elements from second
# and compare every element with
# current max
for i in range(1, n):
if arr[i] > mx:
mx = arr[i]
return mx
# Driver Code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
#calculating length of an array
Ans = largest(arr,n)
# display max
print ("Largest in given array is",Ans)
# This code is contributed by Jai Parkash Bhardwaj
# and improved by prophet1999
|
constant
|
linear
|
import math
class GFG :
@staticmethod
def largest( arr, n, i) :
# last index
# return the element
if (i == n - 1) :
return arr[i]
# find the maximum from rest of the array
recMax = GFG.largest(arr, n, i + 1)
# compare with i-th element and return
return max(recMax,arr[i])
# Driver Code
@staticmethod
def main( args) :
arr = [10, 324, 45, 90, 9808]
n = len(arr)
print("Largest in given array is " + str(GFG.largest(arr, n, 0)))
if __name__=="__main__":
GFG.main([])
# This code is contributed by aadityaburujwale.
|
linear
|
linear
|
# Python 3 program to find
# maximum in arr[] of size n
# returns maximum
# in arr[] of size n
def largest(arr, n):
return max(arr)
# driver code
arr = [10, 324, 45, 90, 9808]
n = len(arr)
print(largest(arr, n))
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
linear
|
# Python3 code to find largest three
# elements in an array
import sys
# Function to print three largest
# elements
def print3largest(arr, arr_size):
# There should be atleast three
# elements
if (arr_size < 3):
print(" Invalid Input ")
return
third = first = second = -sys.maxsize
for i in range(0, arr_size):
# If current element is greater
# than first
if (arr[i] > first):
third = second
second = first
first = arr[i]
# If arr[i] is in between first
# and second then update second
elif (arr[i] > second):
third = second
second = arr[i]
elif (arr[i] > third):
third = arr[i]
print("Three largest elements are",
first, second, third)
# Driver program to test above function
arr = [12, 13, 1, 10, 34, 1]
n = len(arr)
print3largest(arr, n)
# This code is contributed by Smitha Dinesh Semwal
# and edited by Ayush Singla(@ayusin51).
|
constant
|
linear
|
# Python3 code to find largest
# three elements in an array
def find3largest(arr, n):
arr = sorted(arr) # It uses Tuned Quicksort with
# avg. case Time complexity = O(nLogn)
check = 0
count = 1
for i in range(1, n + 1):
if(count < 4):
if(check != arr[n - i]):
# to handle duplicate values
print(arr[n - i], end = " ")
check = arr[n - i]
count += 1
else:
break
# Driver code
arr = [12, 45, 1, -1, 45,
54, 23, 5, 0, -10]
n = len(arr)
find3largest(arr, n)
# This code is contributed by mohit kumar
|
constant
|
nlogn
|
# Python program to implement
# the above approach
# Driver Code
V = [ 11, 65, 193, 36, 209, 664, 32 ];
V.sort()
V.reverse()
print(f"first = {V[0]}");
print(f"second = {V[1]}");
print(f"third = {V[2]}");
# This code is contributed by Saurabh Jaiswal
|
constant
|
nlogn
|
# Python3 program to find
# all elements in array
# which have at-least two
# greater elements itself.
def findElements( arr, n):
# Pick elements one by
# one and count greater
# elements. If count
# is more than 2, print
# that element.
for i in range(n):
count = 0
for j in range(0, n):
if arr[j] > arr[i]:
count = count + 1
if count >= 2 :
print(arr[i], end=" ")
# Driver code
arr = [ 2, -6 ,3 , 5, 1]
n = len(arr)
findElements(arr, n)
# This code is contributed by sunnysingh
|
constant
|
quadratic
|
# Sorting based Python 3 program
# to find all elements in array
# which have atleast two greater
# elements itself.
def findElements(arr, n):
arr.sort()
for i in range(0, n-2):
print(arr[i], end =" ")
# Driven source
arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)
# This code is contributed
# by Smitha Dinesh Semwal
|
constant
|
nlogn
|
# Python3 program to find all elements
# in array which have atleast two
# greater elements itself.
import sys
def findElements(arr, n):
first = -sys.maxsize
second = -sys.maxsize
for i in range(0, n):
# If current element is smaller
# than first then update both
# first and second
if (arr[i] > first):
second = first
first = arr[i]
# If arr[i] is in between first
# and second then update second
elif (arr[i] > second):
second = arr[i]
for i in range(0, n):
if (arr[i] < second):
print(arr[i], end =" ")
# Driver code
arr = [2, -6, 3, 5, 1]
n = len(arr)
findElements(arr, n)
# This code is contributed
# by Smitha Dinesh Semwal
|
constant
|
linear
|
# Python3 program to find mean
# and median of an array
# Function for calculating mean
def findMean(a, n):
sum = 0
for i in range(0, n):
sum += a[i]
return float(sum/n)
# Function for calculating median
def findMedian(a, n):
# First we sort the array
sorted(a)
# check for even case
if n % 2 != 0:
return float(a[int(n/2)])
return float((a[int((n-1)/2)] +
a[int(n/2)])/2.0)
# Driver code
a = [1, 3, 4, 2, 7, 5, 8, 6]
n = len(a)
# Function call
print("Mean =", findMean(a, n))
print("Median =", findMedian(a, n))
# This code is contributed by Smitha Dinesh Semwal
|
constant
|
nlogn
|
# python3 program to find med in
# stream of running integers
from heapq import *
# function to calculate med of stream
def printMedians(arr, n):
# max heap to store the smaller half elements
s = []
# min heap to store the greater half elements
g = []
heapify(s)
heapify(g)
med = arr[0]
heappush(s, arr[0])
print(med)
# reading elements of stream one by one
for i in range(1, n):
x = arr[i]
# case1(left side heap has more elements)
if len(s) > len(g):
if x < med:
heappush(g, heappop(s))
heappush(s, x)
else:
heappush(g, x)
med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2
# case2(both heaps are balanced)
elif len(s) == len(g):
if x < med:
heappush(s, x)
med = nlargest(1, s)[0]
else:
heappush(g, x)
med = nsmallest(1, g)[0]
# case3(right side heap has more elements)
else:
if x > med:
heappush(s, heappop(g))
heappush(g, x)
else:
heappush(s, x)
med = (nlargest(1, s)[0] + nsmallest(1, g)[0])/2
print(med)
# Driver program to test above functions
arr = [5, 15, 10, 20, 3]
printMedians(arr, len(arr))
# This code is contributed by cavi4762.
|
linear
|
nlogn
|
# Python3 program to find minimum
# product of k elements in an array
import math
import heapq
def minProduct(arr, n, k):
heapq.heapify(arr)
count = 0
ans = 1
# One by one extract
# items from min heap
while ( arr ) and count < k:
x = heapq.heappop(arr)
ans = ans * x
count = count + 1
return ans;
# Driver method
arr = [198, 76, 544, 123, 154, 675]
k = 2
n = len(arr)
print ("Minimum product is",
minProduct(arr, n, k))
|
linear
|
nlogn
|
# Python program to find out k maximum
# non-overlapping subarray sums.
# Function to compute k
# maximum sub-array sums.
def kmax(arr, k, n):
# In each iteration it will give
# the ith maximum subarray sum.
for c in range(k):
# Kadane's algorithm
max_so_far = -float("inf")
max_here = 0
# compute starting and ending
# index of each of the subarray
start = 0
end = 0
s = 0
for i in range(n):
max_here += arr[i]
if (max_so_far < max_here):
max_so_far = max_here
start = s
end = i
if (max_here < 0):
max_here = 0
s = i + 1
# Print out the result
print("Maximum non-overlapping sub-array sum",
c + 1, ": ", max_so_far, ", starting index: ",
start, ", ending index: ", end, ".", sep = "")
# Replace all elements of the maximum subarray
# by -infinity. Hence these places cannot form
# maximum sum subarray again.
for l in range(start, end+1):
arr[l] = -float("inf")
print()
# Driver Program
# Test case 1
arr1 = [4, 1, 1, -1, -3, -5, 6, 2, -6, -2]
k1 = 3
n1 = len(arr1)
# Function calling
kmax(arr1, k1, n1)
# Test case 2
arr2 = [5, 1, 2, -6, 2, -1, 3, 1]
k2 = 2
n2 = len(arr2)
# Function calling
kmax(arr2, k2, n2)
|
constant
|
quadratic
|
# Python 3 for printing smallest
# k numbers in order
# Function to print smallest k
# numbers in arr[0..n-1]
def printSmall(arr, n, k):
# For each arr[i] find whether
# it is a part of n-smallest
# with insertion sort concept
for i in range(k, n):
# find largest from first k-elements
max_var = arr[k - 1]
pos = k - 1
for j in range(k - 2, -1, -1):
if (arr[j] > max_var):
max_var = arr[j]
pos = j
# if largest is greater than arr[i]
# shift all element one place left
if (max_var > arr[i]):
j = pos
while (j < k - 1):
arr[j] = arr[j + 1]
j += 1
# make arr[k-1] = arr[i]
arr[k - 1] = arr[i]
# print result
for i in range(0, k):
print(arr[i], end=" ")
# Driver program
arr = [1, 5, 8, 9, 6, 7, 3, 4, 2, 0]
n = len(arr)
k = 5
printSmall(arr, n, k)
|
constant
|
quadratic
|
# Python3 program to find
# k-th absolute difference
# between two elements
from bisect import bisect as upper_bound
# returns number of pairs with
# absolute difference less than
# or equal to mid.
def countPairs(a, n, mid):
res = 0
for i in range(n):
# Upper bound returns pointer to position
# of next higher number than a[i]+mid in
# a[i..n-1]. We subtract (a + i + 1) from
# this position to count
res += upper_bound(a, a[i] + mid)
return res
# Returns k-th absolute difference
def kthDiff(a, n, k):
# Sort array
a = sorted(a)
# Minimum absolute difference
low = a[1] - a[0]
for i in range(1, n - 1):
low = min(low, a[i + 1] - a[i])
# Maximum absolute difference
high = a[n - 1] - a[0]
# Do binary search for k-th absolute difference
while (low < high):
mid = (low + high) >> 1
if (countPairs(a, n, mid) < k):
low = mid + 1
else:
high = mid
return low
# Driver code
k = 3
a = [1, 2, 3, 4]
n = len(a)
print(kthDiff(a, n, k))
# This code is contributed by Mohit Kumar
|
constant
|
nlogn
|
# Python3 program to find second
# largest element in an array
# Function to print the
# second largest elements
def print2largest(arr,
arr_size):
# There should be
# atleast two elements
if (arr_size < 2):
print(" Invalid Input ")
return
# Sort the array
arr.sort
# Start from second last
# element as the largest
# element is at last
for i in range(arr_size-2,
-1, -1):
# If the element is not
# equal to largest element
if (arr[i] != arr[arr_size - 1]) :
print("The second largest element is",
arr[i])
return
print("There is no second largest element")
# Driver code
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)
# This code is contributed by divyeshrabadiya07
|
constant
|
nlogn
|
# Python3 program to find
# second largest element
# in an array
# Function to print
# second largest elements
def print2largest(arr, arr_size):
# There should be atleast
# two elements
if (arr_size < 2):
print(" Invalid Input ");
return;
largest = second = -2454635434;
# Find the largest element
for i in range(0, arr_size):
largest = max(largest, arr[i]);
# Find the second largest element
for i in range(0, arr_size):
if (arr[i] != largest):
second = max(second, arr[i]);
if (second == -2454635434):
print("There is no second " +
"largest element");
else:
print("The second largest " +
"element is \n", second);
# Driver code
if __name__ == '__main__':
arr = [12, 35, 1,
10, 34, 1];
n = len(arr);
print2largest(arr, n);
# This code is contributed by shikhasingrajput
|
constant
|
linear
|
# Python program to
# find second largest
# element in an array
# Function to print the
# second largest elements
def print2largest(arr, arr_size):
# There should be atleast
# two elements
if (arr_size < 2):
print(" Invalid Input ")
return
first = second = -2147483648
for i in range(arr_size):
# If current element is
# smaller than first
# then update both
# first and second
if (arr[i] > first):
second = first
first = arr[i]
# If arr[i] is in
# between first and
# second then update second
elif (arr[i] > second and arr[i] != first):
second = arr[i]
if (second == -2147483648):
print("There is no second largest element")
else:
print("The second largest element is", second)
# Driver program to test
# above function
arr = [12, 35, 1, 10, 34, 1]
n = len(arr)
print2largest(arr, n)
# This code is contributed
# by Anant Agarwal.
|
constant
|
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)
|
linear
|
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 simple approach to print smallest
# and second smallest element.
# driver code
arr = [111, 13, 25, 9, 34, 1]
n = len(arr)
# sorting the array using
# in-built sort function
arr.sort()
# printing the desired element
print("smallest element is "+str(arr[0]))
print("second smallest element is "+str(arr[1]))
# This code is contributed by shinjanpatra
|
constant
|
nlogn
|
# Python program to find smallest and second smallest elements
import math
def print2Smallest(arr):
# There should be atleast two elements
arr_size = len(arr)
if arr_size < 2:
print ("Invalid Input")
return
first = second = math.inf
for i in range(0, arr_size):
# If current element is smaller than first then
# update both first and second
if arr[i] < first:
second = first
first = arr[i]
# If arr[i] is in between first and second then
# update second
elif (arr[i] < second and arr[i] != first):
second = arr[i];
if (second == math.inf):
print ("No second smallest element")
else:
print ('The smallest element is',first,'and', \
' second smallest element is',second)
# Driver function to test above function
arr = [12, 13, 1, 10, 34, 1]
print2Smallest(arr)
# This code is contributed by Devesh Agrawal
|
constant
|
linear
|
# Python3 program to find the smallest
# elements missing in a sorted array.
def findFirstMissing(array, start, end):
if (start > end):
return end + 1
if (start != array[start]):
return start;
mid = int((start + end) / 2)
# Left half has all elements
# from 0 to mid
if (array[mid] == mid):
return findFirstMissing(array,
mid+1, end)
return findFirstMissing(array,
start, mid)
# driver program to test above function
arr = [0, 1, 2, 3, 4, 5, 6, 7, 10]
n = len(arr)
print("Smallest missing element is",
findFirstMissing(arr, 0, n-1))
# This code is contributed by Smitha Dinesh Semwal
|
logn
|
logn
|
# Python3 program for above approach
# Function to find Smallest
# Missing in Sorted Array
def findSmallestMissinginSortedArray(arr):
# Check if 0 is missing
# in the array
if (arr[0] != 0):
return 0
# Check is all numbers 0 to n - 1
# are present in array
if (arr[-1] == len(arr) - 1):
return len(arr)
first = arr[0]
return findFirstMissing(arr, 0,
len(arr) - 1, first)
# Function to find missing element
def findFirstMissing(arr, start, end, first):
if (start < end):
mid = int((start + end) / 2)
# Index matches with value
# at that index, means missing
# element cannot be upto that point
if (arr[mid] != mid + first):
return findFirstMissing(arr, start,
mid, first)
else:
return findFirstMissing(arr, mid + 1,
end, first)
return start + first
# Driver code
arr = [ 0, 1, 2, 3, 4, 5, 7 ]
n = len(arr)
# Function Call
print("First Missing element is :",
findSmallestMissinginSortedArray(arr))
# This code is contributed by rag2127
|
logn
|
logn
|
# Python code to implement the approach
# Function to find the maximum sum
def findMaxSum(arr, N):
# Declare dp array
dp = [[0 for i in range(2)] for j in range(N)]
if (N == 1):
return arr[0]
# Initialize the values in dp array
dp[0][0] = 0
dp[0][1] = arr[0]
# Loop to find the maximum possible sum
for i in range(1,N):
dp[i][1] = dp[i - 1][0] + arr[i]
dp[i][0] = max(dp[i - 1][1], dp[i - 1][0])
# Return the maximum sum
return max(dp[N - 1][0], dp[N - 1][1])
# Driver Code
# Creating the array
arr = [ 5, 5, 10, 100, 10, 5 ]
N = len(arr)
# Function call
print(findMaxSum(arr, N))
# This code is contributed by shinjanpatra
|
linear
|
linear
|
# Python code to implement the approach
# Function to return max sum such that
# no two elements are adjacent
def findMaxSum(arr, n):
incl = 0
excl = 0
for i in arr:
# Current max excluding i
new_excl = max (excl, incl)
# Current max including i
incl = excl + i
excl = new_excl
# Return max of incl and excl
return max(excl, incl)
# Driver code
if __name__ == "__main__":
arr = [5, 5, 10, 100, 10, 5]
N = 6
# Function call
print (findMaxSum(arr, N))
# This code is contributed by Kalai Selvan
|
constant
|
linear
|
# Python 3 program to demonstrate working of Square Root
# Decomposition.
from math import sqrt
MAXN = 10000
SQRSIZE = 100
arr = [0]*(MAXN) # original array
block = [0]*(SQRSIZE) # decomposed array
blk_sz = 0 # block size
# Time Complexity : O(1)
def update(idx, val):
blockNumber = idx // blk_sz
block[blockNumber] += val - arr[idx]
arr[idx] = val
# Time Complexity : O(sqrt(n))
def query(l, r):
sum = 0
while (l < r and l % blk_sz != 0 and l != 0):
# traversing first block in range
sum += arr[l]
l += 1
while (l + blk_sz - 1 <= r):
# traversing completely overlapped blocks in range
sum += block[l//blk_sz]
l += blk_sz
while (l <= r):
# traversing last block in range
sum += arr[l]
l += 1
return sum
# Fills values in input[]
def preprocess(input, n):
# initiating block pointer
blk_idx = -1
# calculating size of block
global blk_sz
blk_sz = int(sqrt(n))
# building the decomposed array
for i in range(n):
arr[i] = input[i];
if (i % blk_sz == 0):
# entering next block
# incrementing block pointer
blk_idx += 1;
block[blk_idx] += arr[i]
# Driver code
# We have used separate array for input because
# the purpose of this code is to explain SQRT
# decomposition in competitive programming where
# we have multiple inputs.
input= [1, 5, 2, 4, 6, 1, 3, 5, 7, 10]
n = len(input)
preprocess(input, n)
print("query(3,8) : ",query(3, 8))
print("query(1,6) : ",query(1, 6))
update(8, 0)
print("query(8,8) : ",query(8, 8))
# This code is contributed by Sanjit_Prasad
|
linear
|
linear
|
# Python3 program to do range minimum
# query using sparse table
import math
# Fills lookup array lookup[][] in
# bottom up manner.
def buildSparseTable(arr, n):
# Initialize M for the intervals
# with length 1
for i in range(0, n):
lookup[i][0] = arr[i]
j = 1
# Compute values from smaller to
# bigger intervals
while (1 << j) <= n:
# Compute minimum value for all
# intervals with size 2^j
i = 0
while (i + (1 << j) - 1) < n:
# For arr[2][10], we compare arr[lookup[0][7]]
# and arr[lookup[3][10]]
if (lookup[i][j - 1] <
lookup[i + (1 << (j - 1))][j - 1]):
lookup[i][j] = lookup[i][j - 1]
else:
lookup[i][j] = \
lookup[i + (1 << (j - 1))][j - 1]
i += 1
j += 1
# Returns minimum of arr[L..R]
def query(L, R):
# Find highest power of 2 that is smaller
# than or equal to count of elements in
# given range. For [2, 10], j = 3
j = int(math.log2(R - L + 1))
# Compute minimum of last 2^j elements
# with first 2^j elements in range.
# For [2, 10], we compare arr[lookup[0][3]]
# and arr[lookup[3][3]],
if lookup[L][j] <= lookup[R - (1 << j) + 1][j]:
return lookup[L][j]
else:
return lookup[R - (1 << j) + 1][j]
# Driver Code
if __name__ == "__main__":
a = [7, 2, 3, 0, 5, 10, 3, 12, 18]
n = len(a)
MAX = 500
# lookup[i][j] is going to store minimum
# value in arr[i..j]. Ideally lookup table
# size should not be fixed and should be
# determined using n Log n. It is kept
# constant to keep code simple.
lookup = [[0 for i in range(MAX)]
for j in range(MAX)]
buildSparseTable(a, n)
print(query(0, 4))
print(query(4, 7))
print(query(7, 8))
# This code is contributed by Rituraj Jain
|
nlogn
|
nlogn
|
# Python3 program to do range minimum
# query using sparse table
import math
# Fills lookup array lookup[][] in
# bottom up manner.
def buildSparseTable(arr, n):
# GCD of single element is element itself
for i in range(0, n):
table[i][0] = arr[i]
# Build sparse table
j = 1
while (1 << j) <= n:
i = 0
while i <= n - (1 << j):
table[i][j] = math.gcd(table[i][j - 1],
table[i + (1 << (j - 1))][j - 1])
i += 1
j += 1
# Returns minimum of arr[L..R]
def query(L, R):
# Find highest power of 2 that is smaller
# than or equal to count of elements in
# given range. For [2, 10], j = 3
j = int(math.log2(R - L + 1))
# Compute GCD of last 2^j elements with
# first 2^j elements in range.
# For [2, 10], we find GCD of arr[lookup[0][3]]
# and arr[lookup[3][3]],
return math.gcd(table[L][j],
table[R - (1 << j) + 1][j])
# Driver Code
if __name__ == "__main__":
a = [7, 2, 3, 0, 5, 10, 3, 12, 18]
n = len(a)
MAX = 500
# lookup[i][j] is going to store minimum
# value in arr[i..j]. Ideally lookup table
# size should not be fixed and should be
# determined using n Log n. It is kept
# constant to keep code simple.
table = [[0 for i in range(MAX)]
for j in range(MAX)]
buildSparseTable(a, n)
print(query(0, 2))
print(query(1, 3))
print(query(4, 5))
# This code is contributed by Rituraj Jain
|
nlogn
|
nlogn
|
# 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
|
# Python3 program to get updated array
# after many array range add operation
# Utility method to add value
# val, to range [lo, hi]
def add(arr, N, lo, hi, val):
arr[lo] += val
if (hi != N - 1):
arr[hi + 1] -= val
# Utility method to get actual
# array from operation array
def updateArray(arr, N):
# convert array into prefix sum array
for i in range(1, N):
arr[i] += arr[i - 1]
# method to print final updated array
def printArr(arr, N):
updateArray(arr, N)
for i in range(N):
print(arr[i], end=" ")
print()
# Driver code
N = 6
arr = [0 for i in range(N)]
# Range add Queries
add(arr, N, 0, 2, 100)
add(arr, N, 1, 5, 100)
add(arr, N, 2, 3, 100)
printArr(arr, N)
# This code is contributed by Anant Agarwal.
|
constant
|
linear
|
# Python program for
# queries of GCD excluding
# given range of elements.
# Calculating GCD
# using euclid algorithm
def GCD(a,b):
if (b==0):
return a
return GCD (b, a%b)
# Filling the prefix
# and suffix array
def FillPrefixSuffix(prefix,arr,suffix,n):
# Filling the prefix array
# following relation
# prefix(i) = GCD(prefix(i-1), arr(i))
prefix[0] = arr[0]
for i in range(1,n):
prefix[i] = GCD (prefix[i-1], arr[i])
# Filling the suffix
# array following the
# relation suffix(i) = GCD(suffix(i+1), arr(i))
suffix[n-1] = arr[n-1]
for i in range(n-2,-1,-1):
suffix[i] = GCD (suffix[i+1], arr[i])
# To calculate gcd of
# the numbers outside range
def GCDoutsideRange(l,r,prefix,suffix,n):
# If l=0, we need to tell GCD of numbers
# from r+1 to n
if (l==0):
return suffix[r+1]
# If r=n-1 we need to return the gcd of
# numbers from 1 to l
if (r==n-1):
return prefix[l-1]
return GCD(prefix[l-1], suffix[r+1])
# Driver code
arr = [2, 6, 9]
n = len(arr)
prefix=[]
suffix=[]
for i in range(n+1):
prefix.append(0)
suffix.append(0)
FillPrefixSuffix(prefix, arr, suffix, n)
l = 0
r = 0
print(GCDoutsideRange(l, r, prefix, suffix, n))
l = 1
r = 1
print(GCDoutsideRange(l, r, prefix, suffix, n))
l = 1
r = 2
print(GCDoutsideRange(l, r, prefix, suffix, n))
# This code is contributed
# by Anant Agarwal.
|
linear
|
nlogn
|
# function to count elements within given range
def countInRange(arr, n, x, y):
# initialize result
count = 0;
for i in range(n):
# check if element is in range
if (arr[i] >= x and arr[i] <= y):
count += 1
return count
# driver function
arr = [1, 3, 4, 9, 10, 3]
n = len(arr)
# Answer queries
i = 1
j = 4
print(countInRange(arr, n, i, j))
i = 9
j = 12
print(countInRange(arr, n, i, j))
|
constant
|
linear
|
# function to find first index >= x
def lowerIndex(arr, n, x):
l = 0
h = n-1
while (l <= h):
mid = int((l + h)//2)
if (arr[mid] >= x):
h = mid - 1
else:
l = mid + 1
return l
# function to find last index <= x
def upperIndex(arr, n, x):
l = 0
h = n-1
while (l <= h):
mid = int((l + h)//2)
if (arr[mid] <= x):
l = mid + 1
else:
h = mid - 1
return h
# function to count elements within given range
def countInRange(arr, n, x, y):
# initialize result
count = 0;
count = upperIndex(arr, n, y) - lowerIndex(arr, n, x) + 1;
return count
# driver function
arr = [1, 3, 4, 9, 10, 3]
# Preprocess array
arr.sort()
n = len(arr)
# Answer queries
i = 1
j = 4
print(countInRange(arr, n, i, j))
i = 9
j = 12
print(countInRange(arr, n, i, j))
|
constant
|
nlogn
|
# implementation of finding number
# represented by binary subarray
from math import pow
# Fills pre[]
def precompute(arr, n, pre):
pre[n - 1] = arr[n - 1] * pow(2, 0)
i = n - 2
while(i >= 0):
pre[i] = (pre[i + 1] + arr[i] *
(1 << (n - 1 - i)))
i -= 1
# returns the number represented by
# a binary subarray l to r
def decimalOfSubarr(arr, l, r, n, pre):
# if r is equal to n-1 r+1 does not exist
if (r != n - 1):
return ((pre[l] - pre[r + 1]) /
(1 << (n - 1 - r)))
return pre[l] / (1 << (n - 1 - r))
# Driver Code
if __name__ == '__main__':
arr = [1, 0, 1, 0, 1, 1]
n = len(arr)
pre = [0 for i in range(n)]
precompute(arr, n, pre)
print(int(decimalOfSubarr(arr, 2, 4, n, pre)))
print(int(decimalOfSubarr(arr, 4, 5, n, pre)))
# This code is contributed by
# Surendra_Gangwar
|
linear
|
linear
|
# Python3 program to perform range
# queries over range queries.
import math
max = 10000
# For prefix sum array
def update(arr, l):
arr[l] += arr[l - 1]
# This function is used to apply square root
# decomposition in the record array
def record_func(block_size, block,
record, l, r, value):
# Traversing first block in range
while (l < r and
l % block_size != 0 and
l != 0):
record[l] += value
l += 1
# Traversing completely overlapped
# blocks in range
while (l + block_size <= r + 1):
block[l // block_size] += value
l += block_size
# Traversing last block in range
while (l <= r):
record[l] += value
l += 1
# Function to print the resultant array
def print_array(arr, n):
for i in range(n):
print(arr[i], end = " ")
# Driver code
if __name__ == "__main__":
n = 5
m = 5
arr = [0] * n
record = [0] * m
block_size = (int)(math.sqrt(m))
block = [0] * max
command = [ [ 1, 1, 2 ],
[ 1, 4, 5 ],
[ 2, 1, 2 ],
[ 2, 1, 3 ],
[ 2, 3, 4 ] ]
for i in range(m - 1, -1, -1):
# If query is of type 2 then function
# call to record_func
if (command[i][0] == 2):
x = i // (block_size)
record_func(block_size, block,
record, command[i][1] - 1,
command[i][2] - 1,
(block[x] + record[i] + 1))
# If query is of type 1 then simply add
# 1 to the record array
else:
record[i] += 1
# Merging the value of the block
# in the record array
for i in range(m):
check = (i // block_size)
record[i] += block[check]
for i in range(m):
# If query is of type 1 then the array
# elements are over-written by the record
# array
if (command[i][0] == 1):
arr[command[i][1] - 1] += record[i]
if ((command[i][2] - 1) < n - 1):
arr[(command[i][2])] -= record[i]
# The prefix sum of the array
for i in range(1, n):
update(arr, i)
# Printing the resultant array
print_array(arr, n)
# This code is contributed by chitranayal
|
linear
|
logn
|
# Python 3 program to count the
# number of indexes in range L R
# such that Ai = Ai + 1
# function that answers every
# query in O(r-l)
def answer_query(a, n, l, r):
# traverse from l to r and
# count the required indexes
count = 0
for i in range(l, r):
if (a[i] == a[i + 1]):
count += 1
return count
# Driver Code
a = [1, 2, 2, 2, 3, 3, 4, 4, 4]
n = len(a)
# 1-st query
L = 1
R = 8
print(answer_query(a, n, L, R))
# 2nd query
L = 0
R = 4
print(answer_query(a, n, L, R))
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
constant
|
# Python program to count
# the number of indexes in
# range L R such that Ai=Ai+1
N = 1000
# array to store count
# of index from 0 to
# i that obey condition
prefixans = [0] * N;
# precomputing
# prefixans[] array
def countIndex(a, n) :
global N, prefixans
# traverse to compute
# the prefixans[] array
for i in range(0, n - 1) :
if (a[i] == a[i + 1]) :
prefixans[i] = 1
if (i != 0) :
prefixans[i] = (prefixans[i] +
prefixans[i - 1])
# def that answers
# every query in O(1)
def answer_query(l, r) :
global N, prefixans
if (l == 0) :
return prefixans[r - 1]
else :
return (prefixans[r - 1] -
prefixans[l - 1])
# Driver Code
a = [1, 2, 2, 2,
3, 3, 4, 4, 4]
n = len(a)
# pre-computation
countIndex(a, n)
# 1-st query
L = 1
R = 8
print (answer_query(L, R))
# 2nd query
L = 0
R = 4
print (answer_query(L, R))
# This code is contributed by
# Manish Shaw(manishshaw1)
|
linear
|
linear
|
# Python program to find maximum contiguous subarray
# Function to find the maximum contiguous subarray
from sys import maxint
def maxSubArraySum(a, size):
max_so_far = -maxint - 1
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
# Driver function to check the above function
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print "Maximum contiguous sum is", maxSubArraySum(a, len(a))
# This code is contributed by _Devesh Agrawal_
|
constant
|
linear
|
# Python program to print largest contiguous array sum
from sys import maxsize
# Function to find the maximum contiguous subarray
# and print its starting and end index
def maxSubArraySum(a, size):
max_so_far = -maxsize - 1
max_ending_here = 0
start = 0
end = 0
s = 0
for i in range(0, size):
max_ending_here += a[i]
if max_so_far < max_ending_here:
max_so_far = max_ending_here
start = s
end = i
if max_ending_here < 0:
max_ending_here = 0
s = i+1
print("Maximum contiguous sum is %d" % (max_so_far))
print("Starting Index %d" % (start))
print("Ending Index %d" % (end))
# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
maxSubArraySum(a, len(a))
|
constant
|
linear
|
# Returns maximum profit with
# two transactions on a given
# list of stock prices price[0..n-1]
def maxProfit(price, n):
# Create profit array and initialize it as 0
profit = [0]*n
# Get the maximum profit
# with only one transaction
# allowed. After this loop,
# profit[i] contains maximum
# profit from price[i..n-1]
# using at most one trans.
max_price = price[n-1]
for i in range(n-2, 0, -1):
if price[i] > max_price:
max_price = price[i]
# we can get profit[i] by
# taking maximum of:
# a) previous maximum,
# i.e., profit[i+1]
# b) profit by buying at
# price[i] and selling at
# max_price
profit[i] = max(profit[i+1], max_price - price[i])
# Get the maximum profit
# with two transactions allowed
# After this loop, profit[n-1]
# contains the result
min_price = price[0]
for i in range(1, n):
if price[i] < min_price:
min_price = price[i]
# Maximum profit is maximum of:
# a) previous maximum,
# i.e., profit[i-1]
# b) (Buy, Sell) at
# (min_price, A[i]) and add
# profit of other trans.
# stored in profit[i]
profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price))
result = profit[n-1]
return result
# Driver function
price = [2, 30, 15, 10, 8, 25, 80]
print ("Maximum profit is", maxProfit(price, len(price)))
# This code is contributed by __Devesh Agrawal__
|
linear
|
linear
|
import sys
def maxtwobuysell(arr, size):
first_buy = -sys.maxsize;
first_sell = 0;
second_buy = -sys.maxsize;
second_sell = 0;
for i in range(size):
first_buy = max(first_buy, -arr[i]);
first_sell = max(first_sell, first_buy + arr[i]);
second_buy = max(second_buy, first_sell - arr[i]);
second_sell = max(second_sell, second_buy + arr[i]);
return second_sell;
if __name__ == '__main__':
arr = [ 2, 30, 15, 10, 8, 25, 80 ];
size = len(arr);
print(maxtwobuysell(arr, size));
# This code is contributed by gauravrajput1
|
constant
|
linear
|
# Python3 program to find
# minimum average subarray
# Prints beginning and ending
# indexes of subarray of size k
# with minimum average
def findsubarrayleast(arr, k, n):
min = 999999
minindex = 0
for i in range(n-k+1):
sum = 0
j = i
for j in range(i, i+k):
sum += arr[j]
if sum < min:
min = sum
minindex = i
# printing the desired subarray
print("subarray with minimum average is: ", end='')
for i in range(minindex, minindex+k):
print(arr[i], end=" ")
# Driver Code
arr = [20, 3, 13, 5, 10, 14, 8, 5, 11, 9, 1, 11]
k = 9 # Subarray size
n = len(arr)
findsubarrayleast(arr, k, n)
# This code is contributed by Aarti_Rathi
|
constant
|
quadratic
|
# Python3 program to find
# minimum average subarray
# Prints beginning and ending
# indexes of subarray of size k
# with minimum average
def findMinAvgSubarray(arr, n, k):
# k must be smaller than or equal to n
if (n < k): return 0
# Initialize beginning index of result
res_index = 0
# Compute sum of first subarray of size k
curr_sum = 0
for i in range(k):
curr_sum += arr[i]
# Initialize minimum sum as current sum
min_sum = curr_sum
# Traverse from (k + 1)'th
# element to n'th element
for i in range(k, n):
# Add current item and remove first
# item of previous subarray
curr_sum += arr[i] - arr[i-k]
# Update result if needed
if (curr_sum < min_sum):
min_sum = curr_sum
res_index = (i - k + 1)
print("Subarray between [", res_index,
", ", (res_index + k - 1),
"] has minimum average")
# Driver Code
arr = [3, 7, 90, 20, 10, 50, 40]
k = 3 # Subarray size
n = len(arr)
findMinAvgSubarray(arr, n, k)
# This code is contributed by Anant Agarwal.
|
constant
|
linear
|
# Python3 code to Find the minimum
# distance between two numbers
def minDist(arr, n, x, y):
min_dist = 99999999
for i in range(n):
for j in range(i + 1, n):
if (x == arr[i] and y == arr[j] or
y == arr[i] and x == arr[j]) and min_dist > abs(i-j):
min_dist = abs(i-j)
return min_dist
# Driver code
arr = [3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print("Minimum distance between ", x, " and ",
y, "is", minDist(arr, n, x, y))
# This code is contributed by "Abhishek Sharma 44"
|
constant
|
quadratic
|
import sys
def minDist(arr, n, x, y):
#previous index and min distance
i=0
p=-1
min_dist = sys.maxsize;
for i in range(n):
if(arr[i] ==x or arr[i] == y):
#we will check if p is not equal to -1 and
#If the element at current index matches with
#the element at index p , If yes then update
#the minimum distance if needed
if(p != -1 and arr[i] != arr[p]):
min_dist = min(min_dist,i-p)
#update the previous index
p=i
#If distance is equal to int max
if(min_dist == sys.maxsize):
return -1
return min_dist
# Driver program to test above function */
arr = [3, 5, 4, 2, 6, 3, 0, 0, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print ("Minimum distance between %d and %d is %d\n"%( x, y,minDist(arr, n, x, y)));
# This code is contributed by Shreyanshi Arun.
|
constant
|
linear
|
# Python program to Find the minimum
# distance between two numbers
import sys
def minDist(arr, n, x, y) :
# idx1 and idx2 will store indices of
# x or y and min_dist will store the minimum difference
idx1=-1; idx2=-1; min_dist = sys.maxsize;
for i in range(n) :
# if current element is x then change idx1
if arr[i]==x :
idx1=i
# if current element is y then change idx2
elif arr[i]==y :
idx2=i
# if x and y both found in array
# then only find the difference and store it in min_dist
if idx1!=-1 and idx2!=-1 :
min_dist=min(min_dist,abs(idx1-idx2));
# if left or right did not found in array
# then return -1
if idx1==-1 or idx2==-1 :
return -1
# return the minimum distance
else :
return min_dist
# Driver code
if __name__ == "__main__" :
arr = [ 3, 5, 4, 2, 6, 5, 6, 6, 5, 4, 8, 3]
n = len(arr)
x = 3
y = 6
print ("Minimum distance between %d and %d is %d\n"%( x, y,minDist(arr, n, x, y)));
# this code is contributed by aditya942003patil
|
constant
|
linear
|
# User function Template
def getMinDiff(arr, n, k):
arr.sort()
ans = arr[n - 1] - arr[0] # Maximum possible height difference
tempmin = arr[0]
tempmax = arr[n - 1]
for i in range(1, n):
if arr[i] < k:
continue
tempmin = min(arr[0] + k, arr[i] - k)
# Minimum element when we
# add k to whole array
# Maximum element when we
tempmax = max(arr[i - 1] + k, arr[n - 1] - k)
# subtract k from whole array
ans = min(ans, tempmax - tempmin)
return ans
# Driver Code Starts
k = 6
n = 6
arr = [7, 4, 8, 8, 8, 9]
ans = getMinDiff(arr, n, k)
print(ans)
# This code is contributed by ninja_hattori.
|
constant
|
nlogn
|
# Python3 program to find Minimum
# number of jumps to reach end
# Returns minimum number of jumps
# to reach arr[h] from arr[l]
def minJumps(arr, l, h):
# Base case: when source and
# destination are same
if (h == l):
return 0
# when nothing is reachable
# from the given source
if (arr[l] == 0):
return float('inf')
# Traverse through all the points
# reachable from arr[l]. Recursively
# get the minimum number of jumps
# needed to reach arr[h] from
# these reachable points.
min = float('inf')
for i in range(l + 1, h + 1):
if (i < l + arr[l] + 1):
jumps = minJumps(arr, i, h)
if (jumps != float('inf') and
jumps + 1 < min):
min = jumps + 1
return min
# Driver program to test above function
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
n = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr, 0, n-1))
# This code is contributed by Soumen Ghosh
|
linear
|
np
|
# Python3 program to find Minimum
# number of jumps to reach end
# Returns minimum number of jumps
# to reach arr[n-1] from arr[0]
def minJumps(arr, n):
jumps = [0 for i in range(n)]
if (n == 0) or (arr[0] == 0):
return float('inf')
jumps[0] = 0
# Find the minimum number of
# jumps to reach arr[i] from
# arr[0] and assign this
# value to jumps[i]
for i in range(1, n):
jumps[i] = float('inf')
for j in range(i):
if (i <= j + arr[j]) and (jumps[j] != float('inf')):
jumps[i] = min(jumps[i], jumps[j] + 1)
break
return jumps[n-1]
# Driver Program to test above function
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
size = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr, size))
# This code is contributed by Soumen Ghosh
|
linear
|
np
|
# Python3 program to find Minimum
# number of jumps to reach end
# Returns Minimum number of
# jumps to reach end
def minJumps(arr, n):
# jumps[0] will hold the result
jumps = [0 for i in range(n)]
# Minimum number of jumps needed
# to reach last element from
# last elements itself is always 0
# jumps[n-1] is also initialized to 0
# Start from the second element,
# move from right to left and
# construct the jumps[] array where
# jumps[i] represents minimum number
# of jumps needed to reach arr[m-1]
# form arr[i]
for i in range(n-2, -1, -1):
# If arr[i] is 0 then arr[n-1]
# can't be reached from here
if (arr[i] == 0):
jumps[i] = float('inf')
# If we can directly reach to
# the end point from here then
# jumps[i] is 1
elif (arr[i] >= n - i - 1):
jumps[i] = 1
# Otherwise, to find out the
# minimum number of jumps
# needed to reach arr[n-1],
# check all the points
# reachable from here and
# jumps[] value for those points
else:
# initialize min value
min = float('inf')
# following loop checks with
# all reachable points and
# takes the minimum
for j in range(i + 1, n):
if (j <= arr[i] + i):
if (min > jumps[j]):
min = jumps[j]
# Handle overflow
if (min != float('inf')):
jumps[i] = min + 1
else:
# or INT_MAX
jumps[i] = min
return jumps[0]
# Driver program to test above function
arr = [1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9]
n = len(arr)
print('Minimum number of jumps to reach',
'end is', minJumps(arr, n-1))
# This code is contributed by Soumen Ghosh
|
linear
|
quadratic
|
# Dynamic Programming based Python
# implementation of Maximum Sum
# Increasing Subsequence (MSIS)
# problem
# maxSumIS() returns the maximum
# sum of increasing subsequence
# in arr[] of size n
def maxSumIS(arr, n):
max = 0
msis = [0 for x in range(n)]
# Initialize msis values
# for all indexes
for i in range(n):
msis[i] = arr[i]
# Compute maximum sum
# values in bottom up manner
for i in range(1, n):
for j in range(i):
if (arr[i] > arr[j] and
msis[i] < msis[j] + arr[i]):
msis[i] = msis[j] + arr[i]
# Pick maximum of
# all msis values
for i in range(n):
if max < msis[i]:
max = msis[i]
return max
# Driver Code
arr = [1, 101, 2, 3, 100, 4, 5]
n = len(arr)
print("Sum of maximum sum increasing " +
"subsequence is " +
str(maxSumIS(arr, n)))
# This code is contributed
# by Bhavya Jain
|
linear
|
quadratic
|
# Python3 program to find Smallest
# subarray with sum greater
# than a given value
# Returns length of smallest subarray
# with sum greater than x. If there
# is no subarray with given sum,
# then returns n+1
def smallestSubWithSum(arr, n, x):
# Initialize length of smallest
# subarray as n+1
min_len = n + 1
# Pick every element as starting point
for start in range(0,n):
# Initialize sum starting
# with current start
curr_sum = arr[start]
# If first element itself is greater
if (curr_sum > x):
return 1
# Try different ending points
# for curremt start
for end in range(start+1,n):
# add last element to current sum
curr_sum += arr[end]
# If sum becomes more than x
# and length of this subarray
# is smaller than current smallest
# length, update the smallest
# length (or result)
if curr_sum > x and (end - start + 1) < min_len:
min_len = (end - start + 1)
return min_len;
# Driver program to test above function */
arr1 = [1, 4, 45, 6, 10, 19]
x = 51
n1 = len(arr1)
res1 = smallestSubWithSum(arr1, n1, x);
if res1 == n1+1:
print("Not possible")
else:
print(res1)
arr2 = [1, 10, 5, 2, 7]
n2 = len(arr2)
x = 9
res2 = smallestSubWithSum(arr2, n2, x);
if res2 == n2+1:
print("Not possible")
else:
print(res2)
arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
n3 = len(arr3)
x = 280
res3 = smallestSubWithSum(arr3, n3, x)
if res3 == n3+1:
print("Not possible")
else:
print(res3)
# This code is contributed by Smitha Dinesh Semwal
|
constant
|
quadratic
|
# O(n) solution for finding smallest
# subarray with sum greater than x
# Returns length of smallest subarray
# with sum greater than x. If there
# is no subarray with given sum, then
# returns n + 1
def smallestSubWithSum(arr, n, x):
# Initialize current sum and minimum length
curr_sum = 0
min_len = n + 1
# Initialize starting and ending indexes
start = 0
end = 0
while (end < n):
# Keep adding array elements while current
# sum is smaller than or equal to x
while (curr_sum <= x and end < n):
curr_sum += arr[end]
end += 1
# If current sum becomes greater than x.
while (curr_sum > x and start < n):
# Update minimum length if needed
if (end - start < min_len):
min_len = end - start
# remove starting elements
curr_sum -= arr[start]
start += 1
return min_len
# Driver program
arr1 = [1, 4, 45, 6, 10, 19]
x = 51
n1 = len(arr1)
res1 = smallestSubWithSum(arr1, n1, x)
print("Not possible") if (res1 == n1 + 1) else print(res1)
arr2 = [1, 10, 5, 2, 7]
n2 = len(arr2)
x = 9
res2 = smallestSubWithSum(arr2, n2, x)
print("Not possible") if (res2 == n2 + 1) else print(res2)
arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]
n3 = len(arr3)
x = 280
res3 = smallestSubWithSum(arr3, n3, x)
print("Not possible") if (res3 == n3 + 1) else print(res3)
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
linear
|
# Python program to find maximum average subarray
# of given length.
# Returns beginning index of maximum average
# subarray of length 'k'
def findMaxAverage(arr, n, k):
# Check if 'k' is valid
if k > n:
return -1
# Create and fill array to store cumulative
# sum. csum[i] stores sum of arr[0] to arr[i]
csum = [0]*n
csum[0] = arr[0]
for i in range(1, n):
csum[i] = csum[i-1] + arr[i];
# Initialize max_sm as sum of first subarray
max_sum = csum[k-1]
max_end = k-1
# Find sum of other subarrays and update
# max_sum if required.
for i in range(k, n):
curr_sum = csum[i] - csum[i-k]
if curr_sum > max_sum:
max_sum = curr_sum
max_end = i
# Return starting index
return max_end - k + 1
# Driver program
arr = [1, 12, -5, -6, 50, 3]
k = 4
n = len(arr)
print("The maximum average subarray of length",k,
"begins at index",findMaxAverage(arr, n, k))
#This code is contributed by
#Smitha Dinesh Semwal
|
linear
|
linear
|
# Python 3 program to find maximum
# average subarray of given length.
# Returns beginning index of maximum
# average subarray of length 'k'
def findMaxAverage(arr, n, k):
# Check if 'k' is valid
if (k > n):
return -1
# Compute sum of first 'k' elements
sum = arr[0]
for i in range(1, k):
sum += arr[i]
max_sum = sum
max_end = k - 1
# Compute sum of remaining subarrays
for i in range(k, n):
sum = sum + arr[i] - arr[i - k]
if (sum > max_sum):
max_sum = sum
max_end = i
# Return starting index
return max_end - k + 1
# Driver program
arr = [1, 12, -5, -6, 50, 3]
k = 4
n = len(arr)
print("The maximum average subarray of length", k,
"begins at index",
findMaxAverage(arr, n, k))
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
linear
|
# Python3 program to count minimum number of
# operations to get the given target array
# Returns count of minimum operations to
# convert a zero array to target array
# with increment and doubling operations.
# This function computes count by doing reverse
# steps, i.e., convert target to zero array.
def countMinOperations(target, n):
# Initialize result (Count of minimum moves)
result = 0;
# Keep looping while all elements of
# target don't become 0.
while (True):
# To store count of zeroes in
# current target array
zero_count = 0;
# To find first odd element
i = 0;
while (i < n):
# If odd number found
if ((target[i] & 1) > 0):
break;
# If 0, then increment
# zero_count
elif (target[i] == 0):
zero_count += 1;
i += 1;
# All numbers are 0
if (zero_count == n):
return result;
# All numbers are even
if (i == n):
# Divide the whole array by 2
# and increment result
for j in range(n):
target[j] = target[j] // 2;
result += 1;
# Make all odd numbers even by
# subtracting one and increment result.
for j in range(i, n):
if (target[j] & 1):
target[j] -= 1;
result += 1;
# Driver Code
arr = [16, 16, 16];
n = len(arr);
print("Minimum number of steps required to",
"\nget the given target array is",
countMinOperations(arr, n));
# This code is contributed by mits
|
constant
|
linear
|
# Python program to find number of operations
# to make an array palindrome
# Returns minimum number of count operations
# required to make arr[] palindrome
def findMinOps(arr, n):
ans = 0 # Initialize result
# Start from two corners
i,j = 0,n-1
while i<=j:
# If corner elements are same,
# problem reduces arr[i+1..j-1]
if arr[i] == arr[j]:
i += 1
j -= 1
# If left element is greater, then
# we merge right two elements
elif arr[i] > arr[j]:
# need to merge from tail.
j -= 1
arr[j] += arr[j+1]
ans += 1
# Else we merge left two elements
else:
i += 1
arr[i] += arr[i-1]
ans += 1
return ans
# Driver program to test above
arr = [1, 4, 5, 9, 1]
n = len(arr)
print("Count of minimum operations is " + str(findMinOps(arr, n)))
# This code is contributed by Pratik Chhajer
|
constant
|
linear
|
# Python3 program to find the smallest
# positive value that cannot be
# represented as sum of subsets
# of a given sorted array
# Returns the smallest number
# that cannot be represented as sum
# of subset of elements from set
# represented by sorted array arr[0..n-1]
def findSmallest(arr, n):
res = 1 #Initialize result
# Traverse the array and increment
# 'res' if arr[i] is smaller than
# or equal to 'res'.
for i in range (0, n ):
if arr[i] <= res:
res = res + arr[i]
else:
break
return res
# Driver program to test above function
arr1 = [1, 3, 4, 5]
n1 = len(arr1)
print(findSmallest(arr1, n1))
arr2= [1, 2, 6, 10, 11, 15]
n2 = len(arr2)
print(findSmallest(arr2, n2))
arr3= [1, 1, 1, 1]
n3 = len(arr3)
print(findSmallest(arr3, n3))
arr4 = [1, 1, 3, 4]
n4 = len(arr4)
print(findSmallest(arr4, n4))
# This code is.contributed by Smitha Dinesh Semwal
|
constant
|
nlogn
|
# Python3 program to print largest contiguous array sum
from sys import maxsize
# Function to find the maximum contiguous subarray
# and print its starting and end index
def maxSubArraySum(a,size):
max_so_far = -maxsize - 1
max_ending_here = 0
start = 0
end = 0
s = 0
for i in range(0,size):
max_ending_here += a[i]
if max_so_far < max_ending_here:
max_so_far = max_ending_here
start = s
end = i
if max_ending_here < 0:
max_ending_here = 0
s = i+1
return (end - start + 1)
# Driver program to test maxSubArraySum
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print(maxSubArraySum(a,len(a)))
|
constant
|
linear
|
# Python implementation of simple method to find
# minimum difference between any pair
# Returns minimum difference between any pair
def findMinDiff(arr, n):
# Initialize difference as infinite
diff = 10**20
# Find the min diff by comparing difference
# of all possible pairs in given array
for i in range(n-1):
for j in range(i+1, n):
if abs(arr[i]-arr[j]) < diff:
diff = abs(arr[i] - arr[j])
# Return min diff
return diff
# Driver code
if __name__ == "__main__":
arr = [1, 5, 3, 19, 18, 25]
n = len(arr)
# Function call
print("Minimum difference is " + str(findMinDiff(arr, n)))
# This code is contributed by Pratik Chhajer
|
constant
|
quadratic
|
# Python3 program to find minimum difference between
# any pair in an unsorted array
# Returns minimum difference between any pair
def findMinDiff(arr, n):
# Sort array in non-decreasing order
arr = sorted(arr)
# Initialize difference as infinite
diff = 10**20
# Find the min diff by comparing adjacent
# pairs in sorted array
for i in range(n-1):
if arr[i+1] - arr[i] < diff:
diff = arr[i+1] - arr[i]
# Return min diff
return diff
# Driver code
if __name__ == "__main__":
arr = [1, 5, 3, 19, 18, 25]
n = len(arr)
# Function call
print("Minimum difference is " + str(findMinDiff(arr, n)))
# This code is contributed by Pratik Chhajer
|
constant
|
nlogn
|
# A Simple python program to find longest common
# subarray of two binary arrays with same sum
# Returns length of the longest common subarray
# with same sum
def longestCommonSum(arr1, arr2, n):
# Initialize result
maxLen = 0
# One by one pick all possible starting points
# of subarrays
for i in range(0,n):
# Initialize sums of current subarrays
sum1 = 0
sum2 = 0
# Consider all points for starting with arr[i]
for j in range(i,n):
# Update sums
sum1 += arr1[j]
sum2 += arr2[j]
# If sums are same and current length is
# more than maxLen, update maxLen
if (sum1 == sum2):
len = j-i+1
if (len > maxLen):
maxLen = len
return maxLen
# Driver program to test above function
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print("Length of the longest common span with same "
"sum is",longestCommonSum(arr1, arr2, n))
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
quadratic
|
# Python program to find longest common
# subarray of two binary arrays with
# same sum
def longestCommonSum(arr1, arr2, n):
# Initialize result
maxLen = 0
# Initialize prefix sums of two arrays
presum1 = presum2 = 0
# Create a dictionary to store indices
# of all possible sums
diff = {}
# Traverse both arrays
for i in range(n):
# Update prefix sums
presum1 += arr1[i]
presum2 += arr2[i]
# Compute current diff which will be
# used as index in diff dictionary
curr_diff = presum1 - presum2
# If current diff is 0, then there
# are same number of 1's so far in
# both arrays, i.e., (i+1) is
# maximum length.
if curr_diff == 0:
maxLen = i+1
elif curr_diff not in diff:
# save the index for this diff
diff[curr_diff] = i
else:
# calculate the span length
length = i - diff[curr_diff]
maxLen = max(maxLen, length)
return maxLen
# Driver program
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
print("Length of the longest common",
" span with same", end = " ")
print("sum is",longestCommonSum(arr1,
arr2, len(arr1)))
# This code is contributed by Abhijeet Nautiyal
|
linear
|
linear
|
# Python program to find largest subarray
# with equal number of 0's and 1's.
# Returns largest common subarray with equal
# number of 0s and 1s
def longestCommonSum(arr1, arr2, n):
# Find difference between the two
arr = [0 for i in range(n)]
for i in range(n):
arr[i] = arr1[i] - arr2[i];
# Creates an empty hashMap hM
hm = {}
sum = 0 # Initialize sum of elements
max_len = 0 #Initialize result
# Traverse through the given array
for i in range(n):
# Add current element to sum
sum += arr[i]
# To handle sum=0 at last index
if (sum == 0):
max_len = i + 1
# If this sum is seen before,
# then update max_len if required
if sum in hm:
max_len = max(max_len, i - hm[sum])
else: # Else put this sum in hash table
hm[sum] = i
return max_len
# Driver code
arr1 = [0, 1, 0, 1, 1, 1, 1]
arr2 = [1, 1, 1, 1, 1, 0, 1]
n = len(arr1)
print(longestCommonSum(arr1, arr2, n))
# This code is contributed by rag2127
|
linear
|
linear
|
# Python 3 program to print an array
# in alternate sorted manner.
# Function to print alternate sorted
# values
def alternateSort(arr, n):
# Sorting the array
arr.sort()
# Printing the last element of array
# first and then first element and then
# second last element and then second
# element and so on.
i = 0
j = n-1
while (i < j):
print(arr[j], end =" ")
j-= 1
print(arr[i], end =" ")
i+= 1
# If the total element in array is odd
# then print the last middle element.
if (n % 2 != 0):
print(arr[i])
# Driver code
arr = [1, 12, 4, 6, 7, 10]
n = len(arr)
alternateSort(arr, n)
# This code is contributed by
# Smitha Dinesh Semwal
|
constant
|
nlogn
|
# Function to sort an array using
# insertion sort
def insertionSort(A, size):
i, key, j = 0, 0, 0
for i in range(size):
key = A[i]
j = i-1
# Move elements of A[0..i-1], that are
# greater than key, to one position
# ahead of their current position.
# This loop will run at most k times
while j >= 0 and A[j] > key:
A[j + 1] = A[j]
j = j - 1
A[j + 1] = key
|
constant
|
constant
|
# A Python3 program to sort a
# nearly sorted array.
from heapq import heappop, heappush, heapify
# A utility function to print
# array elements
def print_array(arr: list):
for elem in arr:
print(elem, end=' ')
# Given an array of size n, where every
# element is k away from its target
# position, sorts the array in O(nLogk) time.
def sort_k(arr: list, n: int, k: int):
"""
:param arr: input array
:param n: length of the array
:param k: max distance, which every
element is away from its target position.
:return: None
"""
# List of first k+1 items
heap = arr[:k + 1]
# using heapify to convert list
# into heap(or min heap)
heapify(heap)
# "rem_elmnts_index" is index for remaining
# elements in arr and "target_index" is
# target index of for current minimum element
# in Min Heap "heap".
target_index = 0
for rem_elmnts_index in range(k + 1, n):
arr[target_index] = heappop(heap)
heappush(heap, arr[rem_elmnts_index])
target_index += 1
while heap:
arr[target_index] = heappop(heap)
target_index += 1
# Driver Code
k = 3
arr = [2, 6, 3, 12, 56, 8]
n = len(arr)
sort_k(arr, n, k)
print('Following is sorted array')
print_array(arr)
# This code is contributed by
# Veerat Beri(viratberi)
|
logn
|
nlogn
|
# Python function to sort the array arr[0..n-1] in wave form,
# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]
def sortInWave(arr, n):
#sort the array
arr.sort()
# Swap adjacent elements
for i in range(0,n-1,2):
arr[i], arr[i+1] = arr[i+1], arr[i]
# Driver program
arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0,len(arr)):
print (arr[i],end=" ")
# This code is contributed by __Devesh Agrawal__
|
constant
|
nlogn
|
# Python function to sort the array arr[0..n-1] in wave form,
# i.e., arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= arr[5]
def sortInWave(arr, n):
# Traverse all even elements
for i in range(0, n - 1, 2):
# If current even element is smaller than previous
if (i > 0 and arr[i] < arr[i-1]):
arr[i], arr[i-1] = arr[i-1], arr[i]
# If current even element is smaller than next
if (i < n-1 and arr[i] < arr[i+1]):
arr[i], arr[i+1] = arr[i+1], arr[i]
# Driver program
arr = [10, 90, 49, 2, 1, 5, 23]
sortInWave(arr, len(arr))
for i in range(0, len(arr)):
print(arr[i], end=" ")
# This code is contributed by __Devesh Agrawal__
|
constant
|
linear
|
# Python program to Merge an array of
# size n into another array of size m + n
NA = -1
# Function to move m elements
# at the end of array mPlusN[]
def moveToEnd(mPlusN, size):
i = 0
j = size - 1
for i in range(size-1, -1, -1):
if (mPlusN[i] != NA):
mPlusN[j] = mPlusN[i]
j -= 1
# Merges array N[]
# of size n into array mPlusN[]
# of size m+n
def merge(mPlusN, N, m, n):
i = n # Current index of i/p part of mPlusN[]
j = 0 # Current index of N[]
k = 0 # Current index of output mPlusN[]
while (k < (m+n)):
# Take an element from mPlusN[] if
# a) value of the picked
# element is smaller and we have
# not reached end of it
# b) We have reached end of N[] */
if ((j == n) or (i < (m+n) and mPlusN[i] <= N[j])):
mPlusN[k] = mPlusN[i]
k += 1
i += 1
else: # Otherwise take element from N[]
mPlusN[k] = N[j]
k += 1
j += 1
# Utility that prints
# out an array on a line
def printArray(arr, size):
for i in range(size):
print(arr[i], " ", end="")
print()
# Driver function to
# test above functions
# Initialize arrays
mPlusN = [2, 8, NA, NA, NA, 13, NA, 15, 20]
N = [5, 7, 9, 25]
n = len(N)
m = len(mPlusN) - n
# Move the m elements
# at the end of mPlusN
moveToEnd(mPlusN, m+n)
# Merge N[] into mPlusN[]
merge(mPlusN, N, m, n)
# Print the resultant mPlusN
printArray(mPlusN, m+n)
# This code is contributed
# by Anant Agarwal.
|
constant
|
linear
|
# Python 3 program to test whether an array
# can be sorted by swapping adjacent
# elements using a boolean array
# Return true if array can be
# sorted otherwise false
def sortedAfterSwap(A, B, n) :
# Check bool array B and sorts
# elements for continuous sequence of 1
for i in range(0, n - 1) :
if (B[i]== 1) :
j = i
while (B[j]== 1) :
j = j + 1
# Sort array A from i to j
A = A[0:i] + sorted(A[i:j + 1]) + A[j + 1:]
i = j
# Check if array is sorted or not
for i in range(0, n) :
if (A[i] != i + 1) :
return False
return True
# Driver program to test sortedAfterSwap()
A = [ 1, 2, 5, 3, 4, 6 ]
B = [ 0, 1, 1, 1, 0 ]
n = len(A)
if (sortedAfterSwap(A, B, n)) :
print("A can be sorted")
else :
print("A can not be sorted")
# This code is contributed
# by Nikita Tiwari.
|
constant
|
quadratic
|
# Python3 program to test whether array
# can be sorted by swapping adjacent
# elements using boolean array
# Return true if array can be
# sorted otherwise false
def sortedAfterSwap(A,B,n):
for i in range(0,n-1):
if B[i]:
if A[i]!=i+1:
A[i], A[i+1] = A[i+1], A[i]
# Check if array is sorted or not
for i in range(n):
if A[i]!=i+1:
return False
return True
# Driver program
if __name__=='__main__':
A = [1, 2, 5, 3, 4, 6]
B = [0, 1, 1, 1, 0]
n =len(A)
if (sortedAfterSwap(A, B, n)) :
print("A can be sorted")
else :
print("A can not be sorted")
# This code is contributed by
# Shrikant13
|
constant
|
linear
|
# Python3 program to sort an array with
# two types of values in one traversal.
# Method for segregation 0 and
# 1 given input array
def segregate0and1(arr, n):
type0 = 0; type1 = n - 1
while (type0 < type1):
if (arr[type0] == 1):
arr[type0], arr[type1] = arr[type1], arr[type0]
type1 -= 1
else:
type0 += 1
# Driver Code
arr = [1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1]
n = len(arr)
segregate0and1(arr, n)
for i in range(0, n):
print(arr[i], end = " ")
# This code is contributed by Smitha Dinesh Semwal
|
constant
|
linear
|
# Python3 program that performs the following
# operations: Sort elements by frequency. If two elements
# have same count, then put the elements that appears first
# Used for sorting
class ele:
def __init__(self):
self.count = 0
self.index = 0
self.val = 0
def mycomp(a):
return a.val
# Used for sorting by frequency. And if frequency is same,
# then by appearance
def mycomp2(a):
# using negative value for a.index
# since the sorting should be in
# descending order
return (a.count, -a.index)
def sortByFrequency(arr, n):
element = [None for _ in range(n)]
for i in range(n):
element[i] = ele()
# Fill Indexes
element[i].index = i
# Initialize counts as 0
element[i].count = 0
# Fill values in structure
# elements
element[i].val = arr[i]
# Sort the structure elements according to value,
# we used stable sort so relative order is maintained.
#
element.sort(key=mycomp)
# initialize count of first element as 1
element[0].count = 1
# Count occurrences of remaining elements
for i in range(1, n):
if (element[i].val == element[i - 1].val):
element[i].count += element[i - 1].count + 1
# Set count of previous element as -1, we are
# doing this because we'll again sort on the
# basis of counts (if counts are equal than on
# the basis of index)*/
element[i - 1].count = -1
# Retain the first index (Remember first index
# is always present in the first duplicate we
# used stable sort. */
element[i].index = element[i - 1].index
# Else If previous element is not equal to current
# so set the count to 1
else:
element[i].count = 1
# Now we have counts and first index for each element
# so now sort on the basis of count and in case of tie
# use index to sort.*/
element.sort(key=mycomp2)
index = 0
for i in range(n - 1, -1, -1):
if (element[i].count != -1):
for j in range(element[i].count):
arr[index] = element[i].val
index += 1
# Driver code
arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
n = len(arr)
# Function call
sortByFrequency(arr, n)
print(*arr)
# This code is contributed by phasing17
|
linear
|
nlogn
|
# Python3 program for above approach
from collections import defaultdict
# Sort by Frequency
def sortByFreq(arr, n):
# arr -> Array to be sorted
# n -> Length of Array
# d is a hashmap(referred as dictionary in python)
d = defaultdict(lambda: 0)
for i in range(n):
d[arr[i]] += 1
# Sorting the array 'arr' where key
# is the function based on which
# the array is sorted
# While sorting we want to give
# first priority to Frequency
# Then to value of item
arr.sort(key=lambda x: (-d[x], x))
return (arr)
# Driver code
if __name__ == "__main__":
arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
n = len(arr)
# Function call
solution = sortByFreq(arr, n)
print(*solution)
|
linear
|
nlogn
|
# Python3 program to count
# inversions in an array
def getInvCount(arr, n):
inv_count = 0
for i in range(n):
for j in range(i + 1, n):
if (arr[i] > arr[j]):
inv_count += 1
return inv_count
# Driver Code
arr = [1, 20, 6, 4, 5]
n = len(arr)
print("Number of inversions are",
getInvCount(arr, n))
# This code is contributed by Smitha Dinesh Semwal
|
constant
|
quadratic
|
# Python 3 program to count inversions in an array
# Function to Use Inversion Count
def mergeSort(arr, n):
# A temp_arr is created to store
# sorted array in merge function
temp_arr = [0]*n
return _mergeSort(arr, temp_arr, 0, n-1)
# This Function will use MergeSort to count inversions
def _mergeSort(arr, temp_arr, left, right):
# A variable inv_count is used to store
# inversion counts in each recursive call
inv_count = 0
# We will make a recursive call if and only if
# we have more than one elements
if left < right:
# mid is calculated to divide the array into two subarrays
# Floor division is must in case of python
mid = (left + right)//2
# It will calculate inversion
# counts in the left subarray
inv_count += _mergeSort(arr, temp_arr,
left, mid)
# It will calculate inversion
# counts in right subarray
inv_count += _mergeSort(arr, temp_arr,
mid + 1, right)
# It will merge two subarrays in
# a sorted subarray
inv_count += merge(arr, temp_arr, left, mid, right)
return inv_count
# This function will merge two subarrays
# in a single sorted subarray
def merge(arr, temp_arr, left, mid, right):
i = left # Starting index of left subarray
j = mid + 1 # Starting index of right subarray
k = left # Starting index of to be sorted subarray
inv_count = 0
# Conditions are checked to make sure that
# i and j don't exceed their
# subarray limits.
while i <= mid and j <= right:
# There will be no inversion if arr[i] <= arr[j]
if arr[i] <= arr[j]:
temp_arr[k] = arr[i]
k += 1
i += 1
else:
# Inversion will occur.
temp_arr[k] = arr[j]
inv_count += (mid-i + 1)
k += 1
j += 1
# Copy the remaining elements of left
# subarray into temporary array
while i <= mid:
temp_arr[k] = arr[i]
k += 1
i += 1
# Copy the remaining elements of right
# subarray into temporary array
while j <= right:
temp_arr[k] = arr[j]
k += 1
j += 1
# Copy the sorted subarray into Original array
for loop_var in range(left, right + 1):
arr[loop_var] = temp_arr[loop_var]
return inv_count
# Driver Code
# Given array is
arr = [1, 20, 6, 4, 5]
n = len(arr)
result = mergeSort(arr, n)
print("Number of inversions are", result)
# This code is contributed by ankush_953
|
linear
|
nlogn
|
from heapq import heappush, heappop
from bisect import bisect, insort
def getNumOfInversions(A):
N = len(A)
if N <= 1:
return 0
sortList = []
result = 0
# Heapsort, O(N*log(N))
for i, v in enumerate(A):
heappush(sortList, (v, i))
# Create a sorted list of indexes
x = []
while sortList:
# O(log(N))
v, i = heappop(sortList)
# Find the current minimum's index
# the index y can represent how many minimums on the left
y = bisect(x, i)
# i can represent how many elements on the left
# i - y can find how many bigger nums on the left
result += i - y
insort(x, i)
return result
# Driver Code
if __name__ == '__main__':
A = [1, 20, 6, 4, 5]
result = getNumOfInversions(A)
print(f'Number of inversions are {result}')
|
linear
|
nlogn
|
# Python3 program to find shortest
# subarray which is unsorted
# Bool function for checking an array
# elements are in increasing
def increasing(a, n):
for i in range(0, n - 1):
if (a[i] >= a[i + 1]):
return False
return True
# Bool function for checking an array
# elements are in decreasing
def decreasing(a, n):
for i in range(0, n - 1):
if (a[i] < a[i + 1]):
return False
return True
def shortestUnsorted(a, n):
# increasing and decreasing are two functions.
# if function return True value then print
# 0 otherwise 3.
if (increasing(a, n) == True or
decreasing(a, n) == True):
return 0
else:
return 3
# Driver code
ar = [7, 9, 10, 8, 11]
n = len(ar)
print(shortestUnsorted(ar, n))
# This code is contributed by Smitha Dinesh Semwal.
|
constant
|
linear
|
# Python3 program to find
# minimum number of swaps
# required to sort an array
# Function returns the minimum
# number of swaps required to
# sort the array
def minSwaps(arr):
n = len(arr)
# Create two arrays and use
# as pairs where first array
# is element and second array
# is position of first element
arrpos = [*enumerate(arr)]
# Sort the array by array element
# values to get right position of
# every element as the elements
# of second array.
arrpos.sort(key = lambda it : it[1])
# To keep track of visited elements.
# Initialize all elements as not
# visited or false.
vis = {k : False for k in range(n)}
# Initialize result
ans = 0
for i in range(n):
# already swapped or
# already present at
# correct position
if vis[i] or arrpos[i][0] == i:
continue
# find number of nodes
# in this cycle and
# add it to ans
cycle_size = 0
j = i
while not vis[j]:
# mark node as visited
vis[j] = True
# move to next node
j = arrpos[j][0]
cycle_size += 1
# update answer by adding
# current cycle
if cycle_size > 0:
ans += (cycle_size - 1)
# return answer
return ans
# Driver Code
arr = [1, 5, 4, 3, 2]
print(minSwaps(arr))
# This code is contributed
# by Dharan Aditya
|
linear
|
nlogn
|
# Function returns the
# minimum number of swaps
# required to sort the array
from functools import cmp_to_key
def cmp(a, b):
return a - b
def minSwaps(nums):
Len = len(nums)
map = {}
for i in range(Len):
map[nums[i]] = i
nums = sorted(nums, key = cmp_to_key(cmp))
# To keep track of visited elements. Initialize
# all elements as not visited or false.
visited = [False for col in range(Len)]
# Initialize result
ans = 0
for i in range(Len):
# already swapped and corrected or
# already present at correct pos
if (visited[i] or map[nums[i]] == i):
continue
j,cycle_size = i, 0
while (visited[j] == False):
visited[j] = True
# move to next node
j = map[nums[j]]
cycle_size += 1
# Update answer by adding current cycle.
if (cycle_size > 0):
ans += (cycle_size - 1)
return ans
# Driver program to test the above function
a = [ 1, 5, 4, 3, 2 ]
print(minSwaps(a))
# This code is contributed by shinjanpatra
|
linear
|
nlogn
|
# Python3 program to find
#minimum number of swaps
# required to sort an array
# Return the minimum number
# of swaps required to sort
# the array
def minSwaps(arr, N):
ans = 0
temp = arr.copy()
temp.sort()
for i in range(N):
# This is checking whether
# the current element is
# at the right place or not
if (arr[i] != temp[i]):
ans += 1
# Swap the current element
# with the right index
# so that arr[0] to arr[i]
# is sorted
swap(arr, i,
indexOf(arr, temp[i]))
return ans
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def indexOf(arr, ele):
for i in range(len(arr)):
if (arr[i] == ele):
return i
return -1
# Driver code
if __name__ == "__main__":
a = [101, 758, 315, 730,
472, 619, 460, 479]
n = len(a)
# Output will be 5
print(minSwaps(a, n))
# This code is contributed by Chitranayal
|
linear
|
quadratic
|
# Python3 program to find
# minimum number of swaps
# required to sort an array
# Return the minimum number
# of swaps required to sort
# the array
def minSwap(arr, n):
ans = 0
temp = arr.copy()
# Dictionary which stores the
# indexes of the input array
h = {}
temp.sort()
for i in range(n):
#h.[arr[i]
h[arr[i]] = i
init = 0
for i in range(n):
# This is checking whether
# the current element is
# at the right place or not
if (arr[i] != temp[i]):
ans += 1
init = arr[i]
# If not, swap this element
# with the index of the
# element which should come here
arr[i], arr[h[temp[i]]] = arr[h[temp[i]]], arr[i]
# Update the indexes in
# the hashmap accordingly
h[init] = h[temp[i]]
h[temp[i]] = i
return ans
# Driver code
a = [ 101, 758, 315, 730,
472, 619, 460, 479 ]
n = len(a)
# Output will be 5
print(minSwap(a, n))
# This code is contributed by avanitrachhadiya2155
|
linear
|
nlogn
|
# Python program to sort an array with
# 0, 1 and 2 in a single pass
# Function to sort array
def sort012(a, arr_size):
lo = 0
hi = arr_size - 1
mid = 0
# Iterate till all the elements
# are sorted
while mid <= hi:
# If the element is 0
if a[mid] == 0:
a[lo], a[mid] = a[mid], a[lo]
lo = lo + 1
mid = mid + 1
# If the element is 1
elif a[mid] == 1:
mid = mid + 1
# If the element is 2
else:
a[mid], a[hi] = a[hi], a[mid]
hi = hi - 1
return a
# Function to print array
def printArray(a):
for k in a:
print(k, end=' ')
# Driver Program
arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
arr_size = len(arr)
arr = sort012(arr, arr_size)
printArray(arr)
# Contributed by Harshit Agrawal
|
constant
|
linear
|
# Python implementation of the approach
# Utility function to print contents of an array
def printArr(arr, n):
for i in range(n):
print(arr[i], end=" ")
# Function to sort the array of 0s, 1s and 2s
def sortArr(arr, n):
cnt0 = 0
cnt1 = 0
cnt2 = 0
# Count the number of 0s, 1s and 2s in the array
for i in range(n):
if arr[i] == 0:
cnt0 += 1
elif arr[i] == 1:
cnt1 += 1
elif arr[i] == 2:
cnt2 += 1
# Update the array
i = 0
# Store all the 0s in the beginning
while (cnt0 > 0):
arr[i] = 0
i += 1
cnt0 -= 1
# Then all the 1s
while (cnt1 > 0):
arr[i] = 1
i += 1
cnt1 -= 1
# Finally all the 2s
while (cnt2 > 0):
arr[i] = 2
i += 1
cnt2 -= 1
# Print the sorted array
printArr(arr, n)
# Driver code
arr = [0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1]
n = len(arr)
sortArr(arr, n)
# This code is contributed by shubhamsingh10
|
constant
|
linear
|
# Function to find position to insert current element of
# stream using binary search
def binarySearch(arr, item, low, high):
if (low >= high):
return (low + 1) if (item > arr[low]) else low
mid = (low + high) // 2
if (item == arr[mid]):
return mid + 1
if (item > arr[mid]):
return binarySearch(arr, item, mid + 1, high)
return binarySearch(arr, item, low, mid - 1)
# Function to print median of stream of integers
def printMedian(arr, n):
i, j, pos, num = 0, 0, 0, 0
count = 1
print(f"Median after reading 1 element is {arr[0]}")
for i in range(1, n):
median = 0
j = i - 1
num = arr[i]
# find position to insert current element in sorted
# part of array
pos = binarySearch(arr, num, 0, j)
# move elements to right to create space to insert
# the current element
while (j >= pos):
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = num
# increment count of sorted elements in array
count += 1
# if odd number of integers are read from stream
# then middle element in sorted order is median
# else average of middle elements is median
if (count % 2 != 0):
median = arr[count // 2]
else:
median = (arr[(count // 2) - 1] + arr[count // 2]) // 2
print(f"Median after reading {i + 1} elements is {median} ")
# Driver Code
if __name__ == "__main__":
arr = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4]
n = len(arr)
printMedian(arr, n)
# This code is contributed by rakeshsahni
|
constant
|
quadratic
|
# Python code to implement the approach
from heapq import heappush, heappop, heapify
import math
# Function to find the median of stream of data
def streamMed(arr, N):
# Declaring two min heap
g = []
s = []
for i in range(len(arr)):
# Negation for treating it as max heap
heappush(s, -arr[i])
heappush(g, -heappop(s))
if len(g) > len(s):
heappush(s, -heappop(g))
if len(g) != len(s):
print(-s[0])
else:
print((g[0] - s[0])/2)
# Driver code
if __name__ == '__main__':
A = [5, 15, 1, 3, 2, 8, 7, 9, 10, 6, 11, 4]
N = len(A)
# Function call
streamMed(A, N)
|
linear
|
nlogn
|
# Python3 code to count the number of
# possible triangles using brute
# force approach
# Function to count all possible
# triangles with arr[] elements
def findNumberOfTriangles(arr, n):
# Count of triangles
count = 0
# The three loops select three
# different values from array
for i in range(n):
for j in range(i + 1, n):
# The innermost loop checks for
# the triangle property
for k in range(j + 1, n):
# Sum of two sides is greater
# than the third
if (arr[i] + arr[j] > arr[k] and
arr[i] + arr[k] > arr[j] and
arr[k] + arr[j] > arr[i]):
count += 1
return count
# Driver code
if __name__ == "__main__":
arr = [10, 21, 22, 100, 101, 200, 300]
size = len(arr)
# Function call
print("Total number of triangles possible is",
findNumberOfTriangles(arr, size))
# This code is contributed by shubhamsingh10
|
constant
|
cubic
|
# Python3 function to count all possible triangles with arr[]
# elements
def findnumberofTriangles(arr):
# Sort array and initialize count as 0
n = len(arr)
arr.sort()
count = 0
# Fix the first element. We need to run till n-3 as
# the other two elements are selected from arr[i + 1...n-1]
for i in range(0, n-2):
# Initialize index of the rightmost third element
k = i + 2
# Fix the second element
for j in range(i + 1, n):
# Find the rightmost element which is smaller
# than the sum of two fixed elements
# The important thing to note here is, we use
# the previous value of k. If value of arr[i] +
# arr[j-1] was greater than arr[k], then arr[i] +
# arr[j] must be greater than k, because the array
# is sorted.
while (k < n and arr[i] + arr[j] > arr[k]):
k += 1
# Total number of possible triangles that can be
# formed with the two fixed elements is k - j - 1.
# The two fixed elements are arr[i] and arr[j]. All
# elements between arr[j + 1] to arr[k-1] can form a
# triangle with arr[i] and arr[j]. One is subtracted
# from k because k is incremented one extra in above
# while loop. k will always be greater than j. If j
# becomes equal to k, then above loop will increment k,
# because arr[k] + arr[i] is always greater than arr[k]
if(k > j):
count += k - j - 1
return count
# Driver code
if __name__ == "__main__":
arr = [10, 21, 22, 100, 101, 200, 300]
# Function call
print("Total number of Triangles:", findnumberofTriangles(arr))
# This code is contributed by Devesh Agrawal
|
constant
|
quadratic
|
# Python implementation of the above approach
def CountTriangles(A):
n = len(A)
A.sort()
count = 0
for i in range(n - 1, 0, -1):
l = 0
r = i - 1
while(l < r):
if(A[l] + A[r] > A[i]):
# If it is possible with a[l], a[r]
# and a[i] then it is also possible
# with a[l + 1]..a[r-1], a[r] and a[i]
count += r - l
# checking for more possible solutions
r -= 1
else:
# if not possible check for
# higher values of arr[l]
l += 1
print("No of possible solutions: ", count)
# Driver Code
if __name__ == '__main__':
A = [10, 21, 22, 100, 101, 200, 300]
# Function call
CountTriangles(A)
# This code is contributed by PrinciRaj1992
|
constant
|
quadratic
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.