diff --git a/Arrays/Find_Missing_Element.py b/Arrays/Find_Missing_Element.py index 42d5ef4..be1be3d 100644 --- a/Arrays/Find_Missing_Element.py +++ b/Arrays/Find_Missing_Element.py @@ -1,43 +1,43 @@ -""" -Problem Statement: -Missing number in array -Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. - -Input: -The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements. - -Output: -Print the missing number in array. - -Constraints: -1 ≤ T ≤ 200 -1 ≤ N ≤ 107 -1 ≤ C[i] ≤ 107 - -Example: -Input: -2 -5 -1 2 3 5 -10 -1 2 3 4 5 6 7 8 10 - -Output: -4 -9 - -Explanation: -Testcase 1: Given array : 1 2 3 5. Missing element is 4. -""" - -if __name__=='__main__': - test_cases=int(input()) # number of test cases - for i in range(test_cases): - number_of_elements = int(input()) # number of array elements to add - elements = list(map(int, input().split())) - predicted_elements = set() - for j in range(1, number_of_elements+1, 1): - predicted_elements.add(j) - diff_set = predicted_elements - set(elements) # find the missing element by subtracting - for missing_element in diff_set: - print(missing_element) +""" +Problem Statement: +Missing number in array +Given an array C of size N-1 and given that there are numbers from 1 to N with one element missing, the missing number is to be found. + +Input: +The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N(size of array). The subsequent line contains N-1 array elements. + +Output: +Print the missing number in array. + +Constraints: +1 ≤ T ≤ 200 +1 ≤ N ≤ 107 +1 ≤ C[i] ≤ 107 + +Example: +Input: +2 +5 +1 2 3 5 +10 +1 2 3 4 5 6 7 8 10 + +Output: +4 +9 + +Explanation: +Testcase 1: Given array : 1 2 3 5. Missing element is 4. +""" + +if __name__=='__main__': + test_cases=int(input()) # number of test cases + for i in range(test_cases): + number_of_elements = int(input()) # number of array elements to add + elements = list(map(int, input().split())) + predicted_elements = set() + for j in range(1, number_of_elements+1, 1): + predicted_elements.add(j) + diff_set = predicted_elements - set(elements) # find the missing element by subtracting + for missing_element in diff_set: + print(missing_element) diff --git a/Arrays/Leaders_Of_Array.py b/Arrays/Leaders_Of_Array.py index 997ae48..ca76175 100644 --- a/Arrays/Leaders_Of_Array.py +++ b/Arrays/Leaders_Of_Array.py @@ -1,69 +1,69 @@ -""" -Leaders in an array -Given an array of positive integers. Your task is to find the leaders in the array. -Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the rightmost element is always a leader. - -Input: -The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. -The first line of each test case contains a single integer N denoting the size of array. -The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. - -Output: -Print all the leaders. - -Constraints: -1 <= T <= 100 -1 <= N <= 107 -0 <= Ai <= 107 - -Example: -Input: -3 -6 -16 17 4 3 5 2 -5 -1 2 3 4 0 -5 -7 4 5 7 3 -Output: -17 5 2 -4 0 -7 7 3 - -Explanation: -Testcase 3: All elements on the right of 7 (at index 0) are smaller than or equal to 7. Also, all the elements of right side of 7 (at index 3) are smaller than 7. And, the last element 3 is itself a leader since no elements are on its right. -""" - -""" -# this code has more time complexity that the following code (but it has a nice approach) -if __name__=='__main__': - test_cases=int(input()) - for i in range(test_cases): - n = int(input()) - elements = list(map(int,input().split())) - for pos, elem in enumerate(elements): - if pos + 1 < n: - if max(elements[pos+1:]) <= elem: - print(elem) - else: - print(elem) -""" -#code -def leader(a,n): - maxx=-1 - l=[] - for i in range(n-1,-1,-1): - if a[i]>=maxx: - maxx=a[i] - l.append(maxx) - length=len(l) - for i in range(length-1,-1,-1): - print(l[i],end=' ') - print() - -t=int(input()) # test cases - -for i in range(t): - n=int(input()) # number of elements - arr=[int(x) for x in input().split()] # elements separated by spaces +""" +Leaders in an array +Given an array of positive integers. Your task is to find the leaders in the array. +Note: An element of array is leader if it is greater than or equal to all the elements to its right side. Also, the rightmost element is always a leader. + +Input: +The first line of input contains an integer T denoting the number of test cases. The description of T test cases follows. +The first line of each test case contains a single integer N denoting the size of array. +The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array. + +Output: +Print all the leaders. + +Constraints: +1 <= T <= 100 +1 <= N <= 107 +0 <= Ai <= 107 + +Example: +Input: +3 +6 +16 17 4 3 5 2 +5 +1 2 3 4 0 +5 +7 4 5 7 3 +Output: +17 5 2 +4 0 +7 7 3 + +Explanation: +Testcase 3: All elements on the right of 7 (at index 0) are smaller than or equal to 7. Also, all the elements of right side of 7 (at index 3) are smaller than 7. And, the last element 3 is itself a leader since no elements are on its right. +""" + +""" +# this code has more time complexity that the following code (but it has a nice approach) +if __name__=='__main__': + test_cases=int(input()) + for i in range(test_cases): + n = int(input()) + elements = list(map(int,input().split())) + for pos, elem in enumerate(elements): + if pos + 1 < n: + if max(elements[pos+1:]) <= elem: + print(elem) + else: + print(elem) +""" +#code +def leader(a,n): + maxx=-1 + l=[] + for i in range(n-1,-1,-1): + if a[i]>=maxx: + maxx=a[i] + l.append(maxx) + length=len(l) + for i in range(length-1,-1,-1): + print(l[i],end=' ') + print() + +t=int(input()) # test cases + +for i in range(t): + n=int(input()) # number of elements + arr=[int(x) for x in input().split()] # elements separated by spaces leader(arr,n) # method to find all leaders \ No newline at end of file diff --git a/Arrays/MountainSubArray.py b/Arrays/MountainSubArray.py index a0e2794..b502da9 100644 --- a/Arrays/MountainSubArray.py +++ b/Arrays/MountainSubArray.py @@ -1,77 +1,77 @@ -""" -Mountain Subarray Problem -We are given an array of integers and a range, we need to find whether the subarray which falls in this range has values in the form of a mountain or not. All values of the subarray are said to be in the form of a mountain if either all values are increasing or decreasing or first increasing and then decreasing. More formally a subarray [a1, a2, a3 … aN] is said to be in form of a mountain if there exists an integer K, 1 <= K <= N such that, -a1 <= a2 <= a3 .. <= aK >= a(K+1) >= a(K+2) …. >= aN -You have to process Q queries. In each query you are given two integer L and R, denoting starting and last index of the subarrays respectively. - -Input: -The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array. The following line contains N space-separated integers forming the array. Next line contains an integer Q, denoting the number of queries. For each query, you are given two space-separated integers L and R in a new line. - -Output: -For each query, print "Yes" (without quotes) if the subarray is in mountain form, otherwise print "No" (without quotes) in a new line. - -Expected Time Complexity: O(N + Q). -Expected Auxiliary Space: O(N). - -Constraints: -1 <= T <= 100 -1 <= N, Q <= 105 -1 <= a[i] <= 106, for each valid i -0 <= L <= R <= N-1 - -Example: -Input: -1 -8 -2 3 2 4 4 6 3 2 -2 -0 2 -1 3 - -Output: -Yes -No - -Explanation: -For L = 0 and R = 2, a0 = 2, a1 = 3 and a2 = 2, since they are in the valid order,answer is Yes. -For L = 1 and R = 3, a1 = 3, a2 = 2 and a3 = 4, since a1 > a2 and a2 < a4 the order isn't valid, hence the answer is No. -""" -def processqueries(arr,n,m,q): - result = [] - for i in range(m): # each list inside q - boundary = q[i] - bound_a = boundary[0] - bound_b = boundary[1] - - sub_array = arr[bound_a:bound_b+1] - m = sub_array.index(max(sub_array)) - if sorted(sub_array) == sub_array: # increasing order - result.append('Yes') - elif sorted(sub_array, reverse=True) == sub_array: # decreasing order - result.append('Yes') - elif 0 <= m < len(sub_array): # first increaing then decreasing - left = sub_array[:m] - right = sub_array[m:] - if sorted(left) == left and sorted(right, reverse=True) == right: - print(f"left={left}\nright={right},\nm={m},\nsub_array={sub_array}") - result.append("Yes") - else: - print(f"\nLeft sub_array:{left}, \nright sub_array:{right}\nPrinting No") - result.append("No") - return result - - -if __name__ == "__main__": - t = int(input()) - x = 0 - while x < t: - n = int(input()) - arr = list(map(int, input().split())) - m = int(input()) - q = list() - for i in range(0,m): - q.append(list(map(int, input().split()))) - result = processqueries(arr,n,m,q) - for i in result: - print(i) +""" +Mountain Subarray Problem +We are given an array of integers and a range, we need to find whether the subarray which falls in this range has values in the form of a mountain or not. All values of the subarray are said to be in the form of a mountain if either all values are increasing or decreasing or first increasing and then decreasing. More formally a subarray [a1, a2, a3 … aN] is said to be in form of a mountain if there exists an integer K, 1 <= K <= N such that, +a1 <= a2 <= a3 .. <= aK >= a(K+1) >= a(K+2) …. >= aN +You have to process Q queries. In each query you are given two integer L and R, denoting starting and last index of the subarrays respectively. + +Input: +The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N denoting the size of the array. The following line contains N space-separated integers forming the array. Next line contains an integer Q, denoting the number of queries. For each query, you are given two space-separated integers L and R in a new line. + +Output: +For each query, print "Yes" (without quotes) if the subarray is in mountain form, otherwise print "No" (without quotes) in a new line. + +Expected Time Complexity: O(N + Q). +Expected Auxiliary Space: O(N). + +Constraints: +1 <= T <= 100 +1 <= N, Q <= 105 +1 <= a[i] <= 106, for each valid i +0 <= L <= R <= N-1 + +Example: +Input: +1 +8 +2 3 2 4 4 6 3 2 +2 +0 2 +1 3 + +Output: +Yes +No + +Explanation: +For L = 0 and R = 2, a0 = 2, a1 = 3 and a2 = 2, since they are in the valid order,answer is Yes. +For L = 1 and R = 3, a1 = 3, a2 = 2 and a3 = 4, since a1 > a2 and a2 < a4 the order isn't valid, hence the answer is No. +""" +def processqueries(arr,n,m,q): + result = [] + for i in range(m): # each list inside q + boundary = q[i] + bound_a = boundary[0] + bound_b = boundary[1] + + sub_array = arr[bound_a:bound_b+1] + m = sub_array.index(max(sub_array)) + if sorted(sub_array) == sub_array: # increasing order + result.append('Yes') + elif sorted(sub_array, reverse=True) == sub_array: # decreasing order + result.append('Yes') + elif 0 <= m < len(sub_array): # first increaing then decreasing + left = sub_array[:m] + right = sub_array[m:] + if sorted(left) == left and sorted(right, reverse=True) == right: + print(f"left={left}\nright={right},\nm={m},\nsub_array={sub_array}") + result.append("Yes") + else: + print(f"\nLeft sub_array:{left}, \nright sub_array:{right}\nPrinting No") + result.append("No") + return result + + +if __name__ == "__main__": + t = int(input()) + x = 0 + while x < t: + n = int(input()) + arr = list(map(int, input().split())) + m = int(input()) + q = list() + for i in range(0,m): + q.append(list(map(int, input().split()))) + result = processqueries(arr,n,m,q) + for i in result: + print(i) x += 1 \ No newline at end of file diff --git a/Arrays/WaveArray.py b/Arrays/WaveArray.py index 2544eeb..58cd2c3 100644 --- a/Arrays/WaveArray.py +++ b/Arrays/WaveArray.py @@ -1,57 +1,57 @@ -""" -Problem Statement: -Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). - -Example 1: - -Input: -N = 5 -arr[] = {1,2,3,4,5} -Output: 2 1 4 3 5 -Explanation: Array elements after -sorting it in wave form are -2 1 4 3 5. - - -Example 2: - -Input: -N = 6 -arr[] = {2,4,7,8,9,10} -Output: 4 2 8 7 10 9 -Explanation: Array elements after -sorting it in wave form are -4 2 8 7 10 9. -Your Task: -The task is to complete the function convertToWave() which converts the given array to wave array. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(1). - -Constraints: -1 ≤ N ≤ 106 -0 ≤ A[i] ≤107 - - -""" - -def convertToWave(A,N): - i = 0 - while i < N: - if (i+1)< N: - a,b = A[i], A[i+1] - A[i] = max(a,b) - A[i+1] = min(a,b) - else: - pass - i += 2 - -if __name__ == "__main__": - i = 0 - t = int(input()) - while i < t: - N = int(input()) - A = list(map(int, input().split())) - convertToWave(A,N) - for i in A: +""" +Problem Statement: +Given a sorted array arr[] of distinct integers. Sort the array into a wave-like array and return it. In other words, arrange the elements into a sequence such that a1 >= a2 <= a3 >= a4 <= a5..... (considering the increasing lexicographical order). + +Example 1: + +Input: +N = 5 +arr[] = {1,2,3,4,5} +Output: 2 1 4 3 5 +Explanation: Array elements after +sorting it in wave form are +2 1 4 3 5. + + +Example 2: + +Input: +N = 6 +arr[] = {2,4,7,8,9,10} +Output: 4 2 8 7 10 9 +Explanation: Array elements after +sorting it in wave form are +4 2 8 7 10 9. +Your Task: +The task is to complete the function convertToWave() which converts the given array to wave array. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(1). + +Constraints: +1 ≤ N ≤ 106 +0 ≤ A[i] ≤107 + + +""" + +def convertToWave(A,N): + i = 0 + while i < N: + if (i+1)< N: + a,b = A[i], A[i+1] + A[i] = max(a,b) + A[i+1] = min(a,b) + else: + pass + i += 2 + +if __name__ == "__main__": + i = 0 + t = int(input()) + while i < t: + N = int(input()) + A = list(map(int, input().split())) + convertToWave(A,N) + for i in A: print(i,end=" ") \ No newline at end of file diff --git a/Arrays/contigous_subarraySum.py b/Arrays/contigous_subarraySum.py index 773281d..379ea55 100644 --- a/Arrays/contigous_subarraySum.py +++ b/Arrays/contigous_subarraySum.py @@ -1,34 +1,34 @@ -""" -source : https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1# -""" - -import math - -class Solution: - ##Complete this function - #Function to find the sum of contiguous subarray with maximum sum. - def maxSubArraySum(self,a,size): - max_so_far = -10**7 - max_end_here = 0 - - for i in range(size): - max_end_here += a[i] - if max_so_far < max_end_here: - max_so_far = max_end_here - if max_end_here < 0: - max_end_here = 0 - return max_so_far - -def main(): - T = int(input()) - while T > 0: - n = int(input()) - arr = [int(x) for x in input().strip().split()] - ob = Solution() - print(ob.maxSubArraySum(arr, n)) - - T -= 1 - - -if __name__ == '__main__': +""" +source : https://practice.geeksforgeeks.org/problems/kadanes-algorithm-1587115620/1# +""" + +import math + +class Solution: + ##Complete this function + #Function to find the sum of contiguous subarray with maximum sum. + def maxSubArraySum(self,a,size): + max_so_far = -10**7 + max_end_here = 0 + + for i in range(size): + max_end_here += a[i] + if max_so_far < max_end_here: + max_so_far = max_end_here + if max_end_here < 0: + max_end_here = 0 + return max_so_far + +def main(): + T = int(input()) + while T > 0: + n = int(input()) + arr = [int(x) for x in input().strip().split()] + ob = Solution() + print(ob.maxSubArraySum(arr, n)) + + T -= 1 + + +if __name__ == '__main__': main() \ No newline at end of file diff --git a/Arrays/dist_between_two_nos.py b/Arrays/dist_between_two_nos.py index dfb33a0..10a58ee 100644 --- a/Arrays/dist_between_two_nos.py +++ b/Arrays/dist_between_two_nos.py @@ -1,66 +1,66 @@ -""" -Minimum distance between two numbers - -You are given an array A, of N elements. Find minimum index based distance between two elements of the array, x and y. - -Input : -The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case consists of three lines. The first line of each test case contains an integer N denoting size array. Then in the next line are N space separated values of the array A. The last line of each test case contains two integers x and y. - -Output : -Print the minimum index based distance between x and y. - -Your Task: -Complete the function minDist() which takes the array, n, x and y as input parameters and returns the minimum distance between x and y in the array. If no such distance is possible then return -1. - -Expected Time Complexity: O(N) -Expected Auxiliary Space: O(1) - -Constraints: -1 <= T <= 100 -1 <= N <= 105 -0 <= A[i], x, y <= 105 - -Example: -Sample Input: -2 -4 -1 2 3 2 -1 2 -7 -86 39 90 67 84 66 62 -42 12 - -Sample Output: -1 --1 - -Explanation: -Testcase1: x = 1 and y = 2. There are two distances between x and y, which are 1 and 3 out of which the least is 1. -Testcase2: x = 42 and y = 12. We return -1 as x and y don't exist in the array. -""" - -def minDist(arr, n, x, y): - # Code here - dist = -1 - if x in arr and y in arr: - x_index = [pos for pos, elem in enumerate(arr) if elem == x] - y_index = [pos for pos, elem in enumerate(arr) if elem == y] - min_dist = 0 - for a in x_index: - for b in y_index: - if min_dist == 0: - min_dist = abs(b-a) - elif abs(a - b) < min_dist: - min_dist = abs(b-a) - return min_dist - else: - return dist - - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().split())) - x, y = tuple(map(int, input().split())) - print(minDist(arr, n, x, y)) +""" +Minimum distance between two numbers + +You are given an array A, of N elements. Find minimum index based distance between two elements of the array, x and y. + +Input : +The first line of input contains an integer T, denoting the number of test cases. Then T test cases follow. Each test case consists of three lines. The first line of each test case contains an integer N denoting size array. Then in the next line are N space separated values of the array A. The last line of each test case contains two integers x and y. + +Output : +Print the minimum index based distance between x and y. + +Your Task: +Complete the function minDist() which takes the array, n, x and y as input parameters and returns the minimum distance between x and y in the array. If no such distance is possible then return -1. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= T <= 100 +1 <= N <= 105 +0 <= A[i], x, y <= 105 + +Example: +Sample Input: +2 +4 +1 2 3 2 +1 2 +7 +86 39 90 67 84 66 62 +42 12 + +Sample Output: +1 +-1 + +Explanation: +Testcase1: x = 1 and y = 2. There are two distances between x and y, which are 1 and 3 out of which the least is 1. +Testcase2: x = 42 and y = 12. We return -1 as x and y don't exist in the array. +""" + +def minDist(arr, n, x, y): + # Code here + dist = -1 + if x in arr and y in arr: + x_index = [pos for pos, elem in enumerate(arr) if elem == x] + y_index = [pos for pos, elem in enumerate(arr) if elem == y] + min_dist = 0 + for a in x_index: + for b in y_index: + if min_dist == 0: + min_dist = abs(b-a) + elif abs(a - b) < min_dist: + min_dist = abs(b-a) + return min_dist + else: + return dist + + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().split())) + x, y = tuple(map(int, input().split())) + print(minDist(arr, n, x, y)) diff --git a/Arrays/duplicates_in_primenumbers_array.py b/Arrays/duplicates_in_primenumbers_array.py index b308d9e..a7dfa29 100644 --- a/Arrays/duplicates_in_primenumbers_array.py +++ b/Arrays/duplicates_in_primenumbers_array.py @@ -1,53 +1,53 @@ -""" -Given an array consisting of only prime numbers, remove all duplicate numbers from it. -Note: Retain the first occurrence of the duplicate element. - -Input: -First line of input contains number of testcases T. For each testcase, there will be two lines, first of which contains N, the size of array. The second line contains N space separated elements of the array. - -Output: -Print the resultant array with no duplicate elements. - -Your Task: -Complete the function removeDuplicate() that takes given array and N as input parameters and returns modified array which has no duplicates. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(N). - -Constraints: -1<=T<=200 -1<=N=1000 -2<=A[i]<100 - -Example: -Sample Input: -1 -6 -2 2 3 3 7 5 - -Sample Output: -2 3 7 5 - -Explanation: -After removing the duplicate 2 and 3 we get 2 3 7 5. -""" - - -def removeDuplicates(arr): - # code here - registered = [] - for i in arr: - if i not in registered: - registered.append(i) - return registered - - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().split())) - res = removeDuplicates(arr) - for i in res: - print(i, end=" ") - print() +""" +Given an array consisting of only prime numbers, remove all duplicate numbers from it. +Note: Retain the first occurrence of the duplicate element. + +Input: +First line of input contains number of testcases T. For each testcase, there will be two lines, first of which contains N, the size of array. The second line contains N space separated elements of the array. + +Output: +Print the resultant array with no duplicate elements. + +Your Task: +Complete the function removeDuplicate() that takes given array and N as input parameters and returns modified array which has no duplicates. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(N). + +Constraints: +1<=T<=200 +1<=N=1000 +2<=A[i]<100 + +Example: +Sample Input: +1 +6 +2 2 3 3 7 5 + +Sample Output: +2 3 7 5 + +Explanation: +After removing the duplicate 2 and 3 we get 2 3 7 5. +""" + + +def removeDuplicates(arr): + # code here + registered = [] + for i in arr: + if i not in registered: + registered.append(i) + return registered + + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().split())) + res = removeDuplicates(arr) + for i in res: + print(i, end=" ") + print() diff --git a/Arrays/find_duplicate_element.py b/Arrays/find_duplicate_element.py index bf07f40..bc17d49 100644 --- a/Arrays/find_duplicate_element.py +++ b/Arrays/find_duplicate_element.py @@ -1,13 +1,13 @@ -"""source:https://leetcode.com/problems/find-the-duplicate-number/ -""" -from typing import List - -class Solution: - def findDuplicate(self, nums: List[int]) -> int: - visited = set() - for idx in range(len(nums)): - if nums[idx] in visited: - return nums[idx] - else: - visited.add(nums[idx]) +"""source:https://leetcode.com/problems/find-the-duplicate-number/ +""" +from typing import List + +class Solution: + def findDuplicate(self, nums: List[int]) -> int: + visited = set() + for idx in range(len(nums)): + if nums[idx] in visited: + return nums[idx] + else: + visited.add(nums[idx]) return 0 \ No newline at end of file diff --git a/Arrays/find_duplicates.py b/Arrays/find_duplicates.py index 58b73aa..2459cb7 100644 --- a/Arrays/find_duplicates.py +++ b/Arrays/find_duplicates.py @@ -1,65 +1,65 @@ -""" -Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array. - -Input: -The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N which denotes the number of elements in the array. The second line of each test case contains n space separated integers denoting elements of the array a[]. - -Output: -Print the duplicate elements from the given array. The order of the output should be in sorted order. Print -1 if no duplicate exists. - -Your Task: -Complete the function duplicates() which takes array a[] and n as input as parameters and returns a list of elements that occur more than once in the given array in sorted manner. If no such element is found return -1. - -Expected Time Complexity: O(n). -Expected Auxiliary Space: O(n). -Note : The extra space is only for the array to be returned. -Try and perform all operation withing the provided array. - -Constraints: -1 <= T <= 100 -1 <= N <= 105 -0 <= A[i] <= N-1, for each valid i - -Example: -Sample Input: -2 -4 -0 3 1 2 -5 -2 3 1 2 3 - -Sample Output: --1 -2 3 - -Explanation: -Testcase 1: N=4 and all elements from 0 to (N-1 = 3) are present in the given array. Therefore output is -1. -Testcase 2: 2 and 3 occur more than once in the given array. -""" -def duplicates(arr, n): - freq_dict = {} - for i in arr: - if i not in freq_dict.keys(): - freq_dict[i] = 1 - else: - freq_dict[i] += 1 - res = [i for i in freq_dict.keys() if freq_dict[i] > 1] - - if len(res) == 0: - return [-1] - else: - return sorted(res) - -# { -# Driver Code Starts -if (__name__ == '__main__'): - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().strip().split())) - res = duplicates(arr, n) - for i in res: - print(i, end=" ") - print() - +""" +Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array. + +Input: +The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N which denotes the number of elements in the array. The second line of each test case contains n space separated integers denoting elements of the array a[]. + +Output: +Print the duplicate elements from the given array. The order of the output should be in sorted order. Print -1 if no duplicate exists. + +Your Task: +Complete the function duplicates() which takes array a[] and n as input as parameters and returns a list of elements that occur more than once in the given array in sorted manner. If no such element is found return -1. + +Expected Time Complexity: O(n). +Expected Auxiliary Space: O(n). +Note : The extra space is only for the array to be returned. +Try and perform all operation withing the provided array. + +Constraints: +1 <= T <= 100 +1 <= N <= 105 +0 <= A[i] <= N-1, for each valid i + +Example: +Sample Input: +2 +4 +0 3 1 2 +5 +2 3 1 2 3 + +Sample Output: +-1 +2 3 + +Explanation: +Testcase 1: N=4 and all elements from 0 to (N-1 = 3) are present in the given array. Therefore output is -1. +Testcase 2: 2 and 3 occur more than once in the given array. +""" +def duplicates(arr, n): + freq_dict = {} + for i in arr: + if i not in freq_dict.keys(): + freq_dict[i] = 1 + else: + freq_dict[i] += 1 + res = [i for i in freq_dict.keys() if freq_dict[i] > 1] + + if len(res) == 0: + return [-1] + else: + return sorted(res) + +# { +# Driver Code Starts +if (__name__ == '__main__'): + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().strip().split())) + res = duplicates(arr, n) + for i in res: + print(i, end=" ") + print() + # } Driver Code Ends \ No newline at end of file diff --git a/Arrays/intersection_elements.py b/Arrays/intersection_elements.py index ffbadfb..4e95ce0 100644 --- a/Arrays/intersection_elements.py +++ b/Arrays/intersection_elements.py @@ -1,68 +1,68 @@ -""" -Intersection of two arrays - -Given two arrays A and B respectively of size N and M, the task is to print the count of elements in the intersection (or common elements) of the two arrays. - -For this question, the intersection of two arrays can be defined as the set containing distinct common elements between the two arrays. - -Example 1: - -Input: -N = 5, M = 3 -A[] = {89,24,75,11,23} -B[] = {89,2,4} -Output: 1 -Explanation: 89 is the only element -in the intersection of two arrays. - -Example 2: - -Input: -N = 6, M = 5 -A[] = {1,2,3,4,5,6} -B[] = {3,4,5,6,7} -Output: 4 -Explanation: 3 4 5 and 6 are the elements -in the intersection of two arrays. - -Input: -The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N and M, N is the size of array A and M is the size of array B. The second line of each test case contains N input A[i]. -The third line of each test case contains M input B[i]. - -Output: -Print the count of intersecting elements. - -Your Task: -The task is to complete the function NumberofElementsInIntersection() which takes 4 inputs ie- array a, array b, n which is the size of array a, m which is the size of array b. The function should return the count of the number of elements in the intersection. - -Expected Time Complexity: O(N + M). -Expected Auxiliary Space: O(min(N,M)). - -Constraints: -1 ≤ N, M ≤ 105 -1 ≤ A[i], B[i] ≤ 105 - -Time limit: 30 min -Code has expected 0.03s time complexity -""" - - -def NumberofElementsInIntersection(a, b, n, m): - return len(set.intersection(set(a),set(b))) - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - - -#contributed by RavinderSinghPB - -if __name__=='__main__': - t=int(input()) - for _ in range(t): - - n,m=[int(x) for x in input().strip().split()] - - a=[int(x) for x in input().strip().split()] +""" +Intersection of two arrays + +Given two arrays A and B respectively of size N and M, the task is to print the count of elements in the intersection (or common elements) of the two arrays. + +For this question, the intersection of two arrays can be defined as the set containing distinct common elements between the two arrays. + +Example 1: + +Input: +N = 5, M = 3 +A[] = {89,24,75,11,23} +B[] = {89,2,4} +Output: 1 +Explanation: 89 is the only element +in the intersection of two arrays. + +Example 2: + +Input: +N = 6, M = 5 +A[] = {1,2,3,4,5,6} +B[] = {3,4,5,6,7} +Output: 4 +Explanation: 3 4 5 and 6 are the elements +in the intersection of two arrays. + +Input: +The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N and M, N is the size of array A and M is the size of array B. The second line of each test case contains N input A[i]. +The third line of each test case contains M input B[i]. + +Output: +Print the count of intersecting elements. + +Your Task: +The task is to complete the function NumberofElementsInIntersection() which takes 4 inputs ie- array a, array b, n which is the size of array a, m which is the size of array b. The function should return the count of the number of elements in the intersection. + +Expected Time Complexity: O(N + M). +Expected Auxiliary Space: O(min(N,M)). + +Constraints: +1 ≤ N, M ≤ 105 +1 ≤ A[i], B[i] ≤ 105 + +Time limit: 30 min +Code has expected 0.03s time complexity +""" + + +def NumberofElementsInIntersection(a, b, n, m): + return len(set.intersection(set(a),set(b))) + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + + +#contributed by RavinderSinghPB + +if __name__=='__main__': + t=int(input()) + for _ in range(t): + + n,m=[int(x) for x in input().strip().split()] + + a=[int(x) for x in input().strip().split()] b=[int(x) for x in input().strip().split()] \ No newline at end of file diff --git a/Arrays/max_second_max.py b/Arrays/max_second_max.py index c179465..f1ad4ec 100644 --- a/Arrays/max_second_max.py +++ b/Arrays/max_second_max.py @@ -1,25 +1,25 @@ -def largestAndSecondLargest(sizeOfArray, arr): - if sizeOfArray < 2: - return [arr[0], -1] - else: - maxx, second_max = sorted(arr)[-1], sorted(arr)[-2] - if maxx == second_max: - set_arr = list(sorted(set(arr))) - if len(set_arr) > 1: - return [set_arr[-1], set_arr[-2]] - else: - return [set_arr[-1], -1] - else: - return [maxx, second_max] - - -if __name__ == "__main__": - t = int(input()) - while t > 0: - sizeOfArray = int(input()) - arr = [int(x) for x in input().split()] - li = largestAndSecondLargest(sizeOfArray, arr) - for val in li: - print(val, end=" ") - print() - t -= 1 +def largestAndSecondLargest(sizeOfArray, arr): + if sizeOfArray < 2: + return [arr[0], -1] + else: + maxx, second_max = sorted(arr)[-1], sorted(arr)[-2] + if maxx == second_max: + set_arr = list(sorted(set(arr))) + if len(set_arr) > 1: + return [set_arr[-1], set_arr[-2]] + else: + return [set_arr[-1], -1] + else: + return [maxx, second_max] + + +if __name__ == "__main__": + t = int(input()) + while t > 0: + sizeOfArray = int(input()) + arr = [int(x) for x in input().split()] + li = largestAndSecondLargest(sizeOfArray, arr) + for val in li: + print(val, end=" ") + print() + t -= 1 diff --git a/Arrays/max_sum_path.py b/Arrays/max_sum_path.py index 3e77d74..2842b24 100644 --- a/Arrays/max_sum_path.py +++ b/Arrays/max_sum_path.py @@ -1,79 +1,79 @@ -""" -Given two sorted arrays A and B, such that the arrays may have some common elements. Find the sum of the maximum sum path to reach from the beginning of any array to end of any of the two arrays. We can switch from one array to another array only at the common elements. - -Input: -First line of input contains number of testcases T. For each testcase, there will be three lines. First line contains M and N denoting the length of the two sorted array A and B respectively. Second line contains elements of array A. Third line contains elements of array B. - -Output: -For each test case, the output is the max sum obtained from the two arrays. - -Your Task: -Complete the function max_path_sum() that takes the two arrays A and B along with their sizes M and N as input parameters. It returns the sum of the maximum sum path. - -Expected Time Complexity: O(M + N) -Expected Auxiliary Space: O(1) - -Constraints: -1 <= T <= 100 -1 <= M,N <= 105 -1 <= A[i], B[i] <= 106 - -Example: -Sample Input: -2 -5 4 -2 3 7 10 12 -1 5 7 8 -3 3 -1 2 4 -1 2 7 - -Sample Output: -35 -10 - -Explanation: -Testcase 1: The path will be 1+5+7+10+12 = 35. -Testcase 2: The path will be 1+2+7=10 -""" -def maxSumPath(arr1, arr2, m, n): - # code here - # 1 2 3 5 6 - # 2 3 3 4 - sum1 = 0 - sum2 = 0 - i = 0 - j = 0 - mainsum = 0 - while i < m and j < n: - - if arr1[i] == arr2[j]: - mainsum += max(sum1, sum2) - # print("mainsum incremented ",mainsum) - sum1 = arr1[i] - sum2 = arr2[j] - i += 1 - j += 1 - elif arr1[i] < arr2[j]: - sum1 += arr1[i] - i += 1 - elif arr2[j] < arr1[i]: - sum2 += arr2[j] - j += 1 - - for num in arr2[j:]: - sum2 += num - for num in arr1[i:]: - sum1 += num - # print(sum1,sum2) - mainsum += max(sum1, sum2) - - return (mainsum) - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - m,n = list(map(int, input().split())) - arr1 = list(map(int, input().split())) - arr2 = list(map(int, input().split())) +""" +Given two sorted arrays A and B, such that the arrays may have some common elements. Find the sum of the maximum sum path to reach from the beginning of any array to end of any of the two arrays. We can switch from one array to another array only at the common elements. + +Input: +First line of input contains number of testcases T. For each testcase, there will be three lines. First line contains M and N denoting the length of the two sorted array A and B respectively. Second line contains elements of array A. Third line contains elements of array B. + +Output: +For each test case, the output is the max sum obtained from the two arrays. + +Your Task: +Complete the function max_path_sum() that takes the two arrays A and B along with their sizes M and N as input parameters. It returns the sum of the maximum sum path. + +Expected Time Complexity: O(M + N) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= T <= 100 +1 <= M,N <= 105 +1 <= A[i], B[i] <= 106 + +Example: +Sample Input: +2 +5 4 +2 3 7 10 12 +1 5 7 8 +3 3 +1 2 4 +1 2 7 + +Sample Output: +35 +10 + +Explanation: +Testcase 1: The path will be 1+5+7+10+12 = 35. +Testcase 2: The path will be 1+2+7=10 +""" +def maxSumPath(arr1, arr2, m, n): + # code here + # 1 2 3 5 6 + # 2 3 3 4 + sum1 = 0 + sum2 = 0 + i = 0 + j = 0 + mainsum = 0 + while i < m and j < n: + + if arr1[i] == arr2[j]: + mainsum += max(sum1, sum2) + # print("mainsum incremented ",mainsum) + sum1 = arr1[i] + sum2 = arr2[j] + i += 1 + j += 1 + elif arr1[i] < arr2[j]: + sum1 += arr1[i] + i += 1 + elif arr2[j] < arr1[i]: + sum2 += arr2[j] + j += 1 + + for num in arr2[j:]: + sum2 += num + for num in arr1[i:]: + sum1 += num + # print(sum1,sum2) + mainsum += max(sum1, sum2) + + return (mainsum) + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + m,n = list(map(int, input().split())) + arr1 = list(map(int, input().split())) + arr2 = list(map(int, input().split())) print(maxSumPath(arr1, arr2, m, n)) \ No newline at end of file diff --git a/Arrays/maximize_arraySum.py b/Arrays/maximize_arraySum.py new file mode 100644 index 0000000..4b4906a --- /dev/null +++ b/Arrays/maximize_arraySum.py @@ -0,0 +1,27 @@ +def solve(arr, max_sum=0): + if len(arr) == 1: + max_sum += arr[0] + print(max_sum) + return + elif len(arr) == 0: + print(max_sum) + return + + max_elem = max(arr) + elem_index = arr.index(max_elem) + if len(arr) > 1 and elem_index == 0 : + max_elem = max(arr[1:]) + elem_index = arr.index(max_elem) + max_sum += max_elem + print(f"selected: {max_elem}, removed: {arr[elem_index-1]}") + del arr[elem_index] + del arr[elem_index-1] + print("arr now:", arr) + solve(arr, max_sum) + +if __name__=='__main__': + test_cases=int(input()) + for i in range(test_cases): + size = int(input()) # take size of the array + arr_elems = list(map(int, input().split())) # take the array elements + solve(arr_elems) \ No newline at end of file diff --git a/Arrays/maximum_index_difference.py b/Arrays/maximum_index_difference.py index 36c2ab6..6388ebb 100644 --- a/Arrays/maximum_index_difference.py +++ b/Arrays/maximum_index_difference.py @@ -1,24 +1,24 @@ -#Complete this function -def maxIndexDiff(arr, n): - ##Your code here - max_diff = 0 - for i in range(n-1): - prev = arr[i] - for j in range(i+1,n): - elem = arr[j] - print(f'i={i},j={j},prev={prev},elem={elem}') - index_diff = j - i - print("Index diff = ",index_diff) - if index_diff > max_diff and prev >= elem: - print("here") - max_diff = index_diff.copy() - print(f'max_diff={max_diff}') - return max_diff - -if __name__ == "__main__": - t = int(input()) - while t: - n = int(input()) - arr = list(map(int, input().split())) - print(maxIndexDiff(arr,n)) +#Complete this function +def maxIndexDiff(arr, n): + ##Your code here + max_diff = 0 + for i in range(n-1): + prev = arr[i] + for j in range(i+1,n): + elem = arr[j] + print(f'i={i},j={j},prev={prev},elem={elem}') + index_diff = j - i + print("Index diff = ",index_diff) + if index_diff > max_diff and prev >= elem: + print("here") + max_diff = index_diff.copy() + print(f'max_diff={max_diff}') + return max_diff + +if __name__ == "__main__": + t = int(input()) + while t: + n = int(input()) + arr = list(map(int, input().split())) + print(maxIndexDiff(arr,n)) t -= 1 \ No newline at end of file diff --git a/Arrays/merge_without_extra_space.py b/Arrays/merge_without_extra_space.py index a5b28f8..e9aebaa 100644 --- a/Arrays/merge_without_extra_space.py +++ b/Arrays/merge_without_extra_space.py @@ -1,9 +1,9 @@ -""" -source: https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays5135/1 -""" -def merge(arr1, m, arr2, n): - tot_size = m + n - gap = tot_size // 2 + tot_size % 2 - for i in range(tot_size): - if i < m: - a = arr1[i] +""" +source: https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays5135/1 +""" +def merge(arr1, m, arr2, n): + tot_size = m + n + gap = tot_size // 2 + tot_size % 2 + for i in range(tot_size): + if i < m: + a = arr1[i] diff --git a/Arrays/min_heights_2.py b/Arrays/min_heights_2.py index 35789d1..4d58f5b 100644 --- a/Arrays/min_heights_2.py +++ b/Arrays/min_heights_2.py @@ -1,30 +1,30 @@ -""" -source: https://practice.geeksforgeeks.org/problems/minimize-the-heights3351/1# -""" - -class Solution: - def getMinDiff(self, arr, n, k): - # code here - arr.sort() - result = arr[-1] - arr[0] - - for i in range(n): - if arr[i] >= k: - max_elem = max(arr[i-1] + k, arr[n-1] - k) - min_elem = min(arr[0] + k, arr[i] - k) - - result = min(result, max_elem - min_elem) - else: - continue - return result - -if __name__ == '__main__': - tc = int(input()) - while tc > 0: - k = int(input()) - n = int(input()) - arr = list(map(int, input().strip().split())) - ob = Solution() - ans = ob.getMinDiff(arr, n, k) - print(ans) +""" +source: https://practice.geeksforgeeks.org/problems/minimize-the-heights3351/1# +""" + +class Solution: + def getMinDiff(self, arr, n, k): + # code here + arr.sort() + result = arr[-1] - arr[0] + + for i in range(n): + if arr[i] >= k: + max_elem = max(arr[i-1] + k, arr[n-1] - k) + min_elem = min(arr[0] + k, arr[i] - k) + + result = min(result, max_elem - min_elem) + else: + continue + return result + +if __name__ == '__main__': + tc = int(input()) + while tc > 0: + k = int(input()) + n = int(input()) + arr = list(map(int, input().strip().split())) + ob = Solution() + ans = ob.getMinDiff(arr, n, k) + print(ans) tc -= 1 \ No newline at end of file diff --git a/Arrays/product_array_puzzle.py b/Arrays/product_array_puzzle.py index df5c3ab..3c43b5b 100644 --- a/Arrays/product_array_puzzle.py +++ b/Arrays/product_array_puzzle.py @@ -1,80 +1,80 @@ - -""" -Problem statement: -Given an array A of size N, construct a Product Array P (of same size) such that P is equal to the product of all the elements of A except A[i]. - -Input: -The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first line is N. The second line contains N elements separated by spaces. It is guranteed that the product of all the elements of the array will not exceed 1e18. - -Output: -For every test case, print the product array in a new line. If the array has only one element print 1. - -Your Task: -You do not have to read input. Your task is to complete productExceptSelf() function and returns the Product vector P that holds product except for self at each index. - -Note: Try to solve this problem without using the division operation. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(N). - -Constraints: -1 <= T <= 100 -1 <= N <= 1000 -0 <= Ai <= 200 - -Example: -Input: -2 -5 -10 3 5 6 2 -2 -12 0 -Output: -180 600 360 300 900 -0 12 - -Explanation: -Testcase1: For the product array P, at i=0 we have 3*5*6*2. At i=1 10*5*6*2. At i=2 we have 10*3*6*2. At i=3 we have 10*3*5*2. At i=4 we have 10*3*5*6 -So P is 180 600 360 300 900 - -""" -def productExceptSelf(arr, n): - #code here - p = [] - prod = 1 - flag = 0 - for i in arr: - if i != 0: - prod *= i - else: - flag += 1 - - for i in arr: - if flag > 1: - p.append(0) - else: - if i != 0 and flag == 1: - p.append(0) - elif i == 0 and flag == 1: - p.append(prod) - else: - p.append(prod//i) - return p - - - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -if __name__ == '__main__': - t=int(input()) - - for _ in range(t): - n=int(input()) - arr=[int(x) for x in input().split()] - - ans=productExceptSelf(arr,n) - print(*ans) + +""" +Problem statement: +Given an array A of size N, construct a Product Array P (of same size) such that P is equal to the product of all the elements of A except A[i]. + +Input: +The first line of input contains an integer T denoting the number of test cases. T testcases follow. Each testcase contains two lines of input. The first line is N. The second line contains N elements separated by spaces. It is guranteed that the product of all the elements of the array will not exceed 1e18. + +Output: +For every test case, print the product array in a new line. If the array has only one element print 1. + +Your Task: +You do not have to read input. Your task is to complete productExceptSelf() function and returns the Product vector P that holds product except for self at each index. + +Note: Try to solve this problem without using the division operation. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(N). + +Constraints: +1 <= T <= 100 +1 <= N <= 1000 +0 <= Ai <= 200 + +Example: +Input: +2 +5 +10 3 5 6 2 +2 +12 0 +Output: +180 600 360 300 900 +0 12 + +Explanation: +Testcase1: For the product array P, at i=0 we have 3*5*6*2. At i=1 10*5*6*2. At i=2 we have 10*3*6*2. At i=3 we have 10*3*5*2. At i=4 we have 10*3*5*6 +So P is 180 600 360 300 900 + +""" +def productExceptSelf(arr, n): + #code here + p = [] + prod = 1 + flag = 0 + for i in arr: + if i != 0: + prod *= i + else: + flag += 1 + + for i in arr: + if flag > 1: + p.append(0) + else: + if i != 0 and flag == 1: + p.append(0) + elif i == 0 and flag == 1: + p.append(prod) + else: + p.append(prod//i) + return p + + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +if __name__ == '__main__': + t=int(input()) + + for _ in range(t): + n=int(input()) + arr=[int(x) for x in input().split()] + + ans=productExceptSelf(arr,n) + print(*ans) # } Driver Code Ends \ No newline at end of file diff --git a/Arrays/rearrage_negative_elems.py b/Arrays/rearrage_negative_elems.py index 9b3bd8b..330d07f 100644 --- a/Arrays/rearrage_negative_elems.py +++ b/Arrays/rearrage_negative_elems.py @@ -1,42 +1,42 @@ -""" -source: https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/ -""" -class Solution: - def segregateelements(self, arr, n): - # ------------ APPROACH WONT WORK IF QUESTION REQUIRES SHIFTING OF ELEMENTS ------------------ - # j = n-1 - # for i in range(n): - # print(f"Checking {arr[i]}") - # if arr[i] < 0 and i < j: - # print(f"\tswapped with :{arr[j]}") - # arr[i], arr[j] = arr[j], arr[i] - # print(f"\t{arr}") - # j -= 1 - - # ------------ APPROACH 2 ---------------- - negatives = [] - positives = [] - i = 0 - for elem in arr: - if elem < 0: - negatives.append(elem) - else: - positives.append(elem) - arr.clear() - arr.extend(positives + negatives) - -def main(): - T = int(input()) - - while T > 0: - n = int(input()) - a = [int(x) for x in input().strip().split()] - ob = Solution() - ob.segregateelements(a, n) - print(*a) - - T -= 1 - -if __name__ == '__main__': - main() - +""" +source: https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/ +""" +class Solution: + def segregateelements(self, arr, n): + # ------------ APPROACH WONT WORK IF QUESTION REQUIRES SHIFTING OF ELEMENTS ------------------ + # j = n-1 + # for i in range(n): + # print(f"Checking {arr[i]}") + # if arr[i] < 0 and i < j: + # print(f"\tswapped with :{arr[j]}") + # arr[i], arr[j] = arr[j], arr[i] + # print(f"\t{arr}") + # j -= 1 + + # ------------ APPROACH 2 ---------------- + negatives = [] + positives = [] + i = 0 + for elem in arr: + if elem < 0: + negatives.append(elem) + else: + positives.append(elem) + arr.clear() + arr.extend(positives + negatives) + +def main(): + T = int(input()) + + while T > 0: + n = int(input()) + a = [int(x) for x in input().strip().split()] + ob = Solution() + ob.segregateelements(a, n) + print(*a) + + T -= 1 + +if __name__ == '__main__': + main() + diff --git a/Arrays/rearrange_array.py b/Arrays/rearrange_array.py index 5da60eb..e2e68d7 100644 --- a/Arrays/rearrange_array.py +++ b/Arrays/rearrange_array.py @@ -1,60 +1,60 @@ -""" -Problem statement: -Rearrange an array with O(1) extra space - -Given an array arr[] of size N where every element is in the range from 0 to n-1. Rearrange the given array so that arr[i] becomes arr[arr[i]]. - -Example 1: - -Input: -N = 2 -arr[] = {1,0} -Output: 0 1 -Explanation: arr[0] = 1 and arr[arr[0]] -= 0.Also, arr[1] = 0 and arr[arr[1]] = 1. -So, rearranging elements, we get array -as, 0 1. - -Example 2: - -Input: -N = 5 -arr[] = {4,0,2,1,3} -Output: 3 4 2 0 1 -Explanation: arr[0] = 4 and arr[arr[0]] -= 3. Also, arr[1] = 0 and arr[arr[1]] -= 4 and so on. So, rearranging elements, -we get array as 3 4 2 0 1. - -Your Task: -The task is to complete the function arrange() which arranges the elements in the array. The printing is done automatically done by the driver code. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(1). - -Constraints: -1 <= N <= 107 -0 <= Arr[i] < N -""" - -def arrange(arr, n): - #Your code here - new_arr = arr.copy() - i = 0 - while i 0: - nd = [int(x) for x in input().strip().split()] - N = nd[0] - D = nd[1] - A = [int(e) for e in input().split()] - rotateArr(A, D, N) - for i in A: - print(i, end=" ") - print() - - T -= 1 +""" +Given an unsorted array arr[] of size N, rotate it by D elements in the counter-clockwise direction. + +Input: +The first line of the input contains T denoting the number of test cases. The first line of each test case contains two space-separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. The subsequent line will contain N space-separated array elements. + +Output: +For each test case, in a new line, print the rotated array. + +Your Task: +Complete the function rotateArr() which takes the array, D and N as input parameters and rotates the array by D elements. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= T <= 200 +1 <= N <= 107 +1 <= D <= N +0 <= arr[i] <= 105 + +Example: +Sample Input: +2 +5 2 +1 2 3 4 5 +10 3 +2 4 6 8 10 12 14 16 18 20 + +Sample Output: +3 4 5 1 2 +8 10 12 14 16 18 20 2 4 6 + +Explanation : +Testcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2. +Testcase 2: 2 4 6 8 10 12 14 16 18 20 when rotated by 3 elements, it becomes 8 10 12 14 16 18 20 2 4 6. +""" + + +def rotateArr(A, D, N): + # Your code here + A[D:] = A[D:] + A[:D] + del A[:D] + + +if __name__ == '__main__': + T = int(input()) + while T > 0: + nd = [int(x) for x in input().strip().split()] + N = nd[0] + D = nd[1] + A = [int(e) for e in input().split()] + rotateArr(A, D, N) + for i in A: + print(i, end=" ") + print() + + T -= 1 diff --git a/Arrays/sort_next_greater_lexOrder.py b/Arrays/sort_next_greater_lexOrder.py index df6e7f3..e881c5b 100644 --- a/Arrays/sort_next_greater_lexOrder.py +++ b/Arrays/sort_next_greater_lexOrder.py @@ -1,43 +1,43 @@ -""" -source:https://leetcode.com/problems/next-permutation/ -""" - -from typing import List - -class Solution: - def nextPermutation(self, nums: List[int]) -> None: - """ - Do not return anything, modify nums in-place instead. - """ - i = j = len(nums)-1 - while i > 0 and nums[i-1] >= nums[i]: - i -= 1 - - if i == 0: # nums are in descending order - nums.reverse() - return # usinf return statement to end the execution here (use the reversed nums array) - - - k = i - 1 # find the last "ascending" position - while nums[j] <= nums[k]: - j -= 1 - nums[k], nums[j] = nums[j], nums[k] - l, r = k+1, len(nums)-1 # reverse the second part - - # loop to reverse from next ascending element to end of array (inplace) - while l < r: - nums[l], nums[r] = nums[r], nums[l] - l +=1 ; r -= 1 - - -def main(): - tc = int(input()) - while tc: - arr = list(map(int, input().strip().split())) - ob = Solution() - ob.nextPermutation(arr) # inplace modification - print(arr) - tc -= 1 - -if __name__ == '__main__': - main() +""" +source:https://leetcode.com/problems/next-permutation/ +""" + +from typing import List + +class Solution: + def nextPermutation(self, nums: List[int]) -> None: + """ + Do not return anything, modify nums in-place instead. + """ + i = j = len(nums)-1 + while i > 0 and nums[i-1] >= nums[i]: + i -= 1 + + if i == 0: # nums are in descending order + nums.reverse() + return # usinf return statement to end the execution here (use the reversed nums array) + + + k = i - 1 # find the last "ascending" position + while nums[j] <= nums[k]: + j -= 1 + nums[k], nums[j] = nums[j], nums[k] + l, r = k+1, len(nums)-1 # reverse the second part + + # loop to reverse from next ascending element to end of array (inplace) + while l < r: + nums[l], nums[r] = nums[r], nums[l] + l +=1 ; r -= 1 + + +def main(): + tc = int(input()) + while tc: + arr = list(map(int, input().strip().split())) + ob = Solution() + ob.nextPermutation(arr) # inplace modification + print(arr) + tc -= 1 + +if __name__ == '__main__': + main() diff --git a/Arrays/sort_without_algo.py b/Arrays/sort_without_algo.py index 15a3d6c..5aea986 100644 --- a/Arrays/sort_without_algo.py +++ b/Arrays/sort_without_algo.py @@ -1,32 +1,32 @@ -""" -source: https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 -""" -class Solution: - def sort012(self,arr,n): - # code here - elem_hash = {} - for elem in arr: - if elem in elem_hash: - elem_hash[elem] += 1 - else: - elem_hash[elem] = 1 - arr.clear() - # -------------- incorrect approach (but may pass test as in dictionary order of elems is not always preserved ) ------------- - # for elem in elem_hash.keys(): - # arr.extend([elem]*elem_hash[elem]) - - # --------------- correct approach ---------------- - for elem in range(3): - if elem in elem_hash.keys(): - arr.extend([elem] * elem_hash[elem]) - -if __name__ == '__main__': - t = int(input()) - for _ in range(t): - n = int(input()) - arr = [int(x) for x in input().strip().split()] - ob = Solution() - ob.sort012(arr, n) - for i in arr: - print(i, end=" ") +""" +source: https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s/0 +""" +class Solution: + def sort012(self,arr,n): + # code here + elem_hash = {} + for elem in arr: + if elem in elem_hash: + elem_hash[elem] += 1 + else: + elem_hash[elem] = 1 + arr.clear() + # -------------- incorrect approach (but may pass test as in dictionary order of elems is not always preserved ) ------------- + # for elem in elem_hash.keys(): + # arr.extend([elem]*elem_hash[elem]) + + # --------------- correct approach ---------------- + for elem in range(3): + if elem in elem_hash.keys(): + arr.extend([elem] * elem_hash[elem]) + +if __name__ == '__main__': + t = int(input()) + for _ in range(t): + n = int(input()) + arr = [int(x) for x in input().strip().split()] + ob = Solution() + ob.sort012(arr, n) + for i in arr: + print(i, end=" ") print() \ No newline at end of file diff --git a/Arrays/sorted_subsequence_of_3.py b/Arrays/sorted_subsequence_of_3.py index e499f7b..96c9922 100644 --- a/Arrays/sorted_subsequence_of_3.py +++ b/Arrays/sorted_subsequence_of_3.py @@ -1,63 +1,63 @@ - - - -def find3number(A, n): - # code here - greater=[0]*n - smaller=[0]*n - smaller[0]=-1 - greater[n-1]=-1 - s,g=0,n-1 - for i in range(1,n): - if A[i]<=A[s]: - s=i - smaller[i]=-1 - else: - smaller[i]=s - for i in range(n-2,-1,-1): - if A[i]>=A[g]: - g=i - greater[i]=-1 - else: - greater[i]=g - for i in range(n): - if smaller[i]!=-1 and greater[i]!=-1: - return [A[smaller[i]],A[i],A[greater[i]]] - return [] - - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -import sys -sys.setrecursionlimit(100000) - -def isSubSeq(arr, lis, n, m): - if m==0: - return True - if n==0: - return False - if arr[n-1]==lis[m-1]: - return isSubSeq(arr, lis, n-1, m-1) - return isSubSeq(arr, lis, n-1, m) - -t=int(input()) -for _ in range(t): - n=int(input()) - arr=list(map(int, input().strip().split())) - lis = find3number(arr, n) - # print(lis) - # print(isSubSeq(arr, lis, n, len(lis))) - if len(lis)!=0 and len(lis)!=3: - print(-1) - continue - if len(lis)==0: - print(0) - elif lis[0]=A[g]: + g=i + greater[i]=-1 + else: + greater[i]=g + for i in range(n): + if smaller[i]!=-1 and greater[i]!=-1: + return [A[smaller[i]],A[i],A[greater[i]]] + return [] + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +import sys +sys.setrecursionlimit(100000) + +def isSubSeq(arr, lis, n, m): + if m==0: + return True + if n==0: + return False + if arr[n-1]==lis[m-1]: + return isSubSeq(arr, lis, n-1, m-1) + return isSubSeq(arr, lis, n-1, m) + +t=int(input()) +for _ in range(t): + n=int(input()) + arr=list(map(int, input().strip().split())) + lis = find3number(arr, n) + # print(lis) + # print(isSubSeq(arr, lis, n, len(lis))) + if len(lis)!=0 and len(lis)!=3: + print(-1) + continue + if len(lis)==0: + print(0) + elif lis[0]= 3: - return sorted(arr)[-3] - else: - return -1 - - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().split())) - print(thirdLargest(arr, n)) +"""" +Third largest element + +Given an array of distinct elements. Find the third largest element in it. + +Input: +The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. The first line of each test case is N, size of the array. The second line of each test case contains N space separated values of the array a[]. + +Output: +Print the third largest element of the array. If the array has less than 3 elements print -1. + +Your Task: +Complete the function thirdLargest() which takes the array a[] and the size of the array, n, as input parameters and returns the third largest element in the array. It return -1 if there are less than 3 elements in the given array. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(1) + +Constraints: +1 ≤ T ≤ 100 +1 ≤ N ≤ 105 +1 ≤ A[i] ≤ 105 + +Example: +Sample Input: +2 +5 +2 4 1 3 5 +2 +10 2 + +Sample Output: +3 +-1 + +Explanation: +Test Case 1: Largest number is 5, followed by 4 and then 3. Hence, the answer is 3. +Test Case 2: Since there are less than 3 numbers, output is -1. +""" + + +def thirdLargest(arr, n): + # code here + if n >= 3: + return sorted(arr)[-3] + else: + return -1 + + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().split())) + print(thirdLargest(arr, n)) diff --git a/Arrays/union_of_sorted_arrays.py b/Arrays/union_of_sorted_arrays.py index e205fe7..29ebe84 100644 --- a/Arrays/union_of_sorted_arrays.py +++ b/Arrays/union_of_sorted_arrays.py @@ -1,77 +1,77 @@ -""" -Problem Statement: -Union of Two Sorted Arrays - -Given two sorted arrays arr[] and brr[] of size N and M respectively. The task is to find the union of these two arrays. -Union of two arrays can be defined as the common and distinct elements in the two arrays. - -Example 1: - -Input: -N = 5, arr1[] = {1, 2, 3, 4, 5} -M = 3, arr2 [] = {1, 2, 3} -Output: 1 2 3 4 5 -Explanation: Distinct elements including -both the arrays are: 1 2 3 4 5. - -Example 2: - -Input: -N = 5, arr1[] = {2, 2, 3, 4, 5} -M = 5, arr2[] = {1, 1, 2, 3, 4} -Output: 1 2 3 4 5 -Explanation: Distinct elements including -both the arrays are: 1 2 3 4 5. - -Example 3: - -Input: -N = 5, arr1[] = {1, 1, 1, 1, 1} -M = 5, arr2[] = {2, 2, 2, 2, 2} -Output: 1 2 -Explanation: Distinct elements including -both the arrays are: 1 2. - - -Your Task: This is a function problem. You only need to complete the function findUnion() that takes two arrays arr1[], arr2[], and their size N and M as parameters and returns the union of two arrays. The new line is automatically appended by the driver code. - -Expected Time Complexity: O(N+M). -Expected Auxiliary Space: O(N+M). - -Constraints: -1 <= N, M <= 105 -1 <= arr[i], brr[i] <= 106 -""" -def mergeArrays(a,b,n,m): - ''' - :param a: given sorted array a - :param n: size of sorted array a - :param b: given sorted array b - :param m: size of sorted array b - :return: The union of both arrays as a list - ''' - # code here - union_array = a+b - sorted_union_array = list(set(union_array)) - return sorted(sorted_union_array) - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -# Contributed by : Nagendra Jha -# Modified by : Sagar Gupta - - -if __name__ == '__main__': - test_cases = int(input()) - for cases in range(test_cases) : - n,m = map(int,input().strip().split()) - a = list(map(int,input().strip().split())) - b = list(map(int,input().strip().split())) - li = mergeArrays(a,b,n,m) - for val in li: - print(val, end = ' ') - print() +""" +Problem Statement: +Union of Two Sorted Arrays + +Given two sorted arrays arr[] and brr[] of size N and M respectively. The task is to find the union of these two arrays. +Union of two arrays can be defined as the common and distinct elements in the two arrays. + +Example 1: + +Input: +N = 5, arr1[] = {1, 2, 3, 4, 5} +M = 3, arr2 [] = {1, 2, 3} +Output: 1 2 3 4 5 +Explanation: Distinct elements including +both the arrays are: 1 2 3 4 5. + +Example 2: + +Input: +N = 5, arr1[] = {2, 2, 3, 4, 5} +M = 5, arr2[] = {1, 1, 2, 3, 4} +Output: 1 2 3 4 5 +Explanation: Distinct elements including +both the arrays are: 1 2 3 4 5. + +Example 3: + +Input: +N = 5, arr1[] = {1, 1, 1, 1, 1} +M = 5, arr2[] = {2, 2, 2, 2, 2} +Output: 1 2 +Explanation: Distinct elements including +both the arrays are: 1 2. + + +Your Task: This is a function problem. You only need to complete the function findUnion() that takes two arrays arr1[], arr2[], and their size N and M as parameters and returns the union of two arrays. The new line is automatically appended by the driver code. + +Expected Time Complexity: O(N+M). +Expected Auxiliary Space: O(N+M). + +Constraints: +1 <= N, M <= 105 +1 <= arr[i], brr[i] <= 106 +""" +def mergeArrays(a,b,n,m): + ''' + :param a: given sorted array a + :param n: size of sorted array a + :param b: given sorted array b + :param m: size of sorted array b + :return: The union of both arrays as a list + ''' + # code here + union_array = a+b + sorted_union_array = list(set(union_array)) + return sorted(sorted_union_array) + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +# Contributed by : Nagendra Jha +# Modified by : Sagar Gupta + + +if __name__ == '__main__': + test_cases = int(input()) + for cases in range(test_cases) : + n,m = map(int,input().strip().split()) + a = list(map(int,input().strip().split())) + b = list(map(int,input().strip().split())) + li = mergeArrays(a,b,n,m) + for val in li: + print(val, end = ' ') + print() # } Driver Code Ends \ No newline at end of file diff --git a/Codeforce/RandomSolves/diff_le800/puzzle_from_future.py b/Codeforce/RandomSolves/diff_le800/puzzle_from_future.py index 99e1633..f412dab 100644 --- a/Codeforce/RandomSolves/diff_le800/puzzle_from_future.py +++ b/Codeforce/RandomSolves/diff_le800/puzzle_from_future.py @@ -1,3 +1,3 @@ -# tags: greedy -# link: https://codeforces.com/problemset/problem/1474/A - +# tags: greedy +# link: https://codeforces.com/problemset/problem/1474/A + diff --git a/Graph/min_swaps.py b/Graph/min_swaps.py index 2a3950a..563c4c0 100644 --- a/Graph/min_swaps.py +++ b/Graph/min_swaps.py @@ -1,90 +1,90 @@ -""" -Given an array of integers. Find the minimum number of swaps required to sort the array in non-decreasing order. - -Input: -The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the no of element of the array A[ ]. In the next line are N space separated values of the array A[ ] . - -Output: -For each test case in a new line output will be an integer denoting minimum umber of swaps that are required to sort the array. - -Constraints: -1 <= T <= 100 -1 <= N <= 105 -1 <= A[] <= 106 - -User Task: -You don't need to read input or print anything. Your task is to complete the function minSwaps() which takes the array arr[] and its size N as inputs and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0. - -Expected Time Complexity: O(NlogN). -Expected Auxiliary Space: O(N). - -Example(To be used only for expected output): -Input: -2 -5 -1 5 4 3 2 -4 -8 9 16 15 - -Output: -2 -1 - -Explanation: -Test Case 1: We need two swaps, swap 2 with 5 and 3 with 4 to make it sorted. -""" - - -# return the minimum number of swaps required to sort the arra -def minSwaps(arr, N): - # Code here - value_to_pos = dict() - #pos_to_value = dict() - - for pos, val in enumerate(sorted(arr)): #O(n log n) - value_to_pos[val] = pos - #pos_to_value[pos] = val - #print(value_to_pos) - #print(pos_to_value) - - visited = [False for _ in range(len(arr))] - counts = 0 - for i in range(len(arr)): - if not visited[i]: - visited[i] = True - - if arr[i] == value_to_pos.get(arr[i]): - continue - else: - tmp = value_to_pos.get(arr[i]) - while not visited[tmp]: - visited[tmp] = True - tmp = value_to_pos.get(arr[tmp]) - counts += 1 - - return counts - -# solution contributed by: Sebastian Widmann - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -import atexit -import io -import sys - -# _INPUT_LINES = sys.stdin.read().splitlines() -# input = iter(_INPUT_LINES).__next__ -# _OUTPUT_BUFFER = io.StringIO() -# sys.stdout = _OUTPUT_BUFFER - - -if __name__=='__main__': - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().strip().split())) - print(minSwaps(arr, n)) - +""" +Given an array of integers. Find the minimum number of swaps required to sort the array in non-decreasing order. + +Input: +The first line of input contains an integer T denoting the no of test cases. Then T test cases follow. Each test case contains an integer N denoting the no of element of the array A[ ]. In the next line are N space separated values of the array A[ ] . + +Output: +For each test case in a new line output will be an integer denoting minimum umber of swaps that are required to sort the array. + +Constraints: +1 <= T <= 100 +1 <= N <= 105 +1 <= A[] <= 106 + +User Task: +You don't need to read input or print anything. Your task is to complete the function minSwaps() which takes the array arr[] and its size N as inputs and returns an integer denoting the minimum number of swaps required to sort the array. If the array is already sorted, return 0. + +Expected Time Complexity: O(NlogN). +Expected Auxiliary Space: O(N). + +Example(To be used only for expected output): +Input: +2 +5 +1 5 4 3 2 +4 +8 9 16 15 + +Output: +2 +1 + +Explanation: +Test Case 1: We need two swaps, swap 2 with 5 and 3 with 4 to make it sorted. +""" + + +# return the minimum number of swaps required to sort the arra +def minSwaps(arr, N): + # Code here + value_to_pos = dict() + #pos_to_value = dict() + + for pos, val in enumerate(sorted(arr)): #O(n log n) + value_to_pos[val] = pos + #pos_to_value[pos] = val + #print(value_to_pos) + #print(pos_to_value) + + visited = [False for _ in range(len(arr))] + counts = 0 + for i in range(len(arr)): + if not visited[i]: + visited[i] = True + + if arr[i] == value_to_pos.get(arr[i]): + continue + else: + tmp = value_to_pos.get(arr[i]) + while not visited[tmp]: + visited[tmp] = True + tmp = value_to_pos.get(arr[tmp]) + counts += 1 + + return counts + +# solution contributed by: Sebastian Widmann + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +import atexit +import io +import sys + +# _INPUT_LINES = sys.stdin.read().splitlines() +# input = iter(_INPUT_LINES).__next__ +# _OUTPUT_BUFFER = io.StringIO() +# sys.stdout = _OUTPUT_BUFFER + + +if __name__=='__main__': + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().strip().split())) + print(minSwaps(arr, n)) + # } Driver Code Ends \ No newline at end of file diff --git a/HackerEarth/pile_of_coins.py b/HackerEarth/pile_of_coins.py index 98790a4..ffab048 100644 --- a/HackerEarth/pile_of_coins.py +++ b/HackerEarth/pile_of_coins.py @@ -1,19 +1,19 @@ -""" -Problem link: https://www.hackerearth.com/problem/algorithm/maximum-profit-5-c3c2ce7c/ -HackerEarth january easy 21 -""" - -# Write your code here -t = int(input()) # test cases - -while t: - n, k = list(map(int, input().split())) - coins = list(set(map(int, input().split()))) - coins_sorted = sorted(coins) - max_sum = 0 - for i in range(len(coins_sorted)-1,-1,-1): - if k: - max_sum += coins_sorted[i] - k -= 1 - print(max_sum) +""" +Problem link: https://www.hackerearth.com/problem/algorithm/maximum-profit-5-c3c2ce7c/ +HackerEarth january easy 21 +""" + +# Write your code here +t = int(input()) # test cases + +while t: + n, k = list(map(int, input().split())) + coins = list(set(map(int, input().split()))) + coins_sorted = sorted(coins) + max_sum = 0 + for i in range(len(coins_sorted)-1,-1,-1): + if k: + max_sum += coins_sorted[i] + k -= 1 + print(max_sum) t -= 1 \ No newline at end of file diff --git a/Matrix/boundary_traversal.py b/Matrix/boundary_traversal.py index f39736e..278d54d 100644 --- a/Matrix/boundary_traversal.py +++ b/Matrix/boundary_traversal.py @@ -1,125 +1,125 @@ -""" -You are given a matrix A of dimensions n1 x m1. The task is to perform boundary traversal on the matrix in clockwise manner. - -Input: -The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1. The second line contains n1*m1 elements separated by spaces. - -Output: -For each testcase, in a new line, print the boundary traversal of the matrix A. - -Your Task: -This is a function problem. You only need to complete the function boundaryTraversal() that takes n1, m1 and matrix as parameters and prints the boundary traversal. The newline is added automatically by the driver code. - -Expected Time Complexity: O(N1 + M1) -Expected Auxiliary Space: O(1) - -Constraints: -1 <= T <= 100 -1 <= n1, m1<= 100 -0 <= arri <= 1000 - -Examples: -Input: -4 -4 4 -1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 -3 4 -12 11 10 9 8 7 6 5 4 3 2 1 -1 4 -1 2 3 4 -4 1 -1 2 3 4 -Output: -1 2 3 4 8 12 16 15 14 13 9 5 -12 11 10 9 5 1 2 3 4 8 -1 2 3 4 -1 2 3 4 - -Explanation: -Testcase1: The matrix is: -1 2 3 4 -5 6 7 8 -9 10 11 12 -13 14 15 16 -The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5 -Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8. -Testcase 3: Boundary Traversal will be 1 2 3 4. -Testcase 4: Boundary Traversal will be 1 2 3 4. -''' - Your task is to print boundary traversal - of a given matrix. - - Function Arguments : a(given array), n (no of rows), m (no of columns). - Return Type: none, you have to print the result. -''' - -""" - - -def BoundaryTraversal(a, n, m): - pattern = [ - min(0, n - 1), # i min - max(0, m - 1), # j max - max(0, n - 1), # i max - min(0, m - 1) # j min - ] - ind = 0 - completed = [] - while ind < len(pattern): - if ind == 0: - for i in range(m): - x = pattern[ind] - y = i - print(a[x][y], end=" ") - completed.append([x, y]) - elif ind == 1: - for i in range(1, n): - x = i - y = pattern[ind] - if [x, y] not in completed: - print(a[x][y], end=" ") - completed.append([x, y]) - elif ind == 2: - for i in range(m - 2, -1, -1): - x = pattern[ind] - y = i - if [x, y] not in completed: - print(a[x][y], end=" ") - completed.append([x, y]) - else: - for i in range(n - 2, 0, -1): - x = i - y = pattern[ind] - if [x, y] not in completed: - print(a[x][y], end=" ") - completed.append([x, y]) - ind += 1 - - -# { -# Driver Code Starts -# Initial Template for Python 3 -# Contributed by : Nagendra Jha - -# import atexit -# import io -# import sys - - -if __name__ == '__main__': - t = int(input()) - for cases in range(t): - n, m = map(int, input().strip().split()) - values = list(map(int, input().strip().split())) - k = 0 - a = [] - for i in range(n): - row = [] - for j in range(m): - row.append(values[k]) - k += 1 - a.append(row) - BoundaryTraversal(a, n, m) - print() - -# } Driver Code Ends +""" +You are given a matrix A of dimensions n1 x m1. The task is to perform boundary traversal on the matrix in clockwise manner. + +Input: +The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase two lines of input. The first line contains dimensions of the matrix A, n1 and m1. The second line contains n1*m1 elements separated by spaces. + +Output: +For each testcase, in a new line, print the boundary traversal of the matrix A. + +Your Task: +This is a function problem. You only need to complete the function boundaryTraversal() that takes n1, m1 and matrix as parameters and prints the boundary traversal. The newline is added automatically by the driver code. + +Expected Time Complexity: O(N1 + M1) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= T <= 100 +1 <= n1, m1<= 100 +0 <= arri <= 1000 + +Examples: +Input: +4 +4 4 +1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 +3 4 +12 11 10 9 8 7 6 5 4 3 2 1 +1 4 +1 2 3 4 +4 1 +1 2 3 4 +Output: +1 2 3 4 8 12 16 15 14 13 9 5 +12 11 10 9 5 1 2 3 4 8 +1 2 3 4 +1 2 3 4 + +Explanation: +Testcase1: The matrix is: +1 2 3 4 +5 6 7 8 +9 10 11 12 +13 14 15 16 +The boundary traversal is 1 2 3 4 8 12 16 15 14 13 9 5 +Testcase 2: Boundary Traversal will be 12 11 10 9 5 1 2 3 4 8. +Testcase 3: Boundary Traversal will be 1 2 3 4. +Testcase 4: Boundary Traversal will be 1 2 3 4. +''' + Your task is to print boundary traversal + of a given matrix. + + Function Arguments : a(given array), n (no of rows), m (no of columns). + Return Type: none, you have to print the result. +''' + +""" + + +def BoundaryTraversal(a, n, m): + pattern = [ + min(0, n - 1), # i min + max(0, m - 1), # j max + max(0, n - 1), # i max + min(0, m - 1) # j min + ] + ind = 0 + completed = [] + while ind < len(pattern): + if ind == 0: + for i in range(m): + x = pattern[ind] + y = i + print(a[x][y], end=" ") + completed.append([x, y]) + elif ind == 1: + for i in range(1, n): + x = i + y = pattern[ind] + if [x, y] not in completed: + print(a[x][y], end=" ") + completed.append([x, y]) + elif ind == 2: + for i in range(m - 2, -1, -1): + x = pattern[ind] + y = i + if [x, y] not in completed: + print(a[x][y], end=" ") + completed.append([x, y]) + else: + for i in range(n - 2, 0, -1): + x = i + y = pattern[ind] + if [x, y] not in completed: + print(a[x][y], end=" ") + completed.append([x, y]) + ind += 1 + + +# { +# Driver Code Starts +# Initial Template for Python 3 +# Contributed by : Nagendra Jha + +# import atexit +# import io +# import sys + + +if __name__ == '__main__': + t = int(input()) + for cases in range(t): + n, m = map(int, input().strip().split()) + values = list(map(int, input().strip().split())) + k = 0 + a = [] + for i in range(n): + row = [] + for j in range(m): + row.append(values[k]) + k += 1 + a.append(row) + BoundaryTraversal(a, n, m) + print() + +# } Driver Code Ends diff --git a/Matrix/find_nth_spiral_element.py b/Matrix/find_nth_spiral_element.py index 25447c3..e1a6058 100644 --- a/Matrix/find_nth_spiral_element.py +++ b/Matrix/find_nth_spiral_element.py @@ -1,104 +1,104 @@ -""" -Find nth element of spiral matrix - -Given a matrix your task is to find the kth element which is obtained while traversing the matrix spirally. You need to complete the method findK which takes four arguments the first argument is the matrix A and the next two arguments will be n and m denoting the size of the matrix A and then the forth argument is an integer k denoting the kth element . The function will return the kth element obtained while traversing the matrix spirally. - - -Input: -The first line of input is the no of test cases then T test cases follow . The first line of each test case has three integers n(rows), m(columns) and k . Then in the next line are n*m space separated values of the matrix A [ ] [ ] . - -Output: -The output for each test case will be the kth obtained element . - -Your Task: -You only need to implement the given function findK(). Do not read input, instead use the arguments given in the function. Return the K'th element obtained by traversing matrix spirally. - -Expected Time Complexity: O(N*M) -Expected Auxiliary Space: O(N*M) - - - -Constraints: -1<=T<=100 -1<=n,m<=20 -1<=k<=n*m - -Example: -Input -1 -3 3 4 -1 2 3 4 5 6 7 8 9 - -Output -6 - -Explanation -The matrix above will look like -1 2 3 -4 5 6 -7 8 9 -and the 4th element in spiral fashion will be 6 . - -Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. -""" - - -# Function should return the an integer -def findK(arr, m, n, q): - # Code here - elements = m * n - top, down, left, right = 0, m - 1, 0, n - 1 - count = 0 - direction = 0 - - while count < elements: - if direction == 0: - for i in range(left, right + 1): - # print(arr[top][i], end=" ") - count += 1 - if count == q: - return arr[top][i] - top += 1 - direction = 1 - elif direction == 1: - for i in range(top, down + 1): - # print(arr[i][right], end=" ") - count += 1 - if count == q: - return arr[i][right] - direction = 2 - right -= 1 - elif direction == 2: - for i in range(right, left - 1, -1): - # print(arr[down][i], end=" ") - count += 1 - if count == q: - return arr[down][i] - direction = 3 - down -= 1 - elif direction == 3: - for i in range(down, top - 1, -1): - # print(arr[i][left], end=" ") - count += 1 - if count == q: - return arr[i][left] - left += 1 - direction = 0 - - -# { -# Driver Code Starts -# Your code goes here -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = list(map(int, input().strip().split())) - arr = list(map(int, input().strip().split())) - matrix = [[0 for i in range(n[1])] for j in range(n[0])] - c = 0 - for i in range(n[0]): - for j in range(n[1]): - matrix[i][j] = arr[c] - c += 1 - print(findK(matrix, n[0], n[1], n[2])) -# } Driver Code Ends +""" +Find nth element of spiral matrix + +Given a matrix your task is to find the kth element which is obtained while traversing the matrix spirally. You need to complete the method findK which takes four arguments the first argument is the matrix A and the next two arguments will be n and m denoting the size of the matrix A and then the forth argument is an integer k denoting the kth element . The function will return the kth element obtained while traversing the matrix spirally. + + +Input: +The first line of input is the no of test cases then T test cases follow . The first line of each test case has three integers n(rows), m(columns) and k . Then in the next line are n*m space separated values of the matrix A [ ] [ ] . + +Output: +The output for each test case will be the kth obtained element . + +Your Task: +You only need to implement the given function findK(). Do not read input, instead use the arguments given in the function. Return the K'th element obtained by traversing matrix spirally. + +Expected Time Complexity: O(N*M) +Expected Auxiliary Space: O(N*M) + + + +Constraints: +1<=T<=100 +1<=n,m<=20 +1<=k<=n*m + +Example: +Input +1 +3 3 4 +1 2 3 4 5 6 7 8 9 + +Output +6 + +Explanation +The matrix above will look like +1 2 3 +4 5 6 +7 8 9 +and the 4th element in spiral fashion will be 6 . + +Note:The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. +""" + + +# Function should return the an integer +def findK(arr, m, n, q): + # Code here + elements = m * n + top, down, left, right = 0, m - 1, 0, n - 1 + count = 0 + direction = 0 + + while count < elements: + if direction == 0: + for i in range(left, right + 1): + # print(arr[top][i], end=" ") + count += 1 + if count == q: + return arr[top][i] + top += 1 + direction = 1 + elif direction == 1: + for i in range(top, down + 1): + # print(arr[i][right], end=" ") + count += 1 + if count == q: + return arr[i][right] + direction = 2 + right -= 1 + elif direction == 2: + for i in range(right, left - 1, -1): + # print(arr[down][i], end=" ") + count += 1 + if count == q: + return arr[down][i] + direction = 3 + down -= 1 + elif direction == 3: + for i in range(down, top - 1, -1): + # print(arr[i][left], end=" ") + count += 1 + if count == q: + return arr[i][left] + left += 1 + direction = 0 + + +# { +# Driver Code Starts +# Your code goes here +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = list(map(int, input().strip().split())) + arr = list(map(int, input().strip().split())) + matrix = [[0 for i in range(n[1])] for j in range(n[0])] + c = 0 + for i in range(n[0]): + for j in range(n[1]): + matrix[i][j] = arr[c] + c += 1 + print(findK(matrix, n[0], n[1], n[2])) +# } Driver Code Ends diff --git a/Matrix/rotate_matrix_by_90.py b/Matrix/rotate_matrix_by_90.py index 198ef49..00b0d95 100644 --- a/Matrix/rotate_matrix_by_90.py +++ b/Matrix/rotate_matrix_by_90.py @@ -1,74 +1,74 @@ -"""Given a square matrix[][] of size N x N. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space. - -Input: -The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case consists of an integer N, where N is the size of the square matrix. The second line of each test case contains N x N space-separated values of the matrix. - -Output: -Corresponding to each test case, in a new line, print the rotated array. - -Your Task: -You only need to implement the given function rotate(). Do not read input, instead use the arguments given in the function. - -Expected Time Complexity: O(N*N) -Expected Auxiliary Space: O(1) - -Constraints: -1 ≤ T ≤ 50 -1 ≤ N ≤ 50 -1 <= matrix[][] <= 100 - -Example: -Input: -1 -3 -1 2 3 4 5 6 7 8 9 -Output: -3 6 9 -2 5 8 -1 4 7 - - """ - - -def rotate(matrix): - # code here - arr = [] - for i in matrix: - arr.extend(i) - n = len(matrix) - j = n - 1 - x = 0 - y = 0 - while j >= 0: - k = j - while k < len(arr): - matrix[x][y] = arr[k] - k = k + n - y += 1 - j = j - 1 - x += 1 - y = 0 - - -# { -# Driver Code Starts -# Initial Template for Python 3 - - -if __name__ == '__main__': - t = int(input()) - for _ in range(t): - N = int(input()) - arr = [int(x) for x in input().split()] - matrix = [] - - for i in range(0, N * N, N): - matrix.append(arr[i:i + N]) - - rotate(matrix) - for i in range(N): - for j in range(N): - print(matrix[i][j], end=' ') - print() - -# } Driver Code Ends +"""Given a square matrix[][] of size N x N. The task is to rotate it by 90 degrees in an anti-clockwise direction without using any extra space. + +Input: +The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consists of two lines. The first line of each test case consists of an integer N, where N is the size of the square matrix. The second line of each test case contains N x N space-separated values of the matrix. + +Output: +Corresponding to each test case, in a new line, print the rotated array. + +Your Task: +You only need to implement the given function rotate(). Do not read input, instead use the arguments given in the function. + +Expected Time Complexity: O(N*N) +Expected Auxiliary Space: O(1) + +Constraints: +1 ≤ T ≤ 50 +1 ≤ N ≤ 50 +1 <= matrix[][] <= 100 + +Example: +Input: +1 +3 +1 2 3 4 5 6 7 8 9 +Output: +3 6 9 +2 5 8 +1 4 7 + + """ + + +def rotate(matrix): + # code here + arr = [] + for i in matrix: + arr.extend(i) + n = len(matrix) + j = n - 1 + x = 0 + y = 0 + while j >= 0: + k = j + while k < len(arr): + matrix[x][y] = arr[k] + k = k + n + y += 1 + j = j - 1 + x += 1 + y = 0 + + +# { +# Driver Code Starts +# Initial Template for Python 3 + + +if __name__ == '__main__': + t = int(input()) + for _ in range(t): + N = int(input()) + arr = [int(x) for x in input().split()] + matrix = [] + + for i in range(0, N * N, N): + matrix.append(arr[i:i + N]) + + rotate(matrix) + for i in range(N): + for j in range(N): + print(matrix[i][j], end=' ') + print() + +# } Driver Code Ends diff --git a/Matrix/search_sorted_2d_matrix.py b/Matrix/search_sorted_2d_matrix.py index b6338a4..269290d 100644 --- a/Matrix/search_sorted_2d_matrix.py +++ b/Matrix/search_sorted_2d_matrix.py @@ -1,76 +1,76 @@ -""" -Search in a row-column sorted Matrix - -Given a matrix mat[] of size n x m, where every row and column is sorted in increasing order, and a number x is given. The task is to find whether element x is present in the matrix or not. - -Input: -The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consists of three lines. First line of each test case consist of two space separated integers N and M, denoting the number of element in a row and column respectively. Second line of each test case consists of N*M space separated integers denoting the elements in the matrix in row major order. Third line of each test case contains a single integer x, the element to be searched. - -Output: -Corresponding to each test case, print in a new line, 1 if the element x is present in the matrix, otherwise simply print 0. - -Your Task: -This is a function problem. You only need to complete the function search that takes n,m, and x as parameters and returns either 0 or 1. - -Expected Time Complexity: O(N + M) -Expected Auxiliary Space: O(1) - -Constraints: -1 <= T <= 200 -1 <= N, M <= 1000 -1 <= mat[][] <= 105 -1 <= X <= 1000 - -Example: -Input: -2 -3 3 -3 30 38 44 52 54 57 60 69 -62 -1 6 -18 21 27 38 55 67 -55 -Output: -0 -1 - -Explanation: -Testcase 1: 62 is not present in the matrix, so output is 0. -Testcase 2: 55 is present in the matrix at 5th cell. -""" - -def search(n1, m1, mat, x): - i, j = 0, m1 - 1 - while True: - if 0 <= i < n1 and 0 <= j < m1: - elem = mat[i][j] - if elem == x: - return 1 - elif elem < x: - i += 1 - elif elem > x: - j -= 1 - else: - break - return 0 - - -def main(): - T = int(input()) - while T > 0: - n, m = map(int, input().split()) - mat = [[0 for j in range(m)] for i in range(n)] - line_1 = [int(x) for x in input().strip().split()] - x = int(input()) - - k = 0 - for i in range(n): - for j in range(m): - mat[i][j] = line_1[k] - k += 1 - print(search(n, m, mat, x)) - T -= 1 - - -if __name__ == '__main__': - main() +""" +Search in a row-column sorted Matrix + +Given a matrix mat[] of size n x m, where every row and column is sorted in increasing order, and a number x is given. The task is to find whether element x is present in the matrix or not. + +Input: +The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. Each test case consists of three lines. First line of each test case consist of two space separated integers N and M, denoting the number of element in a row and column respectively. Second line of each test case consists of N*M space separated integers denoting the elements in the matrix in row major order. Third line of each test case contains a single integer x, the element to be searched. + +Output: +Corresponding to each test case, print in a new line, 1 if the element x is present in the matrix, otherwise simply print 0. + +Your Task: +This is a function problem. You only need to complete the function search that takes n,m, and x as parameters and returns either 0 or 1. + +Expected Time Complexity: O(N + M) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= T <= 200 +1 <= N, M <= 1000 +1 <= mat[][] <= 105 +1 <= X <= 1000 + +Example: +Input: +2 +3 3 +3 30 38 44 52 54 57 60 69 +62 +1 6 +18 21 27 38 55 67 +55 +Output: +0 +1 + +Explanation: +Testcase 1: 62 is not present in the matrix, so output is 0. +Testcase 2: 55 is present in the matrix at 5th cell. +""" + +def search(n1, m1, mat, x): + i, j = 0, m1 - 1 + while True: + if 0 <= i < n1 and 0 <= j < m1: + elem = mat[i][j] + if elem == x: + return 1 + elif elem < x: + i += 1 + elif elem > x: + j -= 1 + else: + break + return 0 + + +def main(): + T = int(input()) + while T > 0: + n, m = map(int, input().split()) + mat = [[0 for j in range(m)] for i in range(n)] + line_1 = [int(x) for x in input().strip().split()] + x = int(input()) + + k = 0 + for i in range(n): + for j in range(m): + mat[i][j] = line_1[k] + k += 1 + print(search(n, m, mat, x)) + T -= 1 + + +if __name__ == '__main__': + main() diff --git a/Matrix/spiral_matrix_traversal.py b/Matrix/spiral_matrix_traversal.py index 323baf3..9056499 100644 --- a/Matrix/spiral_matrix_traversal.py +++ b/Matrix/spiral_matrix_traversal.py @@ -1,106 +1,106 @@ -"""Spirally traversing a matrix -Given a matrix mat[][] of size M*N. Traverse and print the matrix in spiral form. - -Input: -The first line of the input contains a single integer T, denoting the number of test cases. Then T test cases follow. Each testcase has 2 lines. First line contains M and N respectively separated by a space. Second line contains M*N values separated by spaces. - -Output: -Elements when traveled in Spiral form, will be displayed in a single line. - -Your Task: -This is a function problem. You only need to complete the function spirallyTraverse that takes m, n, and matrix as parameters and prints the spiral traversal. The driver code automatically appends a new line. - -Expected Time Complexity: O(N*M) -Expected Auxiliary Space: O(1) - -Constraints: -1 <= T <= 100 -2 <= M, N <= 100 -0 <= Ai <= 100 - -Example: -Input: -2 -4 4 -1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 -3 4 -1 2 3 4 5 6 7 8 9 10 11 12 -Output: -1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 -1 2 3 4 8 12 11 10 9 5 6 7 - -Explanation: -Testcase 1: - - -Testcase 2: Applying same technique as shown above , output for the 2nd testcase will be 1 2 3 4 8 12 11 10 9 5 6 7.""" - -# Complete this function -# a is the matrix -# m is rows -# n is cols -def spirallyTraverse(m, n, a): - # Your code here - elements = m * n - top, down, left, right = 0, m - 1, 0, n - 1 - count = 0 - direction = 0 - - while count < elements: - if direction == 0: - for i in range(left, right + 1): - print(a[top][i], end=" ") - count += 1 - top += 1 - direction = 1 - elif direction == 1: - for i in range(top, down + 1): - print(a[i][right], end=" ") - count += 1 - direction = 2 - right -= 1 - elif direction == 2: - for i in range(right, left - 1, -1): - print(a[down][i], end=" ") - count += 1 - direction = 3 - down -= 1 - elif direction == 3: - for i in range(down, top - 1, -1): - print(a[i][left], end=" ") - count += 1 - left += 1 - direction = 0 - - -# { -# Driver Code Starts -# Initial Template for Python 3 - -def main(): - T = int(input()) - while (T > 0): - n, m = map(int, input().split()) - mat = [[0 for j in range(m)] for i in range(n)] - line1 = [int(x) for x in input().strip().split()] - - k = 0 - for i in range(n): - for j in range(m): - mat[i][j] = line1[k] - k += 1 - - k = 0 - - n, m = m, n - - spirallyTraverse(m, n, mat) - - print() - - T -= 1 - - -if __name__ == "__main__": - main() -# } Driver Code Ends +"""Spirally traversing a matrix +Given a matrix mat[][] of size M*N. Traverse and print the matrix in spiral form. + +Input: +The first line of the input contains a single integer T, denoting the number of test cases. Then T test cases follow. Each testcase has 2 lines. First line contains M and N respectively separated by a space. Second line contains M*N values separated by spaces. + +Output: +Elements when traveled in Spiral form, will be displayed in a single line. + +Your Task: +This is a function problem. You only need to complete the function spirallyTraverse that takes m, n, and matrix as parameters and prints the spiral traversal. The driver code automatically appends a new line. + +Expected Time Complexity: O(N*M) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= T <= 100 +2 <= M, N <= 100 +0 <= Ai <= 100 + +Example: +Input: +2 +4 4 +1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 +3 4 +1 2 3 4 5 6 7 8 9 10 11 12 +Output: +1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10 +1 2 3 4 8 12 11 10 9 5 6 7 + +Explanation: +Testcase 1: + + +Testcase 2: Applying same technique as shown above , output for the 2nd testcase will be 1 2 3 4 8 12 11 10 9 5 6 7.""" + +# Complete this function +# a is the matrix +# m is rows +# n is cols +def spirallyTraverse(m, n, a): + # Your code here + elements = m * n + top, down, left, right = 0, m - 1, 0, n - 1 + count = 0 + direction = 0 + + while count < elements: + if direction == 0: + for i in range(left, right + 1): + print(a[top][i], end=" ") + count += 1 + top += 1 + direction = 1 + elif direction == 1: + for i in range(top, down + 1): + print(a[i][right], end=" ") + count += 1 + direction = 2 + right -= 1 + elif direction == 2: + for i in range(right, left - 1, -1): + print(a[down][i], end=" ") + count += 1 + direction = 3 + down -= 1 + elif direction == 3: + for i in range(down, top - 1, -1): + print(a[i][left], end=" ") + count += 1 + left += 1 + direction = 0 + + +# { +# Driver Code Starts +# Initial Template for Python 3 + +def main(): + T = int(input()) + while (T > 0): + n, m = map(int, input().split()) + mat = [[0 for j in range(m)] for i in range(n)] + line1 = [int(x) for x in input().strip().split()] + + k = 0 + for i in range(n): + for j in range(m): + mat[i][j] = line1[k] + k += 1 + + k = 0 + + n, m = m, n + + spirallyTraverse(m, n, mat) + + print() + + T -= 1 + + +if __name__ == "__main__": + main() +# } Driver Code Ends diff --git a/Matrix/unique_boolean_rows.py b/Matrix/unique_boolean_rows.py index 771671e..c0c5fd0 100644 --- a/Matrix/unique_boolean_rows.py +++ b/Matrix/unique_boolean_rows.py @@ -1,77 +1,77 @@ -""" -Unique rows in boolean matrix - -Given a binary matrix your task is to complete the function printMat which prints all unique rows of the given matrix. The function takes three arguments the first argument is a matrix M and the next two arguments are row and col denoting the rows and columns of the matrix. - -Input: -The first line of input is an integer T denoting the no of test cases. Then T test cases follow. Each test case consists of 2 lines. The first line of each test contains two integers row and col denoting the number of rows and columns of matrix. Then in the next line are row*col space separated values of the matrix M. - -Output: -The output will be the unique rows of the matrix separated by space. - -Note: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. - -Note : Dont print new line after each row instead print "$" without quotes. - -Your Task: -You only need to implement the given function printMat(). Do not read input, instead use the arguments given in the function. - -Expected Time Complexity: O(row * col) -Expected Auxiliary Space: O(row * col) - -Constraints: -1<=T<=20 -1<=row,col<=40 -0<=M[][]<=1 - -Example: -Input -1 -3 4 -1 1 0 1 1 0 0 1 1 1 0 1 - -Output -1 1 0 1 $1 0 0 1 $ - -Explanation -Above the matrix of size 3x4 looks like -1 1 0 1 -1 0 0 1 -1 1 0 1 -The two unique rows are 1 1 0 1 and 1 0 0 1 . -** For More Input/Output Examples Use 'Expected Output' option ** -""" - - -def printmat(row, col, matrix): - new_matrix = [] - new_matrix = [matrix[i:i + col] for i in range(0, len(matrix), col)] - # print(new_matrix) - unique = [] - for r in new_matrix: - if r not in unique: - unique.append(r) - print(' '.join(r), end=' $') - print() - - -# { -# Driver Code Starts -# Initial Template for Python 3 - -def main(): - testcase = int(input()) - while (testcase): - s = input().split() - row = int(s[0]) - col = int(s[1]) - matrix = input().split() - - printmat(row, col, matrix) - - testcase -= 1 - - -if __name__ == "__main__": - main() -# } Driver Code Ends +""" +Unique rows in boolean matrix + +Given a binary matrix your task is to complete the function printMat which prints all unique rows of the given matrix. The function takes three arguments the first argument is a matrix M and the next two arguments are row and col denoting the rows and columns of the matrix. + +Input: +The first line of input is an integer T denoting the no of test cases. Then T test cases follow. Each test case consists of 2 lines. The first line of each test contains two integers row and col denoting the number of rows and columns of matrix. Then in the next line are row*col space separated values of the matrix M. + +Output: +The output will be the unique rows of the matrix separated by space. + +Note: The Input/Ouput format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code. + +Note : Dont print new line after each row instead print "$" without quotes. + +Your Task: +You only need to implement the given function printMat(). Do not read input, instead use the arguments given in the function. + +Expected Time Complexity: O(row * col) +Expected Auxiliary Space: O(row * col) + +Constraints: +1<=T<=20 +1<=row,col<=40 +0<=M[][]<=1 + +Example: +Input +1 +3 4 +1 1 0 1 1 0 0 1 1 1 0 1 + +Output +1 1 0 1 $1 0 0 1 $ + +Explanation +Above the matrix of size 3x4 looks like +1 1 0 1 +1 0 0 1 +1 1 0 1 +The two unique rows are 1 1 0 1 and 1 0 0 1 . +** For More Input/Output Examples Use 'Expected Output' option ** +""" + + +def printmat(row, col, matrix): + new_matrix = [] + new_matrix = [matrix[i:i + col] for i in range(0, len(matrix), col)] + # print(new_matrix) + unique = [] + for r in new_matrix: + if r not in unique: + unique.append(r) + print(' '.join(r), end=' $') + print() + + +# { +# Driver Code Starts +# Initial Template for Python 3 + +def main(): + testcase = int(input()) + while (testcase): + s = input().split() + row = int(s[0]) + col = int(s[1]) + matrix = input().split() + + printmat(row, col, matrix) + + testcase -= 1 + + +if __name__ == "__main__": + main() +# } Driver Code Ends diff --git a/Must_do_coding_questions/Maths/missing_number.cpp b/Must_do_coding_questions/Maths/missing_number.cpp index 23a1c2f..877f9c2 100644 --- a/Must_do_coding_questions/Maths/missing_number.cpp +++ b/Must_do_coding_questions/Maths/missing_number.cpp @@ -1,41 +1,41 @@ -// { Driver Code Starts -// Initial template for C++ - -#include -#include -using namespace std; - -int MissingNumber(vector& array, int n); - -// Position this line where user code will be pasted. - -int main() { - int t; - cin >> t; - while (t--) { - int n; - cin >> n; - - vector array(n - 1); - for (int i = 0; i < n - 1; ++i) cin >> array[i]; - - cout << MissingNumber(array, n) << "\n"; - } - return 0; -}// } Driver Code Ends - - -// User function template for C++ - -int MissingNumber(vector& array, int n) { - // Your code goes here - sort(array.begin(), array.end()); - int i = 1; - for(i=1; i < n; i++){ - if(array[i-1] != i){ - return i; - } - - } - return i; +// { Driver Code Starts +// Initial template for C++ + +#include +#include +using namespace std; + +int MissingNumber(vector& array, int n); + +// Position this line where user code will be pasted. + +int main() { + int t; + cin >> t; + while (t--) { + int n; + cin >> n; + + vector array(n - 1); + for (int i = 0; i < n - 1; ++i) cin >> array[i]; + + cout << MissingNumber(array, n) << "\n"; + } + return 0; +}// } Driver Code Ends + + +// User function template for C++ + +int MissingNumber(vector& array, int n) { + // Your code goes here + sort(array.begin(), array.end()); + int i = 1; + for(i=1; i < n; i++){ + if(array[i-1] != i){ + return i; + } + + } + return i; } \ No newline at end of file diff --git a/Must_do_coding_questions/Maths/sort_names.cpp b/Must_do_coding_questions/Maths/sort_names.cpp index f2a047e..9dfb503 100644 --- a/Must_do_coding_questions/Maths/sort_names.cpp +++ b/Must_do_coding_questions/Maths/sort_names.cpp @@ -1,22 +1,22 @@ -#include -#include -#include -#include - -using namespace std; - -int main(){ - vector user_name; - - user_name = {"Tuhin", "John", "Doe", "Roger", "Fred", "Alen"}; - - sort(user_name.begin(), user_name.end()); - - cout << "Names in ascending order:\n"; - for(auto x:user_name){ - cout << x << endl; - } - - - return 0; +#include +#include +#include +#include + +using namespace std; + +int main(){ + vector user_name; + + user_name = {"Tuhin", "John", "Doe", "Roger", "Fred", "Alen"}; + + sort(user_name.begin(), user_name.end()); + + cout << "Names in ascending order:\n"; + for(auto x:user_name){ + cout << x << endl; + } + + + return 0; } \ No newline at end of file diff --git a/Must_do_coding_questions/Maths/trailing_zeros.cpp b/Must_do_coding_questions/Maths/trailing_zeros.cpp index a33f924..a01ba1a 100644 --- a/Must_do_coding_questions/Maths/trailing_zeros.cpp +++ b/Must_do_coding_questions/Maths/trailing_zeros.cpp @@ -1,54 +1,54 @@ -#include -using namespace std; - - // } Driver Code Ends - - -//User function Template for C++ -class Solution -{ -public: - int factorial(int n){ - int f = 1; - while(n > 1){ - cout << f << endl; - f = f*n; - n -= 1; - } - return f; - } - int trailingZeroes(int N) - { - int f = factorial(N); - cout << "factorial = " << f << endl; - int trail = 0; - while(f){ - if(f%10 == 0){ - trail += 1; - f = int(f / 10); - } - else{ - return trail; - break; - } - } - - return 0; - } -}; - -// { Driver Code Starts. -int main() -{ - int t; - cin >> t; - while (t--) - { - int N; - cin >> N; - Solution ob; - int ans = ob.trailingZeroes(N); - cout< +using namespace std; + + // } Driver Code Ends + + +//User function Template for C++ +class Solution +{ +public: + int factorial(int n){ + int f = 1; + while(n > 1){ + cout << f << endl; + f = f*n; + n -= 1; + } + return f; + } + int trailingZeroes(int N) + { + int f = factorial(N); + cout << "factorial = " << f << endl; + int trail = 0; + while(f){ + if(f%10 == 0){ + trail += 1; + f = int(f / 10); + } + else{ + return trail; + break; + } + } + + return 0; + } +}; + +// { Driver Code Starts. +int main() +{ + int t; + cin >> t; + while (t--) + { + int N; + cin >> N; + Solution ob; + int ans = ob.trailingZeroes(N); + cout<= previous_activity: - previous_activity = s[ind] - print(s[ind],f",start index=[{ind}]") - ind += 1 - - -s = [1, 3, 0, 5, 8, 5] -f = [2, 4, 6, 7, 9, 9] -print("Possible Tasks:") -main(s, f) +"""Statement:You are given n activities with their start and finish times. Select the maximum number of activities +that can be performed by a single person, assuming that a person can only work on a single activity at a time. + +References Used: + +1. For sorting two arrays based on one array +https://www.geeksforgeeks.org/sort-array-according-order-defined-another-array/ + +Problem statement: +2. https://www.geeksforgeeks.org/activity-selection-problem-greedy-algo-1/ +""" + + +def sort_with_ref(f, s): + map_f = {} + map_s = {} + for i in range(len(f)): + map_f[i] = f[i] + for i in range(len(s)): + map_s[i] = s[i] + sorted_f = [] + new_s = [] + for k, v in sorted(map_f.items(), key=lambda x: x[1]): + sorted_f.append(v) + new_s.append(map_s[k]) + return new_s, sorted_f + + +def main(s, f): + m, n = len(s), len(f) + if sorted(f) == f: + pass + else: + s, f = sort_with_ref(f, s) + + ind = 0 + print(s[ind], f",start index=[{ind}]") # first activity always selected + ind += 1 + previous_activity = f[ind - 1] + + while ind < m: + """If the start time of this activity is greater than or equal to the finish time of previously selected + activity then select this activity and print it. """ + + this_activity = s[ind] + if this_activity >= previous_activity: + previous_activity = s[ind] + print(s[ind],f",start index=[{ind}]") + ind += 1 + + +s = [1, 3, 0, 5, 8, 5] +f = [2, 4, 6, 7, 9, 9] +print("Possible Tasks:") +main(s, f) diff --git a/Others/bytelanc_coin_exchange.py b/Others/bytelanc_coin_exchange.py index e22d9f4..8ba7c79 100644 --- a/Others/bytelanc_coin_exchange.py +++ b/Others/bytelanc_coin_exchange.py @@ -1,49 +1,49 @@ -''' -problem statement: -In Byteland they have a very strange monetary system. Each Bytelandian gold -coin has an integer number written on it. A coin n can be exchanged in a bank -into three coins: n/2, n/3 and n/4. But these numbers are all rounded down -(the banks have to make a profit). -You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it? -Input The input will contain several test cases (not more -than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 -000. It is the number written on your coin. -Output For each test case output a -single line, containing the maximum amount of American dollars you can make. -Explanation -You can change 12 into 6, 4 and 3, and then change these into -$6+$4+$3 = $13. -If you try changing the coin 2 into 3 smaller coins, you will get -1, 0 and 0, and later you can get no more than $1 out of them. -It is better just to change the 2 coin directly into $2. -''' - -# Write your code here -def split(n): - a,b,c = n//2, n//3, n//4 - return a,b,c - -def process(n): - a,b,c = split(n) - value = a+b+c - if value >= n: - new_value = 0 - value_list = [a,b,c] - for i in range(len(value_list)): - x,y,z = split(value_list[i]) - if x+y+z >= value_list[i]: - new_value += x+y+z - if new_value > value: - value = process(new_value) - else: - return value - else: - return n - - -if __name__ == '__main__': - t = int(input()) - while t: - n = int(input()) - print(process(n)) +''' +problem statement: +In Byteland they have a very strange monetary system. Each Bytelandian gold +coin has an integer number written on it. A coin n can be exchanged in a bank +into three coins: n/2, n/3 and n/4. But these numbers are all rounded down +(the banks have to make a profit). +You can also sell Bytelandian coins for American dollars. The exchange rate is 1:1. But you can not buy Bytelandian coins. You have one gold coin. What is the maximum amount of American dollars you can get for it? +Input The input will contain several test cases (not more +than 10). Each testcase is a single line with a number n, 0 <= n <= 1 000 000 +000. It is the number written on your coin. +Output For each test case output a +single line, containing the maximum amount of American dollars you can make. +Explanation +You can change 12 into 6, 4 and 3, and then change these into +$6+$4+$3 = $13. +If you try changing the coin 2 into 3 smaller coins, you will get +1, 0 and 0, and later you can get no more than $1 out of them. +It is better just to change the 2 coin directly into $2. +''' + +# Write your code here +def split(n): + a,b,c = n//2, n//3, n//4 + return a,b,c + +def process(n): + a,b,c = split(n) + value = a+b+c + if value >= n: + new_value = 0 + value_list = [a,b,c] + for i in range(len(value_list)): + x,y,z = split(value_list[i]) + if x+y+z >= value_list[i]: + new_value += x+y+z + if new_value > value: + value = process(new_value) + else: + return value + else: + return n + + +if __name__ == '__main__': + t = int(input()) + while t: + n = int(input()) + print(process(n)) t -= 1 \ No newline at end of file diff --git a/Others/collatz_sequence.py b/Others/collatz_sequence.py index 9e4baf0..a389ec5 100644 --- a/Others/collatz_sequence.py +++ b/Others/collatz_sequence.py @@ -1,44 +1,44 @@ -""" -Write a function name collatz() that has one parameter named number. If number is -even, then collatz() should print number // 2 and return this value. - -If number is odd, the collatz() should print and return 3*number+1. -Then write a program that lets the user type in an integer and that keeps calling -collatz() on that number until the function returns the value 1. -(Amazingly enough, this sequence actually works for any integer-sooner or later, -using this sequence, you'll arrive at 1! Even mathematicians aren't sure why. Your -program is exploring what's called the collatz sequence, sometimes called "the -simplest impossible math problem.") - -Remember to convert the return value from input() to an integer with the int() -function; otherwise, it will be a string value. - -Hint: An integer number is even if number%2==0 and it's odd if number%2==1. -The output of this program could look something like this: ------------------------------------------------------------------ -Enter number: -3 -10 -5 -16 -8 -4 -2 -1 ------------------------------------------------------------------ -""" -def collatz(number): - if number % 2 == 0: # Even - print(number//2) - val = collatz(number//2) - return val - else: # odd - if number == 1: - return 1 - else: - print(3*number+1) - val = collatz(3*number+1) - return val - - -collatz(int(input("Enter a number:"))) +""" +Write a function name collatz() that has one parameter named number. If number is +even, then collatz() should print number // 2 and return this value. + +If number is odd, the collatz() should print and return 3*number+1. +Then write a program that lets the user type in an integer and that keeps calling +collatz() on that number until the function returns the value 1. +(Amazingly enough, this sequence actually works for any integer-sooner or later, +using this sequence, you'll arrive at 1! Even mathematicians aren't sure why. Your +program is exploring what's called the collatz sequence, sometimes called "the +simplest impossible math problem.") + +Remember to convert the return value from input() to an integer with the int() +function; otherwise, it will be a string value. + +Hint: An integer number is even if number%2==0 and it's odd if number%2==1. +The output of this program could look something like this: +----------------------------------------------------------------- +Enter number: +3 +10 +5 +16 +8 +4 +2 +1 +----------------------------------------------------------------- +""" +def collatz(number): + if number % 2 == 0: # Even + print(number//2) + val = collatz(number//2) + return val + else: # odd + if number == 1: + return 1 + else: + print(3*number+1) + val = collatz(3*number+1) + return val + + +collatz(int(input("Enter a number:"))) diff --git a/Others/list_operation_1.py b/Others/list_operation_1.py index 2e96587..b73521d 100644 --- a/Others/list_operation_1.py +++ b/Others/list_operation_1.py @@ -1,3 +1,3 @@ -a = [42] -b = [a[0]+42] + a + [a.pop() % 4] +a = [42] +b = [a[0]+42] + a + [a.pop() % 4] print(b) \ No newline at end of file diff --git a/Others/lovely_couple.py b/Others/lovely_couple.py index 0852bfe..5fc44c0 100644 --- a/Others/lovely_couple.py +++ b/Others/lovely_couple.py @@ -1,69 +1,69 @@ -''' -# Sample code to perform I/O: - -name = input() # Reading input from STDIN -print('Hi, %s.' % name) # Writing output to STDOUT - -# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail -''' - -# Write your code here -def compute_lcm(x, y): - - # choose the greater number - if x > y: - greater = x - else: - greater = y - - while(True): - if((greater % x == 0) and (greater % y == 0)): - lcm = greater - break - greater += 1 - - return lcm -def prime_factors(n): - i = 2 - factors = [] - while i * i <= n: - if n % i: - i += 1 - else: - n //= i - factors.append(i) - # factor_count += 1 - if n > 1: - factors.append(n) - # factor_count += 1 - return len(set(factors)) - - -def check_prime(num): - if num > 1: - flag = 0 - for i in range(2,num//2): - if num // i == 0: - flag = 1 - break - # return False - if flag == 0: - return True - else: - return False - else: - return False - - -t = int(input()) -while t: - a,b = tuple(map(int, input().split())) - lcm = compute_lcm(a,b) - print("LCM=",lcm) - count = prime_factors(lcm) - print(f"count of prime factors:",count) - if check_prime(count): - print('Yes') - else: - print('No') - t -= 1 +''' +# Sample code to perform I/O: + +name = input() # Reading input from STDIN +print('Hi, %s.' % name) # Writing output to STDOUT + +# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail +''' + +# Write your code here +def compute_lcm(x, y): + + # choose the greater number + if x > y: + greater = x + else: + greater = y + + while(True): + if((greater % x == 0) and (greater % y == 0)): + lcm = greater + break + greater += 1 + + return lcm +def prime_factors(n): + i = 2 + factors = [] + while i * i <= n: + if n % i: + i += 1 + else: + n //= i + factors.append(i) + # factor_count += 1 + if n > 1: + factors.append(n) + # factor_count += 1 + return len(set(factors)) + + +def check_prime(num): + if num > 1: + flag = 0 + for i in range(2,num//2): + if num // i == 0: + flag = 1 + break + # return False + if flag == 0: + return True + else: + return False + else: + return False + + +t = int(input()) +while t: + a,b = tuple(map(int, input().split())) + lcm = compute_lcm(a,b) + print("LCM=",lcm) + count = prime_factors(lcm) + print(f"count of prime factors:",count) + if check_prime(count): + print('Yes') + else: + print('No') + t -= 1 diff --git a/Others/magazine_hash.py b/Others/magazine_hash.py index f11c6fc..09498fd 100644 --- a/Others/magazine_hash.py +++ b/Others/magazine_hash.py @@ -1,35 +1,35 @@ -#!/bin/python3 - -import math -import os -import random -import re -import sys - - -# Complete the checkMagazine function below. -def checkMagazine(magazine, note): - checked = set() - note_hash = {w: note.count(w) for w in note} - for word, freq in note_hash.items(): - if word not in checked: - if magazine.count(word) >= freq: - checked.add(word) - else: - print("No") - return 0 - print("Yes") - - -if __name__ == '__main__': - mn = input().split() - - m = int(mn[0]) - - n = int(mn[1]) - - magazine = input().rstrip().split() - - note = input().rstrip().split() - - checkMagazine(magazine, note) +#!/bin/python3 + +import math +import os +import random +import re +import sys + + +# Complete the checkMagazine function below. +def checkMagazine(magazine, note): + checked = set() + note_hash = {w: note.count(w) for w in note} + for word, freq in note_hash.items(): + if word not in checked: + if magazine.count(word) >= freq: + checked.add(word) + else: + print("No") + return 0 + print("Yes") + + +if __name__ == '__main__': + mn = input().split() + + m = int(mn[0]) + + n = int(mn[1]) + + magazine = input().rstrip().split() + + note = input().rstrip().split() + + checkMagazine(magazine, note) diff --git a/Others/max_subarray_sum.py b/Others/max_subarray_sum.py index a93323f..31011cb 100644 --- a/Others/max_subarray_sum.py +++ b/Others/max_subarray_sum.py @@ -1,45 +1,45 @@ -""" -problem statement can be found here: -https://www.hackerrank.com/challenges/maximum-subarray-sum/problem? -""" -import math -import os -import random -import re -import sys -import bisect - - -# Complete the maximumSum function below. -def maximumSum(a, m): - mm, pr = 0, 0 - a1 = [] - for i in a: - pr = (pr + i) % m - mm = max(mm, pr) - ind = bisect.bisect_left(a1, pr + 1) - if ind < len(a1): - mm = max(mm, pr - a1[ind] + m) - bisect.insort(a1, pr) - return mm - - -if __name__ == '__main__': - fptr = open(os.environ['OUTPUT_PATH'], 'w') - - q = int(input()) - - for q_itr in range(q): - nm = input().split() - - n = int(nm[0]) - - m = int(nm[1]) - - a = list(map(int, input().rstrip().split())) - - result = maximumSum(a, m) - - fptr.write(str(result) + '\n') - - fptr.close() +""" +problem statement can be found here: +https://www.hackerrank.com/challenges/maximum-subarray-sum/problem? +""" +import math +import os +import random +import re +import sys +import bisect + + +# Complete the maximumSum function below. +def maximumSum(a, m): + mm, pr = 0, 0 + a1 = [] + for i in a: + pr = (pr + i) % m + mm = max(mm, pr) + ind = bisect.bisect_left(a1, pr + 1) + if ind < len(a1): + mm = max(mm, pr - a1[ind] + m) + bisect.insort(a1, pr) + return mm + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + q = int(input()) + + for q_itr in range(q): + nm = input().split() + + n = int(nm[0]) + + m = int(nm[1]) + + a = list(map(int, input().rstrip().split())) + + result = maximumSum(a, m) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/Others/problem_survivor.py b/Others/problem_survivor.py index 17ec0bf..e818b17 100644 --- a/Others/problem_survivor.py +++ b/Others/problem_survivor.py @@ -1,63 +1,63 @@ -""" -The Mad King arrested Shil's comrades for -participating in a rebellion against the King. Instead of punishing them - with death, the King decided to play the Game of survival with them. -The game is played as follows: - -All the N people are forced to stand in a line. -Now the king randomly chooses any two persons standing next to each other in line and kills the one having lower strength. -King keeps on performing step 2 until there are only 2 survivors. -The Last two survivors are forgiven for their crimes and are free to go. - -As Shil is worried for his comrades, he wants to find out the ones -who could survive - at least, one out of all the possible games. -Given N integers denoting the strengths of comrades, you must print the position of comrades who could survive at least one Game. -Input format: -The first Line of input consists of an integer N denoting the total number of comrades. The next line consists of N integers S1, S2 , ..... SN denoting the strength of comrades standing in a line. Si denotes the strength of ith comrade standing in a line. The strengths of all the comrades will be distinct. -Output format: -Print the positions of comrades standing in line who could be one of the - two possible survivors in any possible game. You must print the -positions in an increasingly sorted manner. -Constraints: -3 ≤ N ≤ 105 -1 ≤ Si ≤ 109 -""" -import logging - - -# logging.basicConfig(level=logging.INFO) -def survive(line, survivors, main_line): - logging.info('line=', line) - if len(line) <= 2: - logging.info(f"main line={main_line}") - for ij in line: - elem = main_line.index(ij) + 1 - logging.info(f"adding {elem}[{ij}] to survivors.") - survivors.add(elem) - return list(survivors) - else: - for i in range(len(line) - 1): - a = line[i] - b = line[i + 1] - if a > b: # kill b - new_line = line.copy() - del new_line[i + 1] - else: - new_line = line.copy() - del new_line[i] - logging.info('new_line=', new_line) - surv = survive(new_line, survivors, main_line) - logging.info(surv) - for x in surv: - survivors.add(x) - return list(survivors) - - -t = int(input()) -i = 0 -while i < t: - N = int(input()) - strength = list(map(int, input().split())) - result = survive(strength, set(), strength) - print(' '.join(list(map(str, result)))) - i += 1 +""" +The Mad King arrested Shil's comrades for +participating in a rebellion against the King. Instead of punishing them + with death, the King decided to play the Game of survival with them. +The game is played as follows: + +All the N people are forced to stand in a line. +Now the king randomly chooses any two persons standing next to each other in line and kills the one having lower strength. +King keeps on performing step 2 until there are only 2 survivors. +The Last two survivors are forgiven for their crimes and are free to go. + +As Shil is worried for his comrades, he wants to find out the ones +who could survive - at least, one out of all the possible games. +Given N integers denoting the strengths of comrades, you must print the position of comrades who could survive at least one Game. +Input format: +The first Line of input consists of an integer N denoting the total number of comrades. The next line consists of N integers S1, S2 , ..... SN denoting the strength of comrades standing in a line. Si denotes the strength of ith comrade standing in a line. The strengths of all the comrades will be distinct. +Output format: +Print the positions of comrades standing in line who could be one of the + two possible survivors in any possible game. You must print the +positions in an increasingly sorted manner. +Constraints: +3 ≤ N ≤ 105 +1 ≤ Si ≤ 109 +""" +import logging + + +# logging.basicConfig(level=logging.INFO) +def survive(line, survivors, main_line): + logging.info('line=', line) + if len(line) <= 2: + logging.info(f"main line={main_line}") + for ij in line: + elem = main_line.index(ij) + 1 + logging.info(f"adding {elem}[{ij}] to survivors.") + survivors.add(elem) + return list(survivors) + else: + for i in range(len(line) - 1): + a = line[i] + b = line[i + 1] + if a > b: # kill b + new_line = line.copy() + del new_line[i + 1] + else: + new_line = line.copy() + del new_line[i] + logging.info('new_line=', new_line) + surv = survive(new_line, survivors, main_line) + logging.info(surv) + for x in surv: + survivors.add(x) + return list(survivors) + + +t = int(input()) +i = 0 +while i < t: + N = int(input()) + strength = list(map(int, input().split())) + result = survive(strength, set(), strength) + print(' '.join(list(map(str, result)))) + i += 1 diff --git a/Others/sort_array_with_reference.py b/Others/sort_array_with_reference.py index 1d4d76d..14ab4a9 100644 --- a/Others/sort_array_with_reference.py +++ b/Others/sort_array_with_reference.py @@ -1,19 +1,19 @@ -s = [10, 12, 20] -f = [20, 19, 30] - -map_f = {} -map_s = {} -for i in range(len(f)): - map_f[i] = f[i] - -for i in range(len(s)): - map_s[i] = s[i] - -# print(map_f) -sorted_f = [] -new_s = [] -for k,v in sorted(map_f.items(), key=lambda x:x[1]): - sorted_f.append(v) - new_s.append(map_s[k]) - +s = [10, 12, 20] +f = [20, 19, 30] + +map_f = {} +map_s = {} +for i in range(len(f)): + map_f[i] = f[i] + +for i in range(len(s)): + map_s[i] = s[i] + +# print(map_f) +sorted_f = [] +new_s = [] +for k,v in sorted(map_f.items(), key=lambda x:x[1]): + sorted_f.append(v) + new_s.append(map_s[k]) + print(new_s,'\n',sorted_f) \ No newline at end of file diff --git a/Others/special_string_again.py b/Others/special_string_again.py index 3747f1e..095659d 100644 --- a/Others/special_string_again.py +++ b/Others/special_string_again.py @@ -1,55 +1,55 @@ -import math -import os -import random -import re -import sys - - -# Complete the substrCount function below. -def substrCount(n, s) -> int: - # --------------- approach 1 --------------- - - # substr = list(s) - # substring_count = n - # for i in range(2, n+1): - # for j in range(n): - # if (j + i) <= n: - # sub = s[j:j + i] - # if len(sub) % 2 == 0 and sub == sub[::-1]: - # substring_count += 1 - # substr.append(sub) - # elif len(sub) % 2 == 1 and sub[:len(sub)//2] == sub[len(sub)//2+1:]: - # substring_count += 1 - # substr.append(sub) - # print(substr) - # return substring_count - - # --------------- approach 2 ----------------- - count = n - for x in range(n): - y = x - while y < n - 1: - y += 1 - if s[x] == s[y]: - count += 1 - else: - if s[x:y] == s[y + 1:2 * y - x + 1]: - count += 1 - break - - return count - - -if __name__ == '__main__': - # fptr = open(os.environ['OUTPUT_PATH'], 'w') - - n = int(input("length=")) - - s = input("string=") - - result = substrCount(n, s) - - print(result) - # fptr.write(str(result) + '\n') - # - # fptr.close() +import math +import os +import random +import re +import sys + + +# Complete the substrCount function below. +def substrCount(n, s) -> int: + # --------------- approach 1 --------------- + + # substr = list(s) + # substring_count = n + # for i in range(2, n+1): + # for j in range(n): + # if (j + i) <= n: + # sub = s[j:j + i] + # if len(sub) % 2 == 0 and sub == sub[::-1]: + # substring_count += 1 + # substr.append(sub) + # elif len(sub) % 2 == 1 and sub[:len(sub)//2] == sub[len(sub)//2+1:]: + # substring_count += 1 + # substr.append(sub) + # print(substr) + # return substring_count + + # --------------- approach 2 ----------------- + count = n + for x in range(n): + y = x + while y < n - 1: + y += 1 + if s[x] == s[y]: + count += 1 + else: + if s[x:y] == s[y + 1:2 * y - x + 1]: + count += 1 + break + + return count + + +if __name__ == '__main__': + # fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input("length=")) + + s = input("string=") + + result = substrCount(n, s) + + print(result) + # fptr.write(str(result) + '\n') + # + # fptr.close() diff --git a/Others/zamka.py b/Others/zamka.py index 662556e..f675f6a 100644 --- a/Others/zamka.py +++ b/Others/zamka.py @@ -1,32 +1,32 @@ -""" -Problem statement: -You'll be given 3 integers L, D and X. - -Determine min (N) such that L <= N <= D and the sum of it's digits is X -Determine the max (M) such that L <= M <= D and the sum of it's digits is X -""" -def sum_of_digits(num): - return sum([int(i) for i in list(str(num))]) - - -def trap_escape(L,D,X): - N,M = -1,-1 - - for i in range(L, D+1): - if sum_of_digits(i) == X: - N = i - break - for i in range(D, L-1, -1): - if sum_of_digits(i) == X: - M = i - break - print(f"{N}\n{M}") - -if __name__ == "__main__": - # t = int(input("test-cases:")) - # while t: - L = int(input()) - D = int(input()) - X = int(input()) - trap_escape(L, D, X) +""" +Problem statement: +You'll be given 3 integers L, D and X. + +Determine min (N) such that L <= N <= D and the sum of it's digits is X +Determine the max (M) such that L <= M <= D and the sum of it's digits is X +""" +def sum_of_digits(num): + return sum([int(i) for i in list(str(num))]) + + +def trap_escape(L,D,X): + N,M = -1,-1 + + for i in range(L, D+1): + if sum_of_digits(i) == X: + N = i + break + for i in range(D, L-1, -1): + if sum_of_digits(i) == X: + M = i + break + print(f"{N}\n{M}") + +if __name__ == "__main__": + # t = int(input("test-cases:")) + # while t: + L = int(input()) + D = int(input()) + X = int(input()) + trap_escape(L, D, X) # t -= 1 \ No newline at end of file diff --git a/ProjectEuler+/sum_of_digit_factorials.py b/ProjectEuler+/sum_of_digit_factorials.py index f7e1c0c..9a4300c 100644 --- a/ProjectEuler+/sum_of_digit_factorials.py +++ b/ProjectEuler+/sum_of_digit_factorials.py @@ -1,15 +1,15 @@ -""" -Problem definition: -See image at : "images/sum_o_digits_o_fact.png" - -Sample Input 0 - -2 -3 1000000 -20 1000000 - -Sample Output 0 - -8 -156 -""" +""" +Problem definition: +See image at : "images/sum_o_digits_o_fact.png" + +Sample Input 0 + +2 +3 1000000 +20 1000000 + +Sample Output 0 + +8 +156 +""" diff --git a/README.md b/README.md index 9cb0be3..525ad7b 100644 --- a/README.md +++ b/README.md @@ -1,25 +1,25 @@ -# Python-Codes -Python Competitive Coding -

- Design Image -

- -## Purpose: -I have created this repository to assemble all Python problems that I have solved from GeeksForGeeks -Mostly all questions are asked in Amazon Coding interview. - -Also, I am solving problems from ProjectEuler+ from HackerRank - - 27-11-2020 : Solution from CodeChef also will be added - - 29-11-2020 : DSA cracker sheet (by Love Babbar) solutions will also be added - - 29-01-2021: Problems from HackerEarth to be added under [HackerEarth](HackerEarth/) folder. - - 28-01-2021: Problems from Codeforce to be added under [Codeforce](Codeforce/) folder. - - 28-04-2021: New Topic folder [mathematical](/mathematical) - -All problems will be well named and categorised for easy readability and access. - -## Activity: -I update the repository 2 times a week approximately. - -## Contribution: -You can contribute to my repository and open a pull request. I will accept your contribution and merge the Python code files. - +# Python-Codes +Python Competitive Coding +

+ Design Image +

+ +## Purpose: +I have created this repository to assemble all Python problems that I have solved from GeeksForGeeks +Mostly all questions are asked in Amazon Coding interview. + +Also, I am solving problems from ProjectEuler+ from HackerRank + - 27-11-2020 : Solution from CodeChef also will be added + - 29-11-2020 : DSA cracker sheet (by Love Babbar) solutions will also be added + - 29-01-2021: Problems from HackerEarth to be added under [HackerEarth](HackerEarth/) folder. + - 28-01-2021: Problems from Codeforce to be added under [Codeforce](Codeforce/) folder. + - 28-04-2021: New Topic folder [mathematical](/mathematical) + +All problems will be well named and categorised for easy readability and access. + +## Activity: +I update the repository 2 times a week approximately. + +## Contribution: +You can contribute to my repository and open a pull request. I will accept your contribution and merge the Python code files. + diff --git a/Searching/Floor_for_sorted_array.py b/Searching/Floor_for_sorted_array.py index 84cadee..b8edd67 100644 --- a/Searching/Floor_for_sorted_array.py +++ b/Searching/Floor_for_sorted_array.py @@ -1,90 +1,90 @@ -"""Given a sorted array arr[] of size N without duplicates, and given a value x. Find the floor of x in given array. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. - -Input: -First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the array and element whose floor is to be searched. Last line of input contains array elements. - -Output: -Output the index of floor of x if exists, else print -1 (0 based Indexing). - -User Task: -The task is to complete the function findFloor() which finds the floor of x. - -Expected Time Complexity: O(log N). -Expected Auxiliary Space: O(1). - -Constraints: -1 ≤ T ≤ 100 -1 ≤ N ≤ 107 -1 ≤ arr[i] ≤ 1018 -0 ≤ X ≤ arr[n-1] - -Example: -Input: -3 -7 0 -1 2 8 10 11 12 19 -7 5 -1 2 8 10 11 12 19 -7 10 -1 2 8 10 11 12 19 - -Output: --1 -1 -3 - -Explanation: -Testcase 1: No element less than 0 is found. So output is "-1". -Testcase 2: Number less than 5 is 2, whose index is 1(0-based indexing). -Testcase 3: Number less than or equal to 10 is 10 and its index is 3.""" - - -# Complete this function -def findFloor(A, N, X): - # Your code here - if min(A) < X: - if X in A: - return A.index(X) - else: - count = 0 - prev = A[0] - for i in A[1:]: - - count += 1 - if i < X: - prev = count - else: - return prev - - return prev - elif min(A) == X: - return A.index(X) - else: - return -1 - - -# { -# Driver Code Starts -# Initial Template for Python 3 - - -import math - - -def main(): - T = int(input()) - while T > 0: - NX = [int(x) for x in input().strip().split()] - N = NX[0] - X = NX[1] - - A = [int(x) for x in input().strip().split()] - - print(findFloor(A, N, X)) - - T -= 1 - - -if __name__ == "__main__": - main() +"""Given a sorted array arr[] of size N without duplicates, and given a value x. Find the floor of x in given array. Floor of x is defined as the largest element K in arr[] such that K is smaller than or equal to x. + +Input: +First line of input contains number of testcases T. For each testcase, first line of input contains number of elements in the array and element whose floor is to be searched. Last line of input contains array elements. + +Output: +Output the index of floor of x if exists, else print -1 (0 based Indexing). + +User Task: +The task is to complete the function findFloor() which finds the floor of x. + +Expected Time Complexity: O(log N). +Expected Auxiliary Space: O(1). + +Constraints: +1 ≤ T ≤ 100 +1 ≤ N ≤ 107 +1 ≤ arr[i] ≤ 1018 +0 ≤ X ≤ arr[n-1] + +Example: +Input: +3 +7 0 +1 2 8 10 11 12 19 +7 5 +1 2 8 10 11 12 19 +7 10 +1 2 8 10 11 12 19 + +Output: +-1 +1 +3 + +Explanation: +Testcase 1: No element less than 0 is found. So output is "-1". +Testcase 2: Number less than 5 is 2, whose index is 1(0-based indexing). +Testcase 3: Number less than or equal to 10 is 10 and its index is 3.""" + + +# Complete this function +def findFloor(A, N, X): + # Your code here + if min(A) < X: + if X in A: + return A.index(X) + else: + count = 0 + prev = A[0] + for i in A[1:]: + + count += 1 + if i < X: + prev = count + else: + return prev + + return prev + elif min(A) == X: + return A.index(X) + else: + return -1 + + +# { +# Driver Code Starts +# Initial Template for Python 3 + + +import math + + +def main(): + T = int(input()) + while T > 0: + NX = [int(x) for x in input().strip().split()] + N = NX[0] + X = NX[1] + + A = [int(x) for x in input().strip().split()] + + print(findFloor(A, N, X)) + + T -= 1 + + +if __name__ == "__main__": + main() # } Driver Code Ends \ No newline at end of file diff --git a/Searching/Majoirty_Eelement.py b/Searching/Majoirty_Eelement.py index 52029d6..9cd3055 100644 --- a/Searching/Majoirty_Eelement.py +++ b/Searching/Majoirty_Eelement.py @@ -1,78 +1,78 @@ -""" -Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array. - -Input: -The first line of the input contains T denoting the number of testcases. The first line of the test case will be the size of array and second line will be the elements of the array. - -Output: -For each test case the output will be the majority element of the array. Output "-1" if no majority element is there in the array. - -User Task: -The task is to complete the function findMajority() which finds the majority element in the array. If no majority exists, return -1. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(1). - -Constraints: -1 <= T<= 100 -1 <= N <= 107 -0 <= Ai <= 106 - -Example: -Input: -2 -5 -3 1 3 3 2 -3 -1 2 3 - -Output: -3 --1 - -Explanation: -Testcase 1: Since, 3 is present more than N/2 times, so it is the majority element. -Testcase 2: Since, each element in {1,2,3} appears only once so there is no majority element. -""" - - -# Complete this function -def majorityElement(A, N): - # Your code here - weight_dict = {} - for elem in A: - if elem not in weight_dict.keys(): - weight_dict[elem] = 1 - else: - weight_dict[elem] += 1 - - for item, weight in weight_dict.items(): - if weight > int(N / 2): - return item - return -1 - - -# { -# Driver Code Starts -# Initial Template for Python 3 - -import math - -from sys import stdin - - -def main(): - T = int(input()) - while T > 0: - N = int(input()) - - A = [int(x) for x in input().strip().split()] - - print(majorityElement(A, N)) - - T -= 1 - - -if __name__ == "__main__": - main() +""" +Given an array A of N elements. Find the majority element in the array. A majority element in an array A of size N is an element that appears more than N/2 times in the array. + +Input: +The first line of the input contains T denoting the number of testcases. The first line of the test case will be the size of array and second line will be the elements of the array. + +Output: +For each test case the output will be the majority element of the array. Output "-1" if no majority element is there in the array. + +User Task: +The task is to complete the function findMajority() which finds the majority element in the array. If no majority exists, return -1. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(1). + +Constraints: +1 <= T<= 100 +1 <= N <= 107 +0 <= Ai <= 106 + +Example: +Input: +2 +5 +3 1 3 3 2 +3 +1 2 3 + +Output: +3 +-1 + +Explanation: +Testcase 1: Since, 3 is present more than N/2 times, so it is the majority element. +Testcase 2: Since, each element in {1,2,3} appears only once so there is no majority element. +""" + + +# Complete this function +def majorityElement(A, N): + # Your code here + weight_dict = {} + for elem in A: + if elem not in weight_dict.keys(): + weight_dict[elem] = 1 + else: + weight_dict[elem] += 1 + + for item, weight in weight_dict.items(): + if weight > int(N / 2): + return item + return -1 + + +# { +# Driver Code Starts +# Initial Template for Python 3 + +import math + +from sys import stdin + + +def main(): + T = int(input()) + while T > 0: + N = int(input()) + + A = [int(x) for x in input().strip().split()] + + print(majorityElement(A, N)) + + T -= 1 + + +if __name__ == "__main__": + main() # } Driver Code Ends \ No newline at end of file diff --git a/Searching/Majority_Element.py b/Searching/Majority_Element.py index 463c549..799fb05 100644 --- a/Searching/Majority_Element.py +++ b/Searching/Majority_Element.py @@ -1,22 +1,22 @@ -if __name__ == '__main__': - test_cases = int(input()) - for i in range(test_cases): - n = int(input()) - elements = list(map(int, input().split())) - element_weight = {} - flag =0 - for elem in elements: - if elem not in element_weight.keys(): - element_weight[elem] = 1 - if element_weight[elem] > int(n / 2): - print(elem) - flag = 1 - break - else: - element_weight[elem] += 1 - if element_weight[elem] > int(n / 2): - print(elem) - flag = 1 - break - if flag == 0: - print(-1) +if __name__ == '__main__': + test_cases = int(input()) + for i in range(test_cases): + n = int(input()) + elements = list(map(int, input().split())) + element_weight = {} + flag =0 + for elem in elements: + if elem not in element_weight.keys(): + element_weight[elem] = 1 + if element_weight[elem] > int(n / 2): + print(elem) + flag = 1 + break + else: + element_weight[elem] += 1 + if element_weight[elem] > int(n / 2): + print(elem) + flag = 1 + break + if flag == 0: + print(-1) diff --git a/Searching/Missing_Element.py b/Searching/Missing_Element.py index ca0d08e..af7706f 100644 --- a/Searching/Missing_Element.py +++ b/Searching/Missing_Element.py @@ -1,52 +1,52 @@ -""" -Given an array of size N-1 such that it can only contain distinct integers in the range of 1 to N. Find the missing element. - -Input: -The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N denoting the size of the array. The subsequent line contains N-1 space separated array elements. - -Output: -Print the missing number. - -Your Task : -Complete the function MissingNumber() that takes array and N as input and returns the value of the missing number. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(1). - -Constraints: -1 ≤ T ≤ 200 -1 ≤ N ≤ 106 -1 ≤ array[i] ≤ 106 - -Example: -Input: -2 -5 -1 2 3 5 -10 -1 2 3 4 5 6 7 8 10 - -Output: -4 -9 - -Explanation: -Testcase 1: Given array : 1 2 3 5. Missing element is 4. -Testcase 2: Given array : 1 2 3 4 5 6 7 8 10. Missing element is 9 -""" - -def MissingNumber(array,n): - # code here - array_sum = sum(array) - expected = int((n / 2) * (2 + n - 1)) - # print(f'Array sum:{array_sum}, expected:{expected}') - missing_element = int(expected) - array_sum - return missing_element - - -t = int(input()) -for _ in range(t): - n = int(input()) - a = list(map(int, input().split())) - s = MissingNumber(a, n) +""" +Given an array of size N-1 such that it can only contain distinct integers in the range of 1 to N. Find the missing element. + +Input: +The first line of input contains an integer T denoting the number of test cases. For each test case first line contains N denoting the size of the array. The subsequent line contains N-1 space separated array elements. + +Output: +Print the missing number. + +Your Task : +Complete the function MissingNumber() that takes array and N as input and returns the value of the missing number. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(1). + +Constraints: +1 ≤ T ≤ 200 +1 ≤ N ≤ 106 +1 ≤ array[i] ≤ 106 + +Example: +Input: +2 +5 +1 2 3 5 +10 +1 2 3 4 5 6 7 8 10 + +Output: +4 +9 + +Explanation: +Testcase 1: Given array : 1 2 3 5. Missing element is 4. +Testcase 2: Given array : 1 2 3 4 5 6 7 8 10. Missing element is 9 +""" + +def MissingNumber(array,n): + # code here + array_sum = sum(array) + expected = int((n / 2) * (2 + n - 1)) + # print(f'Array sum:{array_sum}, expected:{expected}') + missing_element = int(expected) - array_sum + return missing_element + + +t = int(input()) +for _ in range(t): + n = int(input()) + a = list(map(int, input().split())) + s = MissingNumber(a, n) print(s) \ No newline at end of file diff --git a/Searching/PeakElement.py b/Searching/PeakElement.py index d5a7706..9e66887 100644 --- a/Searching/PeakElement.py +++ b/Searching/PeakElement.py @@ -1,93 +1,93 @@ -""" -Given an array A of N integers. The task is to find a peak element in it in O( log N ) . -An array element is peak if it is not smaller than its neighbours. For corner elements, we need to consider only one neighbour. -Note: There may be multiple peak element possible, in that case you may return any valid index (0 based indexing). - -Input: -The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N. Then in the next line are N space separated values of the array. - -Output: -For each test case output will be 1 if the index returned by the function is an index with peak element. - -User Task: -You don't have to take any input. Just complete the provided function peakElement() and return the valid index. - -Expected Time Complexity: O(log N). -Expected Auxiliary Space: O(1). - -Constraints: -1 <= T <= 100 -1 <= N <= 105 -1 <= A[] <= 106 - -Example: -Input: -2 -3 -1 2 3 -2 -3 4 -Output: -1 -1 - -Explanation: -Testcase 1: In the given array, 3 is the peak element as it is greater than its neighbour. -Testcase 2: 4 is the peak element as it is greater than its neighbour elements. -""" - - -# function should return index to the any valid peak element -def peakElement(arr, n): - # Code here - i = 0 - while i < n: - if i != 0 and i != n - 1: - left_neighbour = arr[i - 1] - right_neighbour = arr[i + 1] - element = arr[i] - if element > left_neighbour and element > right_neighbour: - return i - elif i == 0: - if n > 1: - right_neighbour = arr[i + 1] - element = arr[i] - if element > right_neighbour: - return i - else: - return 0 - elif i == n - 1: - left_neighbour = arr[i - 1] - element = arr[i] - if element > left_neighbour: - return i - i += 1 - - -# { -# Driver Code Starts -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().strip().split())) - index = peakElement(arr, n) - flag = False - if index == 0 and n == 1: - flag = True - elif index == 0 and arr[index] >= arr[index + 1]: - flag = True - elif index == n - 1 and arr[index] >= arr[index - 1]: - flag = True - elif arr[index - 1] <= arr[index] and arr[index] >= arr[index + 1]: - flag = True - else: - flag = False - - if flag: - print(1) - else: - print(0) -# Contributed by: Harshit Sidhwa - -# } Driver Code Ends +""" +Given an array A of N integers. The task is to find a peak element in it in O( log N ) . +An array element is peak if it is not smaller than its neighbours. For corner elements, we need to consider only one neighbour. +Note: There may be multiple peak element possible, in that case you may return any valid index (0 based indexing). + +Input: +The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer N. Then in the next line are N space separated values of the array. + +Output: +For each test case output will be 1 if the index returned by the function is an index with peak element. + +User Task: +You don't have to take any input. Just complete the provided function peakElement() and return the valid index. + +Expected Time Complexity: O(log N). +Expected Auxiliary Space: O(1). + +Constraints: +1 <= T <= 100 +1 <= N <= 105 +1 <= A[] <= 106 + +Example: +Input: +2 +3 +1 2 3 +2 +3 4 +Output: +1 +1 + +Explanation: +Testcase 1: In the given array, 3 is the peak element as it is greater than its neighbour. +Testcase 2: 4 is the peak element as it is greater than its neighbour elements. +""" + + +# function should return index to the any valid peak element +def peakElement(arr, n): + # Code here + i = 0 + while i < n: + if i != 0 and i != n - 1: + left_neighbour = arr[i - 1] + right_neighbour = arr[i + 1] + element = arr[i] + if element > left_neighbour and element > right_neighbour: + return i + elif i == 0: + if n > 1: + right_neighbour = arr[i + 1] + element = arr[i] + if element > right_neighbour: + return i + else: + return 0 + elif i == n - 1: + left_neighbour = arr[i - 1] + element = arr[i] + if element > left_neighbour: + return i + i += 1 + + +# { +# Driver Code Starts +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().strip().split())) + index = peakElement(arr, n) + flag = False + if index == 0 and n == 1: + flag = True + elif index == 0 and arr[index] >= arr[index + 1]: + flag = True + elif index == n - 1 and arr[index] >= arr[index - 1]: + flag = True + elif arr[index - 1] <= arr[index] and arr[index] >= arr[index + 1]: + flag = True + else: + flag = False + + if flag: + print(1) + else: + print(0) +# Contributed by: Harshit Sidhwa + +# } Driver Code Ends diff --git a/Searching/TransitionPoint.py b/Searching/TransitionPoint.py index 9e13875..76ef6a1 100644 --- a/Searching/TransitionPoint.py +++ b/Searching/TransitionPoint.py @@ -1,55 +1,55 @@ -""" -You are given a sorted array containing only numbers 0 and 1. Find the transition point efficiently. Transition point is a point where "0" ends and "1" begins (0 based indexing). -Note that, if there is no "1" exists, print -1. - -Input: - -The first line of the input contains T denoting the number of testcases. The first line of the test case will be the size of array and second line will be the elements of the array. - -Output: - -Your function should return transition point. - -Your Task: -The task is to complete the function transitionPoint() that takes array and N as input and returns the value of the position where "0" ends and "1" begins. - -Expected Time Complexity: O(LogN). -Expected Auxiliary Space: O(1). - -Constraints: - -1 ≤ T ≤ 100 -1 ≤ N ≤ 500000 -0 ≤ C[i] ≤ 1 -Example: - -Input -2 -5 -0 0 0 1 1 -4 -0 0 0 0 - -Output -3 --1 - -Explanation: -Testcase 1: position 3 is 0 and next one is 1, so answer is 3. -Testcase 2: Since, there is no "1", so the answer is -1. -""" - -def transitionPoint(arr, n): - # Code here - if 1 in arr: - return arr.index(1) - else: - return -1 - - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().split())) - transitionPoint(arr,n) +""" +You are given a sorted array containing only numbers 0 and 1. Find the transition point efficiently. Transition point is a point where "0" ends and "1" begins (0 based indexing). +Note that, if there is no "1" exists, print -1. + +Input: + +The first line of the input contains T denoting the number of testcases. The first line of the test case will be the size of array and second line will be the elements of the array. + +Output: + +Your function should return transition point. + +Your Task: +The task is to complete the function transitionPoint() that takes array and N as input and returns the value of the position where "0" ends and "1" begins. + +Expected Time Complexity: O(LogN). +Expected Auxiliary Space: O(1). + +Constraints: + +1 ≤ T ≤ 100 +1 ≤ N ≤ 500000 +0 ≤ C[i] ≤ 1 +Example: + +Input +2 +5 +0 0 0 1 1 +4 +0 0 0 0 + +Output +3 +-1 + +Explanation: +Testcase 1: position 3 is 0 and next one is 1, so answer is 3. +Testcase 2: Since, there is no "1", so the answer is -1. +""" + +def transitionPoint(arr, n): + # Code here + if 1 in arr: + return arr.index(1) + else: + return -1 + + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().split())) + transitionPoint(arr,n) diff --git a/Searching/count_mentioned_frequency.py b/Searching/count_mentioned_frequency.py index ba122a9..84d302c 100644 --- a/Searching/count_mentioned_frequency.py +++ b/Searching/count_mentioned_frequency.py @@ -1,81 +1,81 @@ -""" -Count More than n/k Occurences -Given an array arr[] of size N and an element k. The task is to find all elements in array that appear more than n/k times. - -Input: -The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the array. Then the next line contains n space separated integers forming the array. The last line of input contains an integer k. - -Output: -Print the count of elements in array that appear more than n/k times. - -User Task: -The task is to complete the function countOccurence() which returns count of elements with more than n/k times appearance. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(N). - -Constraints: -1 <= T <= 102 -1 <= N <= 104 -1 <= a[i] <= 106 -1 <= k <= N - -Example: -Input: -2 -8 -3 1 2 2 1 2 3 3 -4 -4 -2 3 3 2 -3 -Output: -2 -2 - -Explanation: -Testcase 1: In the given array, 3 and 2 are the only elements that appears more than n/k times. -Testcase 2: In the given array, 3 and 2 are the only elements that appears more than n/k times. So the count of elements are 2. -""" - - -# Complete this function -def countOccurence(arr, n, k): - # Your code here - weight = {} - for i in arr: - if i in weight: - weight[i] += 1 - else: - weight[i] = 1 - count = 0 - for item, weight in weight.items(): - if weight > int(n / k): - count += 1 - return count - - -# { -# Driver Code Starts -# Initial Template for Python 3 - -import math - - -def main(): - T = int(input()) - while (T > 0): - N = int(input()) - - A = list(map(int, input().split())) - - K = int(input()) - - print(countOccurence(A, N, K)) - - T -= 1 - - -if __name__ == "__main__": - main() +""" +Count More than n/k Occurences +Given an array arr[] of size N and an element k. The task is to find all elements in array that appear more than n/k times. + +Input: +The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. Each test case contains an integer n denoting the size of the array. Then the next line contains n space separated integers forming the array. The last line of input contains an integer k. + +Output: +Print the count of elements in array that appear more than n/k times. + +User Task: +The task is to complete the function countOccurence() which returns count of elements with more than n/k times appearance. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(N). + +Constraints: +1 <= T <= 102 +1 <= N <= 104 +1 <= a[i] <= 106 +1 <= k <= N + +Example: +Input: +2 +8 +3 1 2 2 1 2 3 3 +4 +4 +2 3 3 2 +3 +Output: +2 +2 + +Explanation: +Testcase 1: In the given array, 3 and 2 are the only elements that appears more than n/k times. +Testcase 2: In the given array, 3 and 2 are the only elements that appears more than n/k times. So the count of elements are 2. +""" + + +# Complete this function +def countOccurence(arr, n, k): + # Your code here + weight = {} + for i in arr: + if i in weight: + weight[i] += 1 + else: + weight[i] = 1 + count = 0 + for item, weight in weight.items(): + if weight > int(n / k): + count += 1 + return count + + +# { +# Driver Code Starts +# Initial Template for Python 3 + +import math + + +def main(): + T = int(input()) + while (T > 0): + N = int(input()) + + A = list(map(int, input().split())) + + K = int(input()) + + print(countOccurence(A, N, K)) + + T -= 1 + + +if __name__ == "__main__": + main() # } Driver Code Ends \ No newline at end of file diff --git a/Searching/extra_elem_index.py b/Searching/extra_elem_index.py index f0aec3e..d6346f0 100644 --- a/Searching/extra_elem_index.py +++ b/Searching/extra_elem_index.py @@ -1,58 +1,58 @@ -""" -Given two sorted arrays of distinct elements. There is only 1 difference between the arrays. First array has one element extra added in between. Find the index of the extra element. - -Input: -The first line of input contains an integer T, denoting the no of test cases. Then T test cases follow. The first line of each test case contains an integer N, denoting the number of elements in array. The second line of each test case contains N space separated values of the array A[]. The Third line of each test case contains N-1 space separated values of the array B[]. - -Output: -Return the index (0 based indexing) of the corresponding extra element in array A[].(starting index 0). - -User Task: -You don't have to take any input. Just complete the provided function findExtra() that takes array A[], B[] and size of A[] and return the valid index (0 based indexing). - -Expected Time Complexity: O(log N). -Expected Auxiliary Space: O(1). - -Constraints: -1<=T<=100 -2<=N<=104 -1<=Ai<=105 - -Example: -Input: -2 -7 -2 4 6 8 9 10 12 -2 4 6 8 10 12 -6 -3 5 7 9 11 13 -3 5 7 11 13 -Output: -4 -3 - -Explanation: -Testcase 1: In the second array, 9 is missing and it's index in the first array is 4. -Testcase 2: In the second array, 9 is missing and it's index in the first array is 3. -""" - - -def findExtra(a, b, n): - # add code here - # find the missing element - if len(a) == n: # means a is larger - extra_element = list(set(a) - set(b))[0] - extra_elem_index = a.index(extra_element) - return extra_elem_index - - -# { -# Driver Code Starts -if __name__ == "__main__": - t = int(input()) - for i in range(t): - n = int(input()) - a = list(map(int, input().split())) - b = list(map(int, input().split())) - print(findExtra(a, b, n)) -# } Driver Code Ends +""" +Given two sorted arrays of distinct elements. There is only 1 difference between the arrays. First array has one element extra added in between. Find the index of the extra element. + +Input: +The first line of input contains an integer T, denoting the no of test cases. Then T test cases follow. The first line of each test case contains an integer N, denoting the number of elements in array. The second line of each test case contains N space separated values of the array A[]. The Third line of each test case contains N-1 space separated values of the array B[]. + +Output: +Return the index (0 based indexing) of the corresponding extra element in array A[].(starting index 0). + +User Task: +You don't have to take any input. Just complete the provided function findExtra() that takes array A[], B[] and size of A[] and return the valid index (0 based indexing). + +Expected Time Complexity: O(log N). +Expected Auxiliary Space: O(1). + +Constraints: +1<=T<=100 +2<=N<=104 +1<=Ai<=105 + +Example: +Input: +2 +7 +2 4 6 8 9 10 12 +2 4 6 8 10 12 +6 +3 5 7 9 11 13 +3 5 7 11 13 +Output: +4 +3 + +Explanation: +Testcase 1: In the second array, 9 is missing and it's index in the first array is 4. +Testcase 2: In the second array, 9 is missing and it's index in the first array is 3. +""" + + +def findExtra(a, b, n): + # add code here + # find the missing element + if len(a) == n: # means a is larger + extra_element = list(set(a) - set(b))[0] + extra_elem_index = a.index(extra_element) + return extra_elem_index + + +# { +# Driver Code Starts +if __name__ == "__main__": + t = int(input()) + for i in range(t): + n = int(input()) + a = list(map(int, input().split())) + b = list(map(int, input().split())) + print(findExtra(a, b, n)) +# } Driver Code Ends diff --git a/Searching/median_of_sorted_arrays.py b/Searching/median_of_sorted_arrays.py index a27a692..59f887a 100644 --- a/Searching/median_of_sorted_arrays.py +++ b/Searching/median_of_sorted_arrays.py @@ -1,72 +1,72 @@ -""" -Given two sorted arrays array1 and array2 of size m and n respectively. Find the median of the two sorted arrays. - -Input: -First line of input contains number of testcases T. For each testcase, there will be two lines. First line will contain m followed by m space separated integers for array1. Second line will contain n followed by n space separated integers for array2. - -Output: -Print the median of the two sorted arrays. - -User Task: -The task is to complete the function MedianOfArrays() that takes array1 and array2 as input and returns their median. - -Expected Time Complexity: O(min(log n, log m)). -Expected Auxiliary Space: O(1). - -Constraints: -1 <= T <= 200 -0 <= m,n <= 10000 -1 <= array1[i], array2[i] <= 10^5 - -Example: -Input: -2 -3 1 5 9 -4 2 3 6 7 -2 4 6 -4 1 2 3 5 - -Output: -5 -3.5 - -Explanation: -Case 1: The middle element for {1,2,3,5,6,7,9} is 5 -Case 2: The middle 2 elements for {1,2,3,4,5,6} are 3 and 4 and their average is 3.5 -""" - -def MedianOfArrays(array1, array2): - new_array = array1.copy() - new_array.extend(array2) - new_array = sorted(list(new_array)) - length = len(new_array) - if length % 2 != 0: # odd - median_index = int((length + 1) / 2) - 1 - median_element = new_array[median_index] - return median_element - else: - median_index_1 = int(length / 2) - 1 - median_index_2 = median_index_1 + 1 - median_element_1 = new_array[median_index_1] - median_element_2 = new_array[median_index_2] - result = (median_element_2 + median_element_1) / 2 - if result - int(result) != 0: - return result - else: - return int(result) - - -# { -# Driver Code Starts -if __name__ == '__main__': - tcs = int(input()) - - for _ in range(tcs): - arr1 = [int(x) for x in input().split()] - arr2 = [int(x) for x in input().split()] - - array1, array2 = arr1[1:], arr2[1:] - - print(MedianOfArrays(array1, array2)) - +""" +Given two sorted arrays array1 and array2 of size m and n respectively. Find the median of the two sorted arrays. + +Input: +First line of input contains number of testcases T. For each testcase, there will be two lines. First line will contain m followed by m space separated integers for array1. Second line will contain n followed by n space separated integers for array2. + +Output: +Print the median of the two sorted arrays. + +User Task: +The task is to complete the function MedianOfArrays() that takes array1 and array2 as input and returns their median. + +Expected Time Complexity: O(min(log n, log m)). +Expected Auxiliary Space: O(1). + +Constraints: +1 <= T <= 200 +0 <= m,n <= 10000 +1 <= array1[i], array2[i] <= 10^5 + +Example: +Input: +2 +3 1 5 9 +4 2 3 6 7 +2 4 6 +4 1 2 3 5 + +Output: +5 +3.5 + +Explanation: +Case 1: The middle element for {1,2,3,5,6,7,9} is 5 +Case 2: The middle 2 elements for {1,2,3,4,5,6} are 3 and 4 and their average is 3.5 +""" + +def MedianOfArrays(array1, array2): + new_array = array1.copy() + new_array.extend(array2) + new_array = sorted(list(new_array)) + length = len(new_array) + if length % 2 != 0: # odd + median_index = int((length + 1) / 2) - 1 + median_element = new_array[median_index] + return median_element + else: + median_index_1 = int(length / 2) - 1 + median_index_2 = median_index_1 + 1 + median_element_1 = new_array[median_index_1] + median_element_2 = new_array[median_index_2] + result = (median_element_2 + median_element_1) / 2 + if result - int(result) != 0: + return result + else: + return int(result) + + +# { +# Driver Code Starts +if __name__ == '__main__': + tcs = int(input()) + + for _ in range(tcs): + arr1 = [int(x) for x in input().split()] + arr2 = [int(x) for x in input().split()] + + array1, array2 = arr1[1:], arr2[1:] + + print(MedianOfArrays(array1, array2)) + # } Driver Code Ends \ No newline at end of file diff --git a/Searching/search_from_rotated_array.py b/Searching/search_from_rotated_array.py index 84e1a26..9b4d708 100644 --- a/Searching/search_from_rotated_array.py +++ b/Searching/search_from_rotated_array.py @@ -1,229 +1,229 @@ -"""Search in a -Sorted and Rotated -Array -Given -a -sorted and rotated -array -A -of -N -distinct -elements -which is rotated -at -some -point, and given -an -element -K.The -task is to -find -the -index -of -the -given -element -K in the -array -A. - -Input: -The -first -line -of -the -input -contains -an -integer -T, denoting -the -total -number -of -test -cases.Then -T -test -cases -follow.Each -test -case -consists -of -three -lines.The -first -line -of -each -test -case -contains -an -integer -N -denoting -the -size -of -the -given -array.The -second -line -of -each -test -case -contains -N -space - separated -integers -denoting -the -elements -of -the -array -A.The -third -line -of -each -test -case -contains -an -integer -K -denoting -the -element -to -be -searched in the -array. - -Output: -For -each -test -case, print -the -index(0 -based -indexing) of -the -element -K in a -new -line, -if K does not exist in the array then print -1. - -User -Task: -Complete -Search() -function and -return the -index -of -the -element -K if found in the -array.If -the -element is not present, then -return -1. - -Expected -Time -Complexity: O(log -N). -Expected -Auxiliary -Space: O(1). - -Constraints: -1 ≤ T ≤ 100 -1 ≤ N ≤ 107 -0 ≤ Ai ≤ 108 -1 ≤ K ≤ 108 - -Example: -Input: -3 -9 -5 -6 -7 -8 -9 -10 -1 -2 -3 -10 -3 -3 -1 -2 -1 -4 -3 -5 -1 -2 -6 - -Output: -5 -1 --1 - -Explanation: -Testcase -1: 10 is found -at -index -5. -Testcase -2: 1 is found -at -index -1. -Testcase -3: 6 -doesn -'t exist. - -""" - - -def Search(arr,n,k): - #code here - if k in arr: - return arr.index(k) - else: - return -1 - - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -if __name__ == '__main__': - tcs=int(input()) - for _ in range(tcs): - n=int(input()) - arr=[int(x) for x in input().split()] - k=int(input()) - - print(Search(arr,n,k)) - +"""Search in a +Sorted and Rotated +Array +Given +a +sorted and rotated +array +A +of +N +distinct +elements +which is rotated +at +some +point, and given +an +element +K.The +task is to +find +the +index +of +the +given +element +K in the +array +A. + +Input: +The +first +line +of +the +input +contains +an +integer +T, denoting +the +total +number +of +test +cases.Then +T +test +cases +follow.Each +test +case +consists +of +three +lines.The +first +line +of +each +test +case +contains +an +integer +N +denoting +the +size +of +the +given +array.The +second +line +of +each +test +case +contains +N +space - separated +integers +denoting +the +elements +of +the +array +A.The +third +line +of +each +test +case +contains +an +integer +K +denoting +the +element +to +be +searched in the +array. + +Output: +For +each +test +case, print +the +index(0 +based +indexing) of +the +element +K in a +new +line, +if K does not exist in the array then print -1. + +User +Task: +Complete +Search() +function and +return the +index +of +the +element +K if found in the +array.If +the +element is not present, then +return -1. + +Expected +Time +Complexity: O(log +N). +Expected +Auxiliary +Space: O(1). + +Constraints: +1 ≤ T ≤ 100 +1 ≤ N ≤ 107 +0 ≤ Ai ≤ 108 +1 ≤ K ≤ 108 + +Example: +Input: +3 +9 +5 +6 +7 +8 +9 +10 +1 +2 +3 +10 +3 +3 +1 +2 +1 +4 +3 +5 +1 +2 +6 + +Output: +5 +1 +-1 + +Explanation: +Testcase +1: 10 is found +at +index +5. +Testcase +2: 1 is found +at +index +1. +Testcase +3: 6 +doesn +'t exist. + +""" + + +def Search(arr,n,k): + #code here + if k in arr: + return arr.index(k) + else: + return -1 + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +if __name__ == '__main__': + tcs=int(input()) + for _ in range(tcs): + n=int(input()) + arr=[int(x) for x in input().split()] + k=int(input()) + + print(Search(arr,n,k)) + # } Driver Code Ends \ No newline at end of file diff --git a/Searching/smallest_positive_number.py b/Searching/smallest_positive_number.py index b7fb4d0..d45d712 100644 --- a/Searching/smallest_positive_number.py +++ b/Searching/smallest_positive_number.py @@ -1,50 +1,50 @@ -"""You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array. -Note: Expected solution in O(n) time using constant extra space. - -Input: -First line consists of T test cases. First line of every test case consists of N, denoting the number of elements in array. Second line of every test case consists of elements in array. - -Output: -Single line output, print the smallest positive number missing. - -User Task: -The task is to complete the function findMissing() which finds the smallest positive missing number. - -Expected Time Complexity: O(N). -Expected Auxiliary Space: O(1). - -Constraints: -1 <= T <= 100 -1 <= N <= 106 --106 <= arr[i] <= 106 - -Example: -Input: -2 -5 -1 2 3 4 5 -5 -0 -10 1 3 -20 -Output: -6 -2""" - - -def findMissing(arr, size): - for i in range(1,size+2): - if i not in arr: - return i - - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -if __name__ == '__main__': - t=int(input()) - for i in range(t): - n = int(input()) - arr = list(map(int, input().strip().split())) - print(findMissing(arr, n)) +"""You are given an array arr[] of N integers including 0. The task is to find the smallest positive number missing from the array. +Note: Expected solution in O(n) time using constant extra space. + +Input: +First line consists of T test cases. First line of every test case consists of N, denoting the number of elements in array. Second line of every test case consists of elements in array. + +Output: +Single line output, print the smallest positive number missing. + +User Task: +The task is to complete the function findMissing() which finds the smallest positive missing number. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(1). + +Constraints: +1 <= T <= 100 +1 <= N <= 106 +-106 <= arr[i] <= 106 + +Example: +Input: +2 +5 +1 2 3 4 5 +5 +0 -10 1 3 -20 +Output: +6 +2""" + + +def findMissing(arr, size): + for i in range(1,size+2): + if i not in arr: + return i + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +if __name__ == '__main__': + t=int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().strip().split())) + print(findMissing(arr, n)) # } Driver Code Ends \ No newline at end of file diff --git a/Sorting/Find_Zero_Sum_Triplets.py b/Sorting/Find_Zero_Sum_Triplets.py index 25cc2cc..2e46565 100644 --- a/Sorting/Find_Zero_Sum_Triplets.py +++ b/Sorting/Find_Zero_Sum_Triplets.py @@ -1,19 +1,19 @@ -def findTriplets(arr, n): - for i in range(n - 1): - # Find all pairs with sum - s = set() - for j in range(i + 1, n): - x = -(arr[i] + arr[j]) - if x in s: - return 1 - else: - s.add(arr[j]) - return 0 - - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - n = int(input()) - a = list(map(int, input().split())) - print(findTriplets(a, n)) +def findTriplets(arr, n): + for i in range(n - 1): + # Find all pairs with sum + s = set() + for j in range(i + 1, n): + x = -(arr[i] + arr[j]) + if x in s: + return 1 + else: + s.add(arr[j]) + return 0 + + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + n = int(input()) + a = list(map(int, input().split())) + print(findTriplets(a, n)) diff --git a/Sorting/Merge_sort.cpp b/Sorting/Merge_sort.cpp index b6b4255..74aa1f2 100644 --- a/Sorting/Merge_sort.cpp +++ b/Sorting/Merge_sort.cpp @@ -1,113 +1,113 @@ -// C program for implementation of Merge Sort -#include -#include -using namespace std; - -void merge(int arr[], int l, int m, int r); - -/* l is for left index and r is right index of the - sub-array of arr to be sorted */ -void mergeSort(int arr[], int l, int r) -{ - if (l < r) - { - // Same as (l+r)/2, but avoids overflow for - // large l and h - int m = l+(r-l)/2; - - // Sort first and second halves - mergeSort(arr, l, m); - mergeSort(arr, m+1, r); - - merge(arr, l, m, r); - } -} - -/* Function to print an array */ -void printArray(int arr[], int size) -{ - int i; - for (i=0; i < size; i++) - printf("%d ", arr[i]); - printf("\n"); -} - -// Driver program to test above functions -int main() -{ - int n,T,i; - - scanf("%d",&T); - - while(T--){ - - scanf("%d",&n); - int arr[n+1]; - for(i=0;i +#include +using namespace std; + +void merge(int arr[], int l, int m, int r); + +/* l is for left index and r is right index of the + sub-array of arr to be sorted */ +void mergeSort(int arr[], int l, int r) +{ + if (l < r) + { + // Same as (l+r)/2, but avoids overflow for + // large l and h + int m = l+(r-l)/2; + + // Sort first and second halves + mergeSort(arr, l, m); + mergeSort(arr, m+1, r); + + merge(arr, l, m, r); + } +} + +/* Function to print an array */ +void printArray(int arr[], int size) +{ + int i; + for (i=0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver program to test above functions +int main() +{ + int n,T,i; + + scanf("%d",&T); + + while(T--){ + + scanf("%d",&n); + int arr[n+1]; + for(i=0;i arr[c]): - if c > j: - count += c - j - c += 1 - return count - - -# { -# Driver Code Starts -# Initial Template for Python 3 - -import atexit -import io -import sys - -_INPUT_LINES = sys.stdin.read().splitlines() -input = iter(_INPUT_LINES).__next__ -_OUTPUT_BUFFER = io.StringIO() -sys.stdout = _OUTPUT_BUFFER - - -@atexit.register -def write(): - sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) - - -if __name__ == '__main__': - t = int(input()) - for i in range(t): - size = int(input()) - arr = list(map(int, input().strip().split())) - print(findNumberOfTriangles(arr, size)) - +""" +Problem Statement: +Given an unsorted array arr[] of positive integers. Find the number of triangles that can be formed with three different array elements as lengths of three sides of triangles. + +Example 1: + +Input: N = 3, arr[] = {3, 5, 4} +Output: 1 +Explanation: A triangle is possible +with all the elements 5, 3 and 4. + +Example 2: + +Input: N = 5, arr[] = {6, 4, 9, 7, 8} +Output: 10 +Explanation: There are 10 triangles possible +with the given elements like (6,4,9), (6,7,8),... + +Your Task: This is a function problem. You only need to complete the function findNumberOfTriangles() that takes arr[] and N as input parameters and returns the count of total possible triangles. + +Expected Time Complexity: O(N2). +Expected Space Complexity: O(1). + +Constraints: +3 <= N <= 103 +1 <= arr[i] <= 103 +""" + +''' Your task is to return the total no of triangles possible.''' + + +def findNumberOfTriangles(arr, n): + # code here + arr.sort() + count = 0 + for i in range(n - 2): + c = i + 1 + for j in range(i + 1, n): + while (c < n and arr[i] + arr[j] > arr[c]): + if c > j: + count += c - j + c += 1 + return count + + +# { +# Driver Code Starts +# Initial Template for Python 3 + +import atexit +import io +import sys + +_INPUT_LINES = sys.stdin.read().splitlines() +input = iter(_INPUT_LINES).__next__ +_OUTPUT_BUFFER = io.StringIO() +sys.stdout = _OUTPUT_BUFFER + + +@atexit.register +def write(): + sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) + + +if __name__ == '__main__': + t = int(input()) + for i in range(t): + size = int(input()) + arr = list(map(int, input().strip().split())) + print(findNumberOfTriangles(arr, size)) + # } Driver Code Ends \ No newline at end of file diff --git a/Sorting/heap_sort.py b/Sorting/heap_sort.py index ab2d897..543aef0 100644 --- a/Sorting/heap_sort.py +++ b/Sorting/heap_sort.py @@ -1,49 +1,49 @@ -""" -Knowledge Source: -Learned from book: "Introduction to algorithms" -By cormen. - -Details about heap sort: - -- running time is O(N Log N) -""" -def heapify(arr, n, i): - largest = i # Initialize largest as root - l = 2 * i + 1 # left = 2*i + 1 - r = 2 * i + 2 # right = 2*i + 2 - - # See if left child of root exists and is - # greater than root - if l < n and arr[i] < arr[l]: - largest = l - - # See if right child of root exists and is - # greater than root - if r < n and arr[largest] < arr[r]: - largest = r - - # Change root, if needed - if largest != i: - arr[i],arr[largest] = arr[largest],arr[i] # swap - - # Heapify the root. - heapify(arr, n, largest) - -def heapsort(arr): - n = len(arr) - - # Since last parent will be at ((n//2)-1) we can start at that location. - for i in range((n//2)-1, -1, -1): - heapify(arr, n, i) - - for i in range(n-1, 0, -1): - arr[i], arr[0] = arr[0], arr[i] - heapify(arr, i, 0) - -arr = [10,40,11,19,70,60,25] -heapsort(arr) -n = len(arr) -print("sorted array is:") -for i in range(n): - print(arr[i], end="," if i 1: - message = 'Neither' - return message - elif unit.isdigit() is True: - if int(unit) > 255: - message = 'Neither' - return message - else: - return "Neither" - return message - else: - return "Neither" - elif ':' in address: - if len(address.split(':')) == 8: - message = "IPv6" - for unit in address.split(':'): - if unit == '' or unit.isalnum() is False or len(unit)>4: - message = "Neither" - return message - for letters in unit: # if any letter in unit (1/8) does not lie in a-f (hexadecimal) - if letters.isalpha() is True: - if letters.lower() not in ['a','b','c','d','e','f']: - return 'Neither' - return message - else: - return "Neither" - else: - return "Neither" - +""" +Write a function to check whether an input string is a valid IPv4 address or IPv6 address or neither. + +IPv4 addresses are canonically represented in dot-decimal notation, which consists of four decimal numbers, each ranging from 0 to 255, separated by dots ("."), e.g.,172.16.254.1; + +Besides, leading zeros in the IPv4 is invalid. For example, the address 172.16.254.01 is invalid. + +IPv6 addresses are represented as eight groups of four hexadecimal digits, each group representing 16 bits. The groups are separated by colons (":"). For example, the address 2001:0db8:85a3:0000:0000:8a2e:0370:7334 is a valid one. Also, we could omit some leading zeros among four hexadecimal digits and some low-case characters in the address to upper-case ones, so 2001:db8:85a3:0:0:8A2E:0370:7334 is also a valid IPv6 address(Omit leading zeros and using upper cases). + +However, we don't replace a consecutive group of zero value with a single empty group using two consecutive colons (::) to pursue simplicity. For example, 2001:0db8:85a3::8A2E:0370:7334 is an invalid IPv6 address. + +Besides, extra leading zeros in the IPv6 is also invalid. For example, the address 02001:0db8:85a3:0000:0000:8a2e:0370:7334 is invalid. + +Note: You may assume there is no extra space or special characters in the input string. + +Example 1: +Input: "172.16.254.1" + +Output: "IPv4" + +Explanation: This is a valid IPv4 address, return "IPv4". +Example 2: +Input: "2001:0db8:85a3:0:0:8A2E:0370:7334" + +Output: "IPv6" + +Explanation: This is a valid IPv6 address, return "IPv6". +Example 3: +Input: "256.256.256.256" + +Output: "Neither" + +Explanation: This is neither a IPv4 address nor a IPv6 address. +""" +def validator(address): + message = '' + if '.' in address: + if len(address.split('.')) == 4: # proceed for validation + message = "IPv4" + for unit in address.split('.'): + if unit.startswith('0') and len(unit) > 1: + message = 'Neither' + return message + elif unit.isdigit() is True: + if int(unit) > 255: + message = 'Neither' + return message + else: + return "Neither" + return message + else: + return "Neither" + elif ':' in address: + if len(address.split(':')) == 8: + message = "IPv6" + for unit in address.split(':'): + if unit == '' or unit.isalnum() is False or len(unit)>4: + message = "Neither" + return message + for letters in unit: # if any letter in unit (1/8) does not lie in a-f (hexadecimal) + if letters.isalpha() is True: + if letters.lower() not in ['a','b','c','d','e','f']: + return 'Neither' + return message + else: + return "Neither" + else: + return "Neither" + print(validator(input("Enter address:"))) \ No newline at end of file diff --git a/String/anagram_of_string.cpp b/String/anagram_of_string.cpp index 0d9152e..3b59182 100644 --- a/String/anagram_of_string.cpp +++ b/String/anagram_of_string.cpp @@ -1,76 +1,76 @@ -/* -Problem Statement: -Anagram of String -Given two strings S1 and S2 in lowercase, the task is to make them anagram. The only allowed operation is to remove a character from any string. Find the minimum number of characters to be deleted to make both the strings anagram. Two strings are called anagram of each other if one of them can be converted into another by rearranging its letters. - -Example 1: - -Input: -S1 = bcadeh -S2 = hea -Output: 3 -Explanation: We need to remove b, c -and d from S1. -Example 2: - -Input: -S1 = cddgk -S2 = gcd -Output: 2 -Explanation: We need to remove d and -k from S1. -Your Task: -Complete the function remAnagram() which takes two strings S1, S2 as input parameter, and returns minimum characters needs to be deleted. - -Expected Time Complexity: O(max(|S1|, |S2|)), where |S| = length of string S. -Expected Auxiliary Space: O(26) - -Constraints: -1 <= |S1|, |S2| <= 10^5 -*/ - -#include -#include -#include -using namespace std; - -const int CHARS = 26; - -int remAnagram(string str1, string str2); - -int main(){ - int t; - cin>>t; - - while (t--) - { - string str1, str2; - cin>>str1>>str2; - cout< +#include +#include +using namespace std; + +const int CHARS = 26; + +int remAnagram(string str1, string str2); + +int main(){ + int t; + cin>>t; + + while (t--) + { + string str1, str2; + cin>>str1>>str2; + cout< -1: - order.append(index_now) - new_str = new_str[index_:] - else: - return False - if sorted(order) == order: - return True - else: - return False - -def main(): - V = input() # take input of the virus - n = int(input()) # number of samples - for p in range(n): - B = input() - if check_subseq(V, B): - print("POSITIVE") - else: - print("NEGATIVE") - -main() - +''' Read input from STDIN. Print your output to STDOUT ''' + #Use input() to read input from STDIN and use print to write your output to STDOUT +def check_subseq(V, B): + new_str = V + order = [] + index_now = 0 + for c in B: + index_ = new_str.find(c) + index_now += index_ + if index_ > -1: + order.append(index_now) + new_str = new_str[index_:] + else: + return False + if sorted(order) == order: + return True + else: + return False + +def main(): + V = input() # take input of the virus + n = int(input()) # number of samples + for p in range(n): + B = input() + if check_subseq(V, B): + print("POSITIVE") + else: + print("NEGATIVE") + +main() + diff --git a/String/implement_str_str.py b/String/implement_str_str.py index 6cc468c..0e8c201 100644 --- a/String/implement_str_str.py +++ b/String/implement_str_str.py @@ -1,15 +1,15 @@ -""" -Your task is to implement the function strstr. The function takes two strings as arguments (s,x) and locates the occurrence of the string x in the string s. The function returns and integer denoting the first occurrence of the string x in s (0 based indexing). -""" - -import re - -def strstr(s,x): - flag = 1 - for i in re.finditer(x,s): - return i.span()[0] - flag = 0 - if flag == 1: - return -1 - +""" +Your task is to implement the function strstr. The function takes two strings as arguments (s,x) and locates the occurrence of the string x in the string s. The function returns and integer denoting the first occurrence of the string x in s (0 based indexing). +""" + +import re + +def strstr(s,x): + flag = 1 + for i in re.finditer(x,s): + return i.span()[0] + flag = 0 + if flag == 1: + return -1 + print(strstr("GeeksForGeeks", "For")) \ No newline at end of file diff --git a/String/to_roman.py b/String/to_roman.py index 1e9ab21..6897704 100644 --- a/String/to_roman.py +++ b/String/to_roman.py @@ -1,19 +1,19 @@ -def convertRoman(n): - #Code here - roman_values = [1000,900,500,400,100,90,50,40,10,9,5,4,1] - roman_string = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] - result = n - roman = "" - while result > 0: - for index,i in enumerate(roman_values): - if result >= i and result >= 0: - result -= i - roman += roman_string[index] - break - elif result <= 0: - break - return roman - -if __name__ == "__main__": - n = int(input()) - print(convertRoman(n)) +def convertRoman(n): + #Code here + roman_values = [1000,900,500,400,100,90,50,40,10,9,5,4,1] + roman_string = ["M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"] + result = n + roman = "" + while result > 0: + for index,i in enumerate(roman_values): + if result >= i and result >= 0: + result -= i + roman += roman_string[index] + break + elif result <= 0: + break + return roman + +if __name__ == "__main__": + n = int(input()) + print(convertRoman(n)) diff --git a/Tree/Check FullTree.py b/Tree/Check FullTree.py index 9fb9645..168cc8e 100644 --- a/Tree/Check FullTree.py +++ b/Tree/Check FullTree.py @@ -1,111 +1,111 @@ - -''' -# Node Class: -class Node: - def __init__(self,val): - self.data = val - self.left = None - self.right = None -''' - -# Return True if the given Binary Tree is a Full Binary Tree. Else return False -def height(node): - # left height - return height(node.left) -def isFullTree(root): - #code here - if not root or (root.left == root.right == None): - return True - else: - if root.right == None or root.left == None: - return False - elif isFullTree(root.left) and isFullTree(root.right): - return True - - - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -from collections import deque -# Tree Node -class Node: - def __init__(self, val): - self.right = None - self.data = val - self.left = None - -# Function to Build Tree -def buildTree(s): - #Corner Case - if(len(s)==0 or s[0]=="N"): - return None - - # Creating list of strings from input - # string after spliting by space - ip=list(map(str,s.split())) - - # Create the root of the tree - root=Node(int(ip[0])) - size=0 - q=deque() - - # Push the root to the queue - q.append(root) - size=size+1 - - # Starting from the second element - i=1 - while(size>0 and i=len(ip)): - break - currVal=ip[i] - - # If the right child is not null - if(currVal!="N"): - - # Create the right child for the current node - currNode.right=Node(int(currVal)) - - # Push it to the queue - q.append(currNode.right) - size=size+1 - i=i+1 - return root - - -if __name__=="__main__": - t=int(input()) - for _ in range(0,t): - s=input() - root=buildTree(s) - if isFullTree(root): - print(1) - else: - print(0) - - - - + +''' +# Node Class: +class Node: + def __init__(self,val): + self.data = val + self.left = None + self.right = None +''' + +# Return True if the given Binary Tree is a Full Binary Tree. Else return False +def height(node): + # left height + return height(node.left) +def isFullTree(root): + #code here + if not root or (root.left == root.right == None): + return True + else: + if root.right == None or root.left == None: + return False + elif isFullTree(root.left) and isFullTree(root.right): + return True + + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +from collections import deque +# Tree Node +class Node: + def __init__(self, val): + self.right = None + self.data = val + self.left = None + +# Function to Build Tree +def buildTree(s): + #Corner Case + if(len(s)==0 or s[0]=="N"): + return None + + # Creating list of strings from input + # string after spliting by space + ip=list(map(str,s.split())) + + # Create the root of the tree + root=Node(int(ip[0])) + size=0 + q=deque() + + # Push the root to the queue + q.append(root) + size=size+1 + + # Starting from the second element + i=1 + while(size>0 and i=len(ip)): + break + currVal=ip[i] + + # If the right child is not null + if(currVal!="N"): + + # Create the right child for the current node + currNode.right=Node(int(currVal)) + + # Push it to the queue + q.append(currNode.right) + size=size+1 + i=i+1 + return root + + +if __name__=="__main__": + t=int(input()) + for _ in range(0,t): + s=input() + root=buildTree(s) + if isFullTree(root): + print(1) + else: + print(0) + + + + # } Driver Code Ends \ No newline at end of file diff --git a/Tree/TreeTraversalFinder.py b/Tree/TreeTraversalFinder.py index 41408b4..25f8d84 100644 --- a/Tree/TreeTraversalFinder.py +++ b/Tree/TreeTraversalFinder.py @@ -1,96 +1,96 @@ -# Python program to construct tree using inorder and -# preorder traversals - -# A binary tree node -class Node: - - # Constructor to create a new node - def __init__(self, data): - self.data = data - self.left = None - self.right = None - - -"""Recursive function to construct binary of size len from -Inorder traversal in[] and Preorder traversal pre[]. Initial values -of inStrt and inEnd should be 0 and len -1. The function doesn't -do any error checking for cases where inorder and preorder -do not form a tree """ - - -def buildTree(inOrder, preOrder, inStrt, inEnd): - if (inStrt > inEnd): - return None - - # Pich current node from Preorder traversal using - # preIndex and increment preIndex - tNode = Node(preOrder[buildTree.preIndex]) - buildTree.preIndex += 1 - - # If this node has no children then return - if inStrt == inEnd: - return tNode - - # Else find the index of this node in Inorder traversal - inIndex = search(inOrder, inStrt, inEnd, tNode.data) - - # Using index in Inorder Traversal, construct left - # and right subtrees - tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex - 1) - tNode.right = buildTree(inOrder, preOrder, inIndex + 1, inEnd) - - return tNode - - -# UTILITY FUNCTIONS -# Function to find index of vaue in arr[start...end] -# The function assumes that value is rpesent in inOrder[] - -def search(arr, start, end, value): - for i in range(start, end + 1): - if arr[i] == value: - return i - - -def printInorder(node): - if node is None: - return - - # first recur on left child - printInorder(node.left) - - # then print the data of node - print(node.data, end=',') - - # now recur on right child - printInorder(node.right) - -def printPostOrder(node): - if node is None: - return - - # recur on left subtree - printPostOrder(node.left) - - # recur on right subtree - printPostOrder(node.right) - - # print the node value - print(node.data, end=',') - - -# Driver program to test above function -# inOrder = ['D', 'B', 'E', 'A', 'F', 'C'] -# preOrder = ['A', 'B', 'D', 'E', 'C', 'F'] -inOrder = list("LMNTOPQ") -preOrder = list("TMLNPOQ") -# Static variable preIndex -buildTree.preIndex = 0 -root = buildTree(inOrder, preOrder, 0, len(inOrder) - 1) - -# Let us test the build tree by priting Inorder traversal -print("Inorder traversal of the constructed tree is") -printInorder(root) -print("\nPost-order traversal:") -printPostOrder(root) -# This code is contributed by Nikhil Kumar Singh(nickzuck_007) +# Python program to construct tree using inorder and +# preorder traversals + +# A binary tree node +class Node: + + # Constructor to create a new node + def __init__(self, data): + self.data = data + self.left = None + self.right = None + + +"""Recursive function to construct binary of size len from +Inorder traversal in[] and Preorder traversal pre[]. Initial values +of inStrt and inEnd should be 0 and len -1. The function doesn't +do any error checking for cases where inorder and preorder +do not form a tree """ + + +def buildTree(inOrder, preOrder, inStrt, inEnd): + if (inStrt > inEnd): + return None + + # Pich current node from Preorder traversal using + # preIndex and increment preIndex + tNode = Node(preOrder[buildTree.preIndex]) + buildTree.preIndex += 1 + + # If this node has no children then return + if inStrt == inEnd: + return tNode + + # Else find the index of this node in Inorder traversal + inIndex = search(inOrder, inStrt, inEnd, tNode.data) + + # Using index in Inorder Traversal, construct left + # and right subtrees + tNode.left = buildTree(inOrder, preOrder, inStrt, inIndex - 1) + tNode.right = buildTree(inOrder, preOrder, inIndex + 1, inEnd) + + return tNode + + +# UTILITY FUNCTIONS +# Function to find index of vaue in arr[start...end] +# The function assumes that value is rpesent in inOrder[] + +def search(arr, start, end, value): + for i in range(start, end + 1): + if arr[i] == value: + return i + + +def printInorder(node): + if node is None: + return + + # first recur on left child + printInorder(node.left) + + # then print the data of node + print(node.data, end=',') + + # now recur on right child + printInorder(node.right) + +def printPostOrder(node): + if node is None: + return + + # recur on left subtree + printPostOrder(node.left) + + # recur on right subtree + printPostOrder(node.right) + + # print the node value + print(node.data, end=',') + + +# Driver program to test above function +# inOrder = ['D', 'B', 'E', 'A', 'F', 'C'] +# preOrder = ['A', 'B', 'D', 'E', 'C', 'F'] +inOrder = list("LMNTOPQ") +preOrder = list("TMLNPOQ") +# Static variable preIndex +buildTree.preIndex = 0 +root = buildTree(inOrder, preOrder, 0, len(inOrder) - 1) + +# Let us test the build tree by priting Inorder traversal +print("Inorder traversal of the constructed tree is") +printInorder(root) +print("\nPost-order traversal:") +printPostOrder(root) +# This code is contributed by Nikhil Kumar Singh(nickzuck_007) diff --git a/Tree/check_symmetric_tree.py b/Tree/check_symmetric_tree.py index 25a6e42..f904b7c 100644 --- a/Tree/check_symmetric_tree.py +++ b/Tree/check_symmetric_tree.py @@ -1,97 +1,97 @@ - -# return true/false denoting whether the tree is Symmetric or not -def condition(root1, root2): - if root1 == root2 is None: - return True - - if root1 is not None and root2 is not None: - if root1.data == root2.data: - return (condition(root1.left, root2.right) and condition(root1.right, root2.left)) - - return False - - -def isSymmetric(root): - return condition(root, root) - - -# { -# Driver Code Starts -# Initial Template for Python 3 - -# Contributed by Sudarshan Sharma -from collections import deque -# Tree Node -class Node: - def __init__(self, val): - self.right = None - self.data = val - self.left = None - -# Function to Build Tree -def buildTree(s): - # Corner Case - if(len(s)==0 or s[0]=="N"): - return None - - # Creating list of strings from input - # string after spliting by space - ip =list(map(str ,s.split())) - - # Create the root of the tree - root =Node(int(ip[0])) - size =0 - q=deque() - - # Push the root to the queue - q.append(root) - size=size +1 - - # Starting from the second element - i=1 - while(size>0 and i= len(ip)): - break - currVal=ip[ i ] - - # If the right child is not null - if(currVal!="N ") : - # Create the right child for the current node - currNode.right=Node(int(currVal)) - - # Push it to the queue - q.append(currNode.right) - size=size +1 - i=i+1 - return root - - -if __name__=="_ _m ain__": - t=int ( input()) - for _ in range(0,t): - s=input() - root=buildTree(s) - if isSymmetric(root): - print("True") - else: - print("False") - + +# return true/false denoting whether the tree is Symmetric or not +def condition(root1, root2): + if root1 == root2 is None: + return True + + if root1 is not None and root2 is not None: + if root1.data == root2.data: + return (condition(root1.left, root2.right) and condition(root1.right, root2.left)) + + return False + + +def isSymmetric(root): + return condition(root, root) + + +# { +# Driver Code Starts +# Initial Template for Python 3 + +# Contributed by Sudarshan Sharma +from collections import deque +# Tree Node +class Node: + def __init__(self, val): + self.right = None + self.data = val + self.left = None + +# Function to Build Tree +def buildTree(s): + # Corner Case + if(len(s)==0 or s[0]=="N"): + return None + + # Creating list of strings from input + # string after spliting by space + ip =list(map(str ,s.split())) + + # Create the root of the tree + root =Node(int(ip[0])) + size =0 + q=deque() + + # Push the root to the queue + q.append(root) + size=size +1 + + # Starting from the second element + i=1 + while(size>0 and i= len(ip)): + break + currVal=ip[ i ] + + # If the right child is not null + if(currVal!="N ") : + # Create the right child for the current node + currNode.right=Node(int(currVal)) + + # Push it to the queue + q.append(currNode.right) + size=size +1 + i=i+1 + return root + + +if __name__=="_ _m ain__": + t=int ( input()) + for _ in range(0,t): + s=input() + root=buildTree(s) + if isSymmetric(root): + print("True") + else: + print("False") + # } Driver Code Ends \ No newline at end of file diff --git a/Tree/height_of_a_binary_tree.py b/Tree/height_of_a_binary_tree.py index 1876f0f..eb87497 100644 --- a/Tree/height_of_a_binary_tree.py +++ b/Tree/height_of_a_binary_tree.py @@ -1,101 +1,101 @@ - -''' -# Node Class: -class Node: - def _init_(self,val): - self.data = val - self.left = None - self.right = None - ''' - -# return the Height of the given Binary Tree -def height(root): - # code here - if root: - return max(height(root.left), height(root.right)) + 1 - else: - return 0 - - - -#{ -# Driver Code Starts -#Initial Template for Python 3 - -#Contributed by Sudarshan Sharma -from collections import deque -# Tree Node -class Node: - def __init__(self, val): - self.right = None - self.data = val - self.left = None - -# Function to Build Tree -def buildTree(s): - #Corner Case - if(len(s)==0 or s[0]=="N"): - return None - - # Creating list of strings from input - # string after spliting by space - ip=list(map(str,s.split())) - - # Create the root of the tree - root=Node(int(ip[0])) - size=0 - q=deque() - - # Push the root to the queue - q.append(root) - size=size+1 - - # Starting from the second element - i=1 - while(size>0 and i=len(ip)): - break - currVal=ip[i] - - # If the right child is not null - if(currVal!="N"): - - # Create the right child for the current node - currNode.right=Node(int(currVal)) - - # Push it to the queue - q.append(currNode.right) - size=size+1 - i=i+1 - return root - - -if __name__=="__main__": - t=int(input()) - for _ in range(0,t): - s=input() - root=buildTree(s) - print(height(root)) - - - + +''' +# Node Class: +class Node: + def _init_(self,val): + self.data = val + self.left = None + self.right = None + ''' + +# return the Height of the given Binary Tree +def height(root): + # code here + if root: + return max(height(root.left), height(root.right)) + 1 + else: + return 0 + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +#Contributed by Sudarshan Sharma +from collections import deque +# Tree Node +class Node: + def __init__(self, val): + self.right = None + self.data = val + self.left = None + +# Function to Build Tree +def buildTree(s): + #Corner Case + if(len(s)==0 or s[0]=="N"): + return None + + # Creating list of strings from input + # string after spliting by space + ip=list(map(str,s.split())) + + # Create the root of the tree + root=Node(int(ip[0])) + size=0 + q=deque() + + # Push the root to the queue + q.append(root) + size=size+1 + + # Starting from the second element + i=1 + while(size>0 and i=len(ip)): + break + currVal=ip[i] + + # If the right child is not null + if(currVal!="N"): + + # Create the right child for the current node + currNode.right=Node(int(currVal)) + + # Push it to the queue + q.append(currNode.right) + size=size+1 + i=i+1 + return root + + +if __name__=="__main__": + t=int(input()) + for _ in range(0,t): + s=input() + root=buildTree(s) + print(height(root)) + + + # } Driver Code Ends \ No newline at end of file diff --git a/Tree/inorder_traversal.cpp b/Tree/inorder_traversal.cpp index 294852f..f803d6c 100644 --- a/Tree/inorder_traversal.cpp +++ b/Tree/inorder_traversal.cpp @@ -1,133 +1,133 @@ -#include -using namespace std; - -// Tree Node -struct Node { - int data; - Node *left; - Node *right; - - Node(int val) { - data = val; - left = right = NULL; - } -}; - -vector inOrder(struct Node *root); - -// Function to Build Tree -Node* buildTree(string str) -{ - // Corner Case - if(str.length() == 0 || str[0] == 'N') - return NULL; - - // Creating vector of strings from input - // string after spliting by space - vector ip; - - istringstream iss(str); - for(string str; iss >> str; ) - ip.push_back(str); - - // Create the root of the tree - Node* root = new Node(stoi(ip[0])); - - // Push the root to the queue - queue queue; - queue.push(root); - - // Starting from the second element - int i = 1; - while(!queue.empty() && i < ip.size()) { - - // Get and remove the front of the queue - Node* currNode = queue.front(); - queue.pop(); - - // Get the current node's value from the string - string currVal = ip[i]; - - // If the left child is not null - if(currVal != "N") { - - // Create the left child for the current node - currNode->left = new Node(stoi(currVal)); - - // Push it to the queue - queue.push(currNode->left); - } - - // For the right child - i++; - if(i >= ip.size()) - break; - currVal = ip[i]; - - // If the right child is not null - if(currVal != "N") { - - // Create the right child for the current node - currNode->right = new Node(stoi(currVal)); - - // Push it to the queue - queue.push(currNode->right); - } - i++; - } - - return root; -} - - -int main() { - int t; - string tc; - getline(cin,tc); - t=stoi(tc); - while(t--) - { - string s; - getline(cin,s); - Node* root = buildTree(s); - - vector res = inOrder(root); - for (int i = 0; i < res.size (); i++) - cout << res[i] << " "; - cout << endl; - } - return 0; -} - - -// } Driver Code Ends - - -/* A binary tree node has data, pointer to left child - and a pointer to right child -struct Node { - int data; - Node *left; - Node *right; - - Node(int val) { - data = val; - left = right = NULL; - } -}; */ - - -// Return a vector containing the inorder traversal of the tree - -void inorderFun(Node *root, vector &res) -{ -if (root == NULL)return; -inorderFun(root->left, res); -res.push_back (root->data); -inorderFun(root->right, res); -} -vector inOrder(struct Node *root) { -vector res; -inorderFun(root, res); -return res; -} +#include +using namespace std; + +// Tree Node +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; + +vector inOrder(struct Node *root); + +// Function to Build Tree +Node* buildTree(string str) +{ + // Corner Case + if(str.length() == 0 || str[0] == 'N') + return NULL; + + // Creating vector of strings from input + // string after spliting by space + vector ip; + + istringstream iss(str); + for(string str; iss >> str; ) + ip.push_back(str); + + // Create the root of the tree + Node* root = new Node(stoi(ip[0])); + + // Push the root to the queue + queue queue; + queue.push(root); + + // Starting from the second element + int i = 1; + while(!queue.empty() && i < ip.size()) { + + // Get and remove the front of the queue + Node* currNode = queue.front(); + queue.pop(); + + // Get the current node's value from the string + string currVal = ip[i]; + + // If the left child is not null + if(currVal != "N") { + + // Create the left child for the current node + currNode->left = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->left); + } + + // For the right child + i++; + if(i >= ip.size()) + break; + currVal = ip[i]; + + // If the right child is not null + if(currVal != "N") { + + // Create the right child for the current node + currNode->right = new Node(stoi(currVal)); + + // Push it to the queue + queue.push(currNode->right); + } + i++; + } + + return root; +} + + +int main() { + int t; + string tc; + getline(cin,tc); + t=stoi(tc); + while(t--) + { + string s; + getline(cin,s); + Node* root = buildTree(s); + + vector res = inOrder(root); + for (int i = 0; i < res.size (); i++) + cout << res[i] << " "; + cout << endl; + } + return 0; +} + + +// } Driver Code Ends + + +/* A binary tree node has data, pointer to left child + and a pointer to right child +struct Node { + int data; + Node *left; + Node *right; + + Node(int val) { + data = val; + left = right = NULL; + } +}; */ + + +// Return a vector containing the inorder traversal of the tree + +void inorderFun(Node *root, vector &res) +{ +if (root == NULL)return; +inorderFun(root->left, res); +res.push_back (root->data); +inorderFun(root->right, res); +} +vector inOrder(struct Node *root) { +vector res; +inorderFun(root, res); +return res; +} diff --git a/Tree/nodeWithProducts.py b/Tree/nodeWithProducts.py index f1fc161..2ef28b4 100644 --- a/Tree/nodeWithProducts.py +++ b/Tree/nodeWithProducts.py @@ -1,59 +1,59 @@ -class Tree: - def __init__(self, data) -> None: - self.left = None - self.right = None - self.data = data - -def preOrder(node, p=None): - if not p: - p = [] - if not node: - return p - p.append(node.data) - preOrder(node.left, p) - preOrder(node.right, p) - return p - -def inOrder(root): - if not root: - return - inOrder(root.left) - print(root.data, end=" ") - inOrder(root.right) - -def updateTree(root, p): - if not root: - return - root.data = int(p / root.data) - updateTree(root.left, p) - updateTree(root.right, p) - -def create_tree(): - # tree = Tree(15) - # tree.left = Tree(10) - # tree.right = Tree(20) - # tree.left.left = Tree(8) - # tree.left.right =Tree(12) - # tree.right.left = Tree(16) - # tree.right.right = Tree(25) - tree = Tree(1) - tree.left = Tree(2) - tree.right = Tree(3) - - tree.right.left = Tree(4) - tree.right.right = Tree(5) - - print(f"Initial Inorder traversal:") - inOrder(tree) - - pre_ordered = preOrder(tree) - mul = 1 - for i in pre_ordered: - mul *= i - # print("multiplication of all nodes result =", mul) - updateTree(tree, mul) - print(f"\n\nAfter updating inorder traversal:") - inOrder(tree) - - +class Tree: + def __init__(self, data) -> None: + self.left = None + self.right = None + self.data = data + +def preOrder(node, p=None): + if not p: + p = [] + if not node: + return p + p.append(node.data) + preOrder(node.left, p) + preOrder(node.right, p) + return p + +def inOrder(root): + if not root: + return + inOrder(root.left) + print(root.data, end=" ") + inOrder(root.right) + +def updateTree(root, p): + if not root: + return + root.data = int(p / root.data) + updateTree(root.left, p) + updateTree(root.right, p) + +def create_tree(): + # tree = Tree(15) + # tree.left = Tree(10) + # tree.right = Tree(20) + # tree.left.left = Tree(8) + # tree.left.right =Tree(12) + # tree.right.left = Tree(16) + # tree.right.right = Tree(25) + tree = Tree(1) + tree.left = Tree(2) + tree.right = Tree(3) + + tree.right.left = Tree(4) + tree.right.right = Tree(5) + + print(f"Initial Inorder traversal:") + inOrder(tree) + + pre_ordered = preOrder(tree) + mul = 1 + for i in pre_ordered: + mul *= i + # print("multiplication of all nodes result =", mul) + updateTree(tree, mul) + print(f"\n\nAfter updating inorder traversal:") + inOrder(tree) + + create_tree() \ No newline at end of file diff --git a/codechef/warmup_and_complexity/answer_to_everything.py b/codechef/warmup_and_complexity/answer_to_everything.py index ccaab72..05ef346 100644 --- a/codechef/warmup_and_complexity/answer_to_everything.py +++ b/codechef/warmup_and_complexity/answer_to_everything.py @@ -1,5 +1,5 @@ -while True: - x = int(input()) - if x==42: - break +while True: + x = int(input()) + if x==42: + break print (x) \ No newline at end of file diff --git a/codechef/warmup_and_complexity/lapindromes.py b/codechef/warmup_and_complexity/lapindromes.py index b1f8efa..894e8b0 100644 --- a/codechef/warmup_and_complexity/lapindromes.py +++ b/codechef/warmup_and_complexity/lapindromes.py @@ -1,15 +1,15 @@ -t = int(input()) -while t: - test_string = input() - middle_point = len(test_string)//2 - if len(test_string) % 2 == 0: # string length is even - f_half = test_string[:middle_point] - s_half = test_string[middle_point:] - else: - f_half = test_string[:middle_point] - s_half = test_string[middle_point+1:] - if sorted(f_half) == sorted(s_half): - print('YES') - else: - print('NO') - t -= 1 +t = int(input()) +while t: + test_string = input() + middle_point = len(test_string)//2 + if len(test_string) % 2 == 0: # string length is even + f_half = test_string[:middle_point] + s_half = test_string[middle_point:] + else: + f_half = test_string[:middle_point] + s_half = test_string[middle_point+1:] + if sorted(f_half) == sorted(s_half): + print('YES') + else: + print('NO') + t -= 1 diff --git a/codechef/warmup_and_complexity/reverse_the_number.py b/codechef/warmup_and_complexity/reverse_the_number.py index b161278..bb00fa2 100644 --- a/codechef/warmup_and_complexity/reverse_the_number.py +++ b/codechef/warmup_and_complexity/reverse_the_number.py @@ -1,5 +1,5 @@ -t = int(input()) -while t: - n = input() - print(n[::-1]) +t = int(input()) +while t: + n = input() + print(n[::-1]) t-= 1 \ No newline at end of file diff --git a/images/image.txt b/images/image.txt index f1d5146..379a65e 100644 --- a/images/image.txt +++ b/images/image.txt @@ -1 +1 @@ -All image files used in this project. +All image files used in this project. diff --git a/mathematical/bricks.py b/mathematical/bricks.py index e9f40d3..2a9e823 100644 --- a/mathematical/bricks.py +++ b/mathematical/bricks.py @@ -1,28 +1,28 @@ -def make_bricks(small, big, goal): - big_rem = goal // 5 - if (goal - (big_rem * 5)) <= small and big_rem <= big: - return True - elif big_rem > big and (goal - 5*big <= small): - return True - return False - -if __name__ == '__main__': - tests = [ - (1,4,11), - (3,1,8), - (3,1,9), - (3,2,10), - (3,2,9), - (3,2,8), - (6,1,11), - (6,0,11), - (0,3,10), - (3,1,7), - (1,1,7), - (2,1,7), - (1,4,12), - (7,1,11) - ] - for test in tests: - res = make_bricks(*test) +def make_bricks(small, big, goal): + big_rem = goal // 5 + if (goal - (big_rem * 5)) <= small and big_rem <= big: + return True + elif big_rem > big and (goal - 5*big <= small): + return True + return False + +if __name__ == '__main__': + tests = [ + (1,4,11), + (3,1,8), + (3,1,9), + (3,2,10), + (3,2,9), + (3,2,8), + (6,1,11), + (6,0,11), + (0,3,10), + (3,1,7), + (1,1,7), + (2,1,7), + (1,4,12), + (7,1,11) + ] + for test in tests: + res = make_bricks(*test) print(test, "=", res) \ No newline at end of file diff --git a/mathematical/catandMouse.py b/mathematical/catandMouse.py index 5f2bb26..ff5860e 100644 --- a/mathematical/catandMouse.py +++ b/mathematical/catandMouse.py @@ -1,37 +1,37 @@ -""" -problem link: https://www.hackerrank.com/challenges/cats-and-a-mouse/problem -"""n3 - -import math -import os -import random -import re -import sys - -# Complete the catAndMouse function below. -def catAndMouse(x, y, z): - cat_a = abs(z-x) - cat_b = abs(y-z) - if cat_a > cat_b: - return "Cat B" - elif cat_b > cat_a: - return "Cat A" - else: - return "Mouse C" - - -if __name__ == '__main__': - - q = int(input()) - - for q_itr in range(q): - xyz = input().split() - - x = int(xyz[0]) - - y = int(xyz[1]) - - z = int(xyz[2]) - - result = catAndMouse(x, y, z) - print(result) +""" +problem link: https://www.hackerrank.com/challenges/cats-and-a-mouse/problem +"""n3 + +import math +import os +import random +import re +import sys + +# Complete the catAndMouse function below. +def catAndMouse(x, y, z): + cat_a = abs(z-x) + cat_b = abs(y-z) + if cat_a > cat_b: + return "Cat B" + elif cat_b > cat_a: + return "Cat A" + else: + return "Mouse C" + + +if __name__ == '__main__': + + q = int(input()) + + for q_itr in range(q): + xyz = input().split() + + x = int(xyz[0]) + + y = int(xyz[1]) + + z = int(xyz[2]) + + result = catAndMouse(x, y, z) + print(result) diff --git a/mathematical/counting_valley.py b/mathematical/counting_valley.py index 064999a..0c97bcb 100644 --- a/mathematical/counting_valley.py +++ b/mathematical/counting_valley.py @@ -1,37 +1,37 @@ -#!/bin/python3 - -import math -import os -import random -import re -import sys - -# -# Complete the 'countingValleys' function below. -# -# The function is expected to return an INTEGER. -# The function accepts following parameters: -# 1. INTEGER steps -# 2. STRING path -# - -def countingValleys(steps, path): - last_state = path[0] - count = 0 - u_count = 0 - d_count = 0 - for state in path[1:]: - if last_state != state: # state change - if state == 'D': - count += 1 - print("state change to D, count increased to ", count) - last_state = state - return count - - - -if __name__ == '__main__': - steps = int(input().strip()) - path = input() - result = countingValleys(steps, path) - print(result) +#!/bin/python3 + +import math +import os +import random +import re +import sys + +# +# Complete the 'countingValleys' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER steps +# 2. STRING path +# + +def countingValleys(steps, path): + last_state = path[0] + count = 0 + u_count = 0 + d_count = 0 + for state in path[1:]: + if last_state != state: # state change + if state == 'D': + count += 1 + print("state change to D, count increased to ", count) + last_state = state + return count + + + +if __name__ == '__main__': + steps = int(input().strip()) + path = input() + result = countingValleys(steps, path) + print(result) diff --git a/mathematical/factorial.java b/mathematical/factorial.java index 1ee51d0..7c60522 100644 --- a/mathematical/factorial.java +++ b/mathematical/factorial.java @@ -1,52 +1,52 @@ -import java.util.Arrays; -import java.util.Scanner; - -public class factorial { - public static void main(String[] args) { - Scanner sc = new Scanner(System.in); - - int T = sc.nextInt(); - while (T-- > 0){ - Solution obj = new Solution(); - int N; - - N = sc.nextInt(); - - System.out.println(obj.factorial(N)); - } - } -} -class Solution{ - int multiply(int x, int[] res, int res_size){ - int carry = 0; - for (int i=0; i < res_size; i++){ - int prod = res[i] * x + carry; - res[i] = prod % 10; - carry = prod/10; - } - - while (carry != 0){ - res[res_size] = carry % 10; - carry /= 10; - res_size ++; - } - return res_size; - } - - public long factorial(int N){ - int[] res = new int[1000]; - - res[0] = 1; - int res_size = 1; - - for (int x=2; x<= N; x++){ - res_size = multiply(x, res, res_size); - } - - long fact = 0; - for (int index = res_size - 1; index >= 0; index--){ - fact = (long) Math.pow(10,index) * res[index] + fact; - } - return fact; - } +import java.util.Arrays; +import java.util.Scanner; + +public class factorial { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + + int T = sc.nextInt(); + while (T-- > 0){ + Solution obj = new Solution(); + int N; + + N = sc.nextInt(); + + System.out.println(obj.factorial(N)); + } + } +} +class Solution{ + int multiply(int x, int[] res, int res_size){ + int carry = 0; + for (int i=0; i < res_size; i++){ + int prod = res[i] * x + carry; + res[i] = prod % 10; + carry = prod/10; + } + + while (carry != 0){ + res[res_size] = carry % 10; + carry /= 10; + res_size ++; + } + return res_size; + } + + public long factorial(int N){ + int[] res = new int[1000]; + + res[0] = 1; + int res_size = 1; + + for (int x=2; x<= N; x++){ + res_size = multiply(x, res, res_size); + } + + long fact = 0; + for (int index = res_size - 1; index >= 0; index--){ + fact = (long) Math.pow(10,index) * res[index] + fact; + } + return fact; + } } \ No newline at end of file diff --git a/mathematical/noOfopendoors.py b/mathematical/noOfopendoors.py index ae2d89f..25a8410 100644 --- a/mathematical/noOfopendoors.py +++ b/mathematical/noOfopendoors.py @@ -1,16 +1,16 @@ -""" -problem link: https://practice.geeksforgeeks.org/problems/number-of-open-doors1552/1 -""" -class Solution: - def noOfOpenDoors(self, N): - return math.floor(math.sqrt(N)) - - -import math -if __name__ == '__main__': - t = int(input()) - for _ in range(t): - N = int(input()) - ob = Solution() - print(ob.noOfOpenDoors(N)) - +""" +problem link: https://practice.geeksforgeeks.org/problems/number-of-open-doors1552/1 +""" +class Solution: + def noOfOpenDoors(self, N): + return math.floor(math.sqrt(N)) + + +import math +if __name__ == '__main__': + t = int(input()) + for _ in range(t): + N = int(input()) + ob = Solution() + print(ob.noOfOpenDoors(N)) + diff --git a/mathematical/turnPages.py b/mathematical/turnPages.py index 5935f84..1ca103c 100644 --- a/mathematical/turnPages.py +++ b/mathematical/turnPages.py @@ -1,38 +1,38 @@ -""" -problem link:https://www.hackerrank.com/challenges/drawing-book/problem -""" - -import math -import os -import random -import re -import sys - -# -# Complete the 'pageCount' function below. -# -# The function is expected to return an INTEGER. -# The function accepts following parameters: -# 1. INTEGER n -# 2. INTEGER p -# - -def pageCount(n, p): - if p == n or p==n or (n%2 != 0 and p==(n-1)): - return 0 - else: - if p <= n/2: - return p//2 - else: - return (n//2)-(p//2) - - -if __name__ == '__main__': - - n = int(input().strip()) - - p = int(input().strip()) - - result = pageCount(n, p) - - print(result) +""" +problem link:https://www.hackerrank.com/challenges/drawing-book/problem +""" + +import math +import os +import random +import re +import sys + +# +# Complete the 'pageCount' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER n +# 2. INTEGER p +# + +def pageCount(n, p): + if p == n or p==n or (n%2 != 0 and p==(n-1)): + return 0 + else: + if p <= n/2: + return p//2 + else: + return (n//2)-(p//2) + + +if __name__ == '__main__': + + n = int(input().strip()) + + p = int(input().strip()) + + result = pageCount(n, p) + + print(result)