From 799dfc26ad731da90ddfba3369e01bc575053930 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Thu, 21 Jan 2021 23:56:47 +0530 Subject: [PATCH 01/49] Paint House! --- .../Dynamic_Programming/paint-house.py | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Python/Interviewbit/Dynamic_Programming/paint-house.py diff --git a/Python/Interviewbit/Dynamic_Programming/paint-house.py b/Python/Interviewbit/Dynamic_Programming/paint-house.py new file mode 100644 index 0000000..f9d3f35 --- /dev/null +++ b/Python/Interviewbit/Dynamic_Programming/paint-house.py @@ -0,0 +1,52 @@ +""" +Problem Description +There are a row of N houses, each house can be painted with one of the three colors: red, blue or green. +The cost of painting each house with a certain color is different. You have to paint all the houses such that no two adjacent houses have the same color. +The cost of painting each house with a certain color is represented by a N x 3 cost matrix A. +For example, A[0][0] is the cost of painting house 0 with color red; A[1][2] is the cost of painting house 1 with color green, and so on. +Find the minimum total cost to paint all houses. + +Problem Constraints +1 <= N <= 105 +1 <= A[i][j] <= 103 + +Input Format +First and only argument is an 2D integer matrix A of size N x 3 denoting the cost to paint the houses. + +Output Format +Return an integer denoting the minimum total cost to paint all houses. + +Example Input +Input 1: +A = [ [1, 2, 3] + [10, 11, 12] + ] + +Example Output +Output 1: +12 + +Example Explanation +Explanation 1: +Paint house 1 with red and house 2 with green i.e A[0][0] + A[1][1] = 1 + 11 = 12 +""" +class Solution: + # @param A : list of list of integers + # @return an integer + def solve(self, A): + r = g = b = 0 + + for i in range(1,len(A)+1): + r, g, b = min(g, b) + A[i-1][0], min(r, b) + A[i-1][1], min(r, g) + A[i-1][2] + + return min(r, g, b) + + def solve1(self, A): + dp = [[0, 0, 0] for _ in range(len(A)+1)] + + for i in range(1,len(A)+1): + dp[i][0] = min(dp[i-1][1], dp[i-1][2]) + A[i-1][0] + dp[i][1] = min(dp[i-1][0], dp[i-1][2]) + A[i-1][1] + dp[i][2] = min(dp[i-1][0], dp[i-1][1]) + A[i-1][2] + + return min(dp[-1][0], dp[-1][1], dp[-1][2]) \ No newline at end of file From d2be43259d3d132db59b6de73a4ae74a9f77fcfb Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Tue, 26 Jan 2021 13:17:28 +0530 Subject: [PATCH 02/49] Maximum Path in Triangle --- .../maximum-path-in-triangle.py | 91 +++++++++++++++++++ 1 file changed, 91 insertions(+) create mode 100644 Python/Interviewbit/Dynamic_Programming/maximum-path-in-triangle.py diff --git a/Python/Interviewbit/Dynamic_Programming/maximum-path-in-triangle.py b/Python/Interviewbit/Dynamic_Programming/maximum-path-in-triangle.py new file mode 100644 index 0000000..9ed9b80 --- /dev/null +++ b/Python/Interviewbit/Dynamic_Programming/maximum-path-in-triangle.py @@ -0,0 +1,91 @@ +""" +Problem Link: https://www.interviewbit.com/problems/maximum-path-in-triangle/ + +Problem Description +Given a 2D integer array A of size N * N representing a triangle of numbers. +Find the maximum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. + +NOTE: +Adjacent cells to cell (i,j) are only (i+1,j) and (i+1,j+1) +Row i contains i integer and n-i zeroes for all i in [1,n] where zeroes represents empty cells. + +Problem Constraints +0 <= N <= 1000 +0 <= A[i][j] <= 1000 + +Input Format +First and only argument is an 2D integer array A of size N * N. + +Output Format +Return a single integer denoting the maximum path sum from top to bottom in the triangle. + +Example Input +Input 1: +A = [ + [3, 0, 0, 0] + [7, 4, 0, 0] + [2, 4, 6, 0] + [8, 5, 9, 3] +] + +Input 2: +A = [ + [8, 0, 0, 0] + [4, 4, 0, 0] + [2, 2, 6, 0] + [1, 1, 1, 1] +] + +Example Output +Output 1: +23 + +Output 2: +19 + +Example Explanation +Explanation 1: +Given triangle looks like: 3 + 7 4 + 2 4 6 + 8 5 9 3 +So max path is (3 + 7 + 4 + 9) = 23 + +Explanation 1: +Given triangle looks like: 8 + 4 4 + 2 2 6 + 1 1 1 1 +So max path is (8 + 4 + 6 + 1) = 19 +""" +class Solution: + # @param A : list of list of integers + # @return an integer + def solve(self, A): + if not A: + return 0 + + dp = [[0] * len(A) for _ in range(len(A))] + dp[-1] = A[-1] + for i in range(len(A)-2, -1, -1): + for j in range(len(A)-2, -1, -1): + dp[i][j] = max(dp[i+1][j], dp[i+1][j+1]) + A[i][j] + + return dp[0][0] + + +class Solution1: + # @param A : list of list of integers + # @return an integer + def solve(self, A): + if not A: + return 0 + + cur = [0] * len(A) + prev = A[-1] + for i in range(len(A)-2, -1, -1): + for j in range(i+1): + cur[j] = max(prev[j], prev[j+1]) + A[i][j] + prev = cur + + return cur[0] or prev[0] \ No newline at end of file From 51604bf562d10affe088dc4a626c44ae6a509502 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Wed, 12 May 2021 19:13:44 +0530 Subject: [PATCH 03/49] Longest K unique characters substring --- .../longest-k-unique-characters-substring.py | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 Python/GeeksforGeeks/longest-k-unique-characters-substring.py diff --git a/Python/GeeksforGeeks/longest-k-unique-characters-substring.py b/Python/GeeksforGeeks/longest-k-unique-characters-substring.py new file mode 100644 index 0000000..cd76a8f --- /dev/null +++ b/Python/GeeksforGeeks/longest-k-unique-characters-substring.py @@ -0,0 +1,70 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/longest-k-unique-characters-substring0853/1 + +Given a string you need to print the size of the longest possible substring that has exactly K unique characters. +If there is no possible substring then print -1. + +Example 1: +Input: +S = "aabacbebebe", K = 3 +Output: 7 +Explanation: "cbebebe" is the longest +substring with K distinct characters. + +Example 2: +Input: +S = "aaaa", K = 2 +Output: -1 +Explanation: There's no substring with K +distinct characters. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function longestKSubstr() which takes the string S +and an integer K as input and returns the length of the longest substring with exactly K distinct characters. +If there is no substring with exactly K distinct characters then return -1. + +Expected Time Complexity: O(|S|). +Expected Auxiliary Space: O(1). + +Constraints: +1<=|S|<=105 +1<=K<=105 +""" +class Solution: + + def longestKSubstr(self, s, k): + char_count = {} + ans = -1 + + start_index = 0 + for index, char in enumerate(s): + char_count[char] = char_count.get(char, 0) + 1 + + if len(char_count) == k: + ans = max(ans, index - start_index + 1) + + if len(char_count) == k+1: + while len(char_count) > k and start_index < index: + char_count[s[start_index]] -= 1 + + if char_count[s[start_index]] == 0: + del char_count[s[start_index]] + + start_index += 1 + ans = max(ans, index - start_index + 1) + + return ans + +if __name__ == '__main__': + + t = int(input()) + + for _ in range(t): + s = input() + k = int(input()) + + solObj = Solution() + + ans = solObj.longestKSubstr(s, k) + + print(ans) From 0832f6fcd52ba19a98f76ef186d9df62fe4c8d7d Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Thu, 13 May 2021 13:31:55 +0530 Subject: [PATCH 04/49] Min distance between two given nodes of a Binary Tree --- ...etween-two-given-nodes-of-a-binary-tree.py | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 Python/GeeksforGeeks/min-distance-between-two-given-nodes-of-a-binary-tree.py diff --git a/Python/GeeksforGeeks/min-distance-between-two-given-nodes-of-a-binary-tree.py b/Python/GeeksforGeeks/min-distance-between-two-given-nodes-of-a-binary-tree.py new file mode 100644 index 0000000..03ccf75 --- /dev/null +++ b/Python/GeeksforGeeks/min-distance-between-two-given-nodes-of-a-binary-tree.py @@ -0,0 +1,163 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/min-distance-between-two-given-nodes-of-a-binary-tree/1# + +Given a binary tree and two node values your task is to find the minimum distance between them. + +Example 1: +Input: + 1 + / \ + 2 3 +a = 2, b = 3 +Output: 2 +Explanation: The tree formed is: + 1 + / \ + 2 3 + +We need the distance between 2 and 3. +Being at node 2, we need to take two +steps ahead in order to reach node 3. +The path followed will be: +2 -> 1 -> 3. Hence, the result is 2. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function findDist() which takes the root node +of the Tree and the two node values a and b as input parameters and returns the minimum distance between the nodes +represented by the two given node values. +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(Height of the Tree). + +Constraints: +1 <= Number of nodes <= 104 +1 <= Data of a node <= 105 +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. +""" +#User function Template for python3 + +''' +# Node Class: +class Node: + def __init__(self,val): + self.data = val + self.left = None + self.right = None +''' +def findDist(root,a,b): + + + def find_node(root, val, parents): + if not root: + return [] + + if root.data == val: + parents.append(root.data) + return parents + + return find_node(root.left, val, parents + [root.data]) or find_node(root.right, val, parents + [root.data]) + + a_parents = find_node(root, a, []) + b_parents = find_node(root, b, []) + + index = 0 + + while index < len(a_parents) and index < len(b_parents): + if a_parents[index] != b_parents[index]: + break + index += 1 + + return (len(a_parents) - index) + (len(b_parents) - index) + + + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +import sys +sys.setrecursionlimit(50000) +from collections import deque +# Tree Node +class Node: + def __init__(self, val): + self.right = None + self.data = val + self.left = None + +''' +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) + a, b=map(int, input().split()) + print(findDist(root, a, b)) + +# } Driver Code Ends \ No newline at end of file From 578cdfc29bcc470a35856b713e335f942c768bb9 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Fri, 14 May 2021 20:42:50 +0530 Subject: [PATCH 05/49] Count the number of contiguous increasing and decreasing subsequences in a sequence --- ...d-decreasing-subsequences-in-a-sequence.py | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Python/GeeksforGeeks/count-the-number-of-contiguous-increasing-and-decreasing-subsequences-in-a-sequence.py diff --git a/Python/GeeksforGeeks/count-the-number-of-contiguous-increasing-and-decreasing-subsequences-in-a-sequence.py b/Python/GeeksforGeeks/count-the-number-of-contiguous-increasing-and-decreasing-subsequences-in-a-sequence.py new file mode 100644 index 0000000..6c462df --- /dev/null +++ b/Python/GeeksforGeeks/count-the-number-of-contiguous-increasing-and-decreasing-subsequences-in-a-sequence.py @@ -0,0 +1,32 @@ +""" +For a given distinct integer sequence of size N, the task is to count the number of contiguous increasing subsequence and +contiguous decreasing subsequence in this sequence. + +Examples: +Input: arr[] = { 80, 50, 60, 70, 40 } +Output: 1 2 +Explanation: +The only one increasing subsequence is (50, 60, 70) and +two decreasing subsequences are (80, 50) and (70, 40). + +Input: arr[] = { 10, 20, 23, 12, 5, 4, 61, 67, 87, 9 } +Output: 2 2 +Explanation: +The increasing subsequences are (10, 20, 23) and (4, 61, 67, 87) +whereas the decreasing subsequences are (23, 12, 5, 4) and (87, 9). +""" +def num_of_subseq(seq): + is_decreasing_regularly = is_increasing_regularly = False + + increasing = decreasing = 0 + for i in range(1, len(seq)): + if seq[i] > seq[i-1] and not is_increasing_regularly: + increasing += 1 + is_increasing_regularly = True + is_decreasing_regularly = False + elif seq[i] < seq[i-1] and not is_decreasing_regularly: + decreasing += 1 + is_decreasing_regularly = True + is_increasing_regularly = False + + return increasing, decreasing From 59d81b8e4e2caa7aee272cd95c7efd0f28f40617 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Fri, 14 May 2021 23:03:32 +0530 Subject: [PATCH 06/49] k smallest elements in same order --- Python/GeeksforGeeks/k-smallest-elements.py | 36 +++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Python/GeeksforGeeks/k-smallest-elements.py diff --git a/Python/GeeksforGeeks/k-smallest-elements.py b/Python/GeeksforGeeks/k-smallest-elements.py new file mode 100644 index 0000000..1cd69cb --- /dev/null +++ b/Python/GeeksforGeeks/k-smallest-elements.py @@ -0,0 +1,36 @@ +""" +You are given an array of n-elements you have to find k smallest elements from the array but they must be in the +same order as they are in given array and we are allowed to use only O(1) extra space. + +Examples: +Input : arr[] = {4, 2, 6, 1, 5}, + k = 3 +Output : 4 2 1 +Explanation : 1, 2 and 4 are three smallest +numbers and 4 2 1 is their order in given array + +Input : arr[] = {4, 12, 16, 21, 25}, + k = 3 +Output : 4 12 16 +Explanation : 4, 12 and 16 are 3 smallest numbers +and 4 12 16 is their order in given array +""" +def k_smallest_numbers(arr, k): + for i in range(k, len(arr)): + + max_num = arr[k-1] + pos = k-1 + for j in range(k-2, -1, -1): + if arr[j] > max_num: + max_num = arr[j] + pos = j + + if arr[pos] > arr[i]: + while pos < k-1: + arr[pos] = arr[pos + 1] + pos += 1 + + arr[k-1] = arr[i] + + for i in range(k): + print(arr[i], end=" ") From 5903ee8ad03274db5f97475d4076db71d1e9e256 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 15 May 2021 17:20:26 +0530 Subject: [PATCH 07/49] the-celebrity-problem --- Python/GeeksforGeeks/the-celebrity-problem.py | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 Python/GeeksforGeeks/the-celebrity-problem.py diff --git a/Python/GeeksforGeeks/the-celebrity-problem.py b/Python/GeeksforGeeks/the-celebrity-problem.py new file mode 100644 index 0000000..9e3480d --- /dev/null +++ b/Python/GeeksforGeeks/the-celebrity-problem.py @@ -0,0 +1,84 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/the-celebrity-problem/1# + +A celebrity is a person who is known to all but does not know anyone at a party. If you go to a party of N people, +find if there is a celebrity in the party or not. +A square NxN matrix M[][] is used to represent people at the party such that if an element of row i and column j +is set to 1 it means ith person knows jth person. Here M[i][i] will always be 0. +Note: Follow 0 based indexing. + +Example 1: +Input: +N = 3 +M[][] = {{0 1 0}, + {0 0 0}, + {0 1 0}} +Output: 1 +Explanation: 0th and 2nd person both +know 1. Therefore, 1 is the celebrity. + +Example 2: +Input: +N = 2 +M[][] = {{0 1}, + {1 0}} +Output: -1 +Explanation: The two people at the party both +know each other. None of them is a celebrity. + +Your Task: +You don't need to read input or print anything. Complete the function celebrity() which takes the matrix M and +its size N as input parameters and returns the index of the celebrity. If no such celebrity is present, return -1. +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(1) + +Constraints: +2 <= N <= 3000 +0 <= M[][] <= 1 +""" +class Solution: + + def celebrity(self, M, n): + + start, end = 0, n-1 + + while start < end: + if self.knows(start, end, M): + start += 1 + else: + end -= 1 + + celeb = start + for person in range(n): + if person != celeb: + if not (self.knows(person, celeb, M) and not self.knows(celeb, person, M)): + return -1 + + return celeb + + def knows(self, p1, p2, M): + return M[p1][p2] + +class Solution1: + + def celebrity(self, M, n): + + celeberities = [] + + for i in range(n): + num_of_known = 0 + for j in range(n): + num_of_known += M[i][j] + + if not num_of_known: + celeberities.append(i) + + for j in celeberities: + num_of_known = n-1 + for i in range(n): + num_of_known -= M[i][j] + + if not num_of_known: + return j + + return -1 \ No newline at end of file From bfa6723766b614d72c2f43d54dd36539e7c7c1ea Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 15 May 2021 19:38:37 +0530 Subject: [PATCH 08/49] Count Increasing Subsequences --- .../count-increasing-subsequences.py | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Python/GeeksforGeeks/count-increasing-subsequences.py diff --git a/Python/GeeksforGeeks/count-increasing-subsequences.py b/Python/GeeksforGeeks/count-increasing-subsequences.py new file mode 100644 index 0000000..6ebcf40 --- /dev/null +++ b/Python/GeeksforGeeks/count-increasing-subsequences.py @@ -0,0 +1,76 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/count-increasing-subsequences3134/1 + +Given an array of digits (values lie in range from 0 to 9). The task is to count all the sub sequences possible in array +such that in each subsequence every digit is greater than its previous digits in the subsequence. + +Example 1: +Input : +a[] = {1, 2, 3, 4} +Output: +15 +Explanation : +There are total increasing subsequences +{1}, {2}, {3}, {4}, {1,2}, {1,3}, {1,4}, +{2,3}, {2,4}, {3,4}, {1,2,3}, {1,2,4}, +{1,3,4}, {2,3,4}, {1,2,3,4} + + +Example 2: +Input : +a[] = {4, 3, 6, 5} +Output: +8 +Explanation : +Sub-sequences are {4}, {3}, {6}, {5}, +{4,6}, {4,5}, {3,6}, {3,5} + +Example 3: +Input : +a[] = {3, 2, 4, 5, 4} +Output : +14 +Explanation : +Sub-sequences are {3}, {2}, {4}, {3,4}, +{2,4}, {5}, {3,5}, {2,5}, {4,5}, {3,2,5} +{3,4,5}, {4}, {3,4}, {2,4} + +Your Task: +You don't have to print anything, printing is done by the driver function. You have to complete the function countSub() +which takes the array a[] and its size N as inputs and returns the count of all increasing subsequences in given array of digits. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O( max(a[i]) ) = O(10) + +Constraints: +1 ≤ N ≤ 500 +1 ≤ a[i] ≤ 9 +""" +# O(N) +class Solution: + def countSub(self, arr, n): + count = [0] * 10 + + for i in range(n): + for j in range(arr[i]-1, -1, -1): + count[arr[i]] += count[j] + + count[arr[i]] += 1 + + return sum(count) + + +# O(N*N) +class Solution1: + def countSub(self, arr, n): + dp = [1] * n + + total_sum = 1 + for i in range(1, n): + for j in range(i+1): + if arr[j] < arr[i]: + dp[i] += dp[j] + + total_sum += dp[i] + + return total_sum \ No newline at end of file From 07e158953847c592bd862b76a6dd59bf0e983640 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 09:54:32 +0530 Subject: [PATCH 09/49] IPL 2021 - Match Day 2 --- Python/GeeksforGeeks/IPL-2021-Match-Day-2.py | 100 +++++++++++++++++++ 1 file changed, 100 insertions(+) create mode 100644 Python/GeeksforGeeks/IPL-2021-Match-Day-2.py diff --git a/Python/GeeksforGeeks/IPL-2021-Match-Day-2.py b/Python/GeeksforGeeks/IPL-2021-Match-Day-2.py new file mode 100644 index 0000000..6056599 --- /dev/null +++ b/Python/GeeksforGeeks/IPL-2021-Match-Day-2.py @@ -0,0 +1,100 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/deee0e8cf9910e7219f663c18d6d640ea0b87f87/1 + +Due to the rise of covid-19 cases in India, this year BCCI decided to organize knock-out matches in IPL rather than a league. +Today is matchday 2 and it is between the most loved team Chennai Super Kings and the most underrated team - +Punjab Kings. Stephen Fleming, the head coach of CSK, analyzing the batting stats of Punjab. He has stats of runs scored +by all N players in the previous season and he wants to find the maximum score for each and every contiguous sub-list of +size K to strategize for the game. + +Example 1: +Input: +N = 9, K = 3 +arr[] = 1 2 3 1 4 5 2 3 6 +Output: +3 3 4 5 5 5 6 +Explanation: +1st contiguous subarray = {1 2 3} Max = 3 +2nd contiguous subarray = {2 3 1} Max = 3 +3rd contiguous subarray = {3 1 4} Max = 4 +4th contiguous subarray = {1 4 5} Max = 5 +5th contiguous subarray = {4 5 2} Max = 5 +6th contiguous subarray = {5 2 3} Max = 5 +7th contiguous subarray = {2 3 6} Max = 6 + +Example 2: +Input: +N = 10, K = 4 +arr[] = 8 5 10 7 9 4 15 12 90 13 +Output: +10 10 10 15 15 90 90 +Explanation: +1st contiguous subarray = {8 5 10 7}, Max = 10 +2nd contiguous subarray = {5 10 7 9}, Max = 10 +3rd contiguous subarray = {10 7 9 4}, Max = 10 +4th contiguous subarray = {7 9 4 15}, Max = 15 +5th contiguous subarray = {9 4 15 12}, Max = 15 +6th contiguous subarray = {4 15 12 90}, Max = 90 +7th contiguous subarray = {15 12 90 13}, Max = 90 + +Your Task: +You don't need to read input or print anything. Complete the function max_of_subarrays() which takes the array, N, +and K as input parameters and returns a list of integers denoting the maximum of every contiguous subarray of size K. + +Constraints: +1 ≤ N ≤ 106 +1 ≤ K ≤ N +0 ≤ arr[i] ≤ 106 +""" +from collections import deque + +class Solution: + def max_of_subarrays(self,arr,n,k): + ''' + :param a: given array + :param n: size of array + :param k: value of k + :return: A list of required values + ''' + res = [] + q = deque() + + for i in range(k): + + while q and arr[i] >= arr[q[-1]]: + q.pop() + + q.append(i) + + for i in range(k, n): + res.append(arr[q[0]]) + + while q and q[0] <= i - k: + q.popleft() + + while q and arr[i] >= arr[q[-1]]: + q.pop() + + q.append(i) + + res.append(arr[q[0]]) + return res + + +class Solution1: + def max_of_subarrays(self,arr,n,k): + ''' + :param a: given array + :param n: size of array + :param k: value of k + :return: A list of required values + ''' + max_scores = [] + for i in range(n-k+1): + max_num = arr[i] + for j in range(k): + if max_num < arr[i+j]: + max_num = arr[i+j] + max_scores.append(max_num) + + return max_scores \ No newline at end of file From 22b6805cdf1c83862b45c73c6ff59cc08d3d3ba7 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 11:09:08 +0530 Subject: [PATCH 10/49] Cutting Binary String --- Python/GeeksforGeeks/cutting-binary-string.py | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 Python/GeeksforGeeks/cutting-binary-string.py diff --git a/Python/GeeksforGeeks/cutting-binary-string.py b/Python/GeeksforGeeks/cutting-binary-string.py new file mode 100644 index 0000000..8dcbbb8 --- /dev/null +++ b/Python/GeeksforGeeks/cutting-binary-string.py @@ -0,0 +1,98 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/cutting-binary-string1342/1 + +Given a string s containing 0's and 1's. You have to return a smallest positive integer C, +such that the binary string can be cut into C pieces and each piece should be of the power of 5 with no leading zeros. + +Example 1: +Input: +s = "101101101" +Output: 3 +Explanation: We can split the given string + into three “101”s, where 101 is + the binary representation of 5. + +Example 2: +Input: +s = "00000" +Output: -1 +Explanation: 0 is not a power of 5. + +Your Task: +Your task is to complete the function cuts() which take a single argument(string s) and return C. +You need not take any input or print anything. +Expected Time Complexity: O(|s|*|s|*|s|). +Expected Auxiliary Space: O(|s|). + +Constraints: +1<=s.length()<=50 +Note: The string s is a binary string. +""" +import math + +class Solution: + + def cuts(self, s): + + dp = [[False] * len(s) for _ in range(len(s))] + + for i in range(len(s)): + cur_str = "" + for j in range(i, len(s)): + cur_str += s[j] + if cur_str == "1": + dp[i][j] = True + else: + dp[i][j] = self.is_power(cur_str, 5) + + stack = [] + for i in range(len(s)): + if dp[0][i]: + stack.append([i+1, 1]) + + # print(stack) + res = float('inf') + while stack: + index, level = stack.pop() + # print(index, level) + + if index == len(s): + res = min(level, res) + continue + + for i in range(index, len(s)): + if dp[index][i]: + stack.append([i+1, level + 1]) + + return res if res != float('inf') else -1 + + + + def is_power(self, x, y): + if x[0] == "0": + return False + + x = int(x, 2) + if x < y: + return False + + s = math.log(x, y) + p = round(s) + return y**p == x + +#{ +# Driver Code Starts +#Initial Template for Python 3 + +if __name__ == '__main__': + + t = int(input()) + + for _ in range(t): + s = input() + + solObj = Solution() + + print(solObj.cuts(s)) + +# } Driver Code Ends \ No newline at end of file From e7aa0e00f6df2aff4e705e499e89febd9deeb846 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 12:38:04 +0530 Subject: [PATCH 11/49] Chocolate Distribution Problem --- .../chocolate-distribution-problem.py | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/GeeksforGeeks/chocolate-distribution-problem.py diff --git a/Python/GeeksforGeeks/chocolate-distribution-problem.py b/Python/GeeksforGeeks/chocolate-distribution-problem.py new file mode 100644 index 0000000..ae6b9cd --- /dev/null +++ b/Python/GeeksforGeeks/chocolate-distribution-problem.py @@ -0,0 +1,57 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1 + +Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. +Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate +packets among M students such that : +1. Each student gets exactly one packet. +2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given +to a student is minimum. + +Example 1: +Input: +N = 8, M = 5 +A = {3, 4, 1, 9, 56, 7, 9, 12} +Output: 6 +Explanation: The minimum difference between +maximum chocolates and minimum chocolates +is 9 - 3 = 6 by choosing following M packets : +{3, 4, 9, 7, 9}. + +Example 2: +Input: +N = 7, M = 3 +A = {7, 3, 2, 4, 9, 12, 56} +Output: 2 +Explanation: The minimum difference between +maximum chocolates and minimum chocolates +is 4 - 2 = 2 by choosing following M packets : +{3, 2, 4}. + +Your Task: +You don't need to take any input or print anything. Your task is to complete the function findMinDiff() +which takes array A[ ], N and M as input parameters and returns the minimum possible difference between +maximum number of chocolates given to a student and minimum number of chocolates given to a student. + +Expected Time Complexity: O(N*Log(N)) +Expected Auxiliary Space: O(1) + +Constraints: +1 ≤ T ≤ 100 +1 ≤ N ≤ 105 +1 ≤ Ai ≤ 109 +1 ≤ M ≤ N +""" +class Solution: + + def findMinDiff(self, A,N,M): + A.sort() + res = float('inf') + M -= 1 + index = 0 + while M < N: + res = min(res, A[M] - A[index]) + index += 1 + M += 1 + + return res From 1a7b0dd64f06631735440a534a531ea83f0c48b5 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 16:24:23 +0530 Subject: [PATCH 12/49] Maximum sum of elements not part of LIS --- ...maximum-sum-of-elements-not-part-of-lis.py | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/GeeksforGeeks/maximum-sum-of-elements-not-part-of-lis.py diff --git a/Python/GeeksforGeeks/maximum-sum-of-elements-not-part-of-lis.py b/Python/GeeksforGeeks/maximum-sum-of-elements-not-part-of-lis.py new file mode 100644 index 0000000..7692373 --- /dev/null +++ b/Python/GeeksforGeeks/maximum-sum-of-elements-not-part-of-lis.py @@ -0,0 +1,54 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/maximum-sum-of-elements-not-part-of-lis/1 + +Given an array Arr[], the task is to find the maximum sum of all the elements which are not a part of the longest +increasing subsequence. + +Example 1: +Input: +n = 6 +Arr = {4, 6, 1, 2, 4, 6} +Output: 10 +Explaination: Elements are 4 and 6. + +Example 2: +Input: +n = 5 +Arr = {5, 4, 3, 2, 1} +Output: 14 +Explaination: Elements are 5,4,3 and 2. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function maxSumLis() which takes the +array Arr[] and its size n as input parameters and returns maximum sum of elements not part of LIS. + +Expected Time Complexity: O(n2) +Expected Auxiliary Space: O(n) + +Constraints: +1 ≤ N ≤ 1000 +1 ≤ Arr[i] ≤ 105 +""" +class Solution: + def maxSumLis(self, arr, n): + total_sum = sum(arr) + + dp = [[1, num] for num in arr] + + res = min(dp) + for i in range(n): + for j in range(i): + if arr[j] < arr[i]: + temp = [dp[j][0] + 1, dp[j][1] + arr[i]] + + if temp[0] > dp[i][0]: + dp[i] = temp + elif temp[0] == dp[i][0]: + dp[i][1] = min(temp[1], dp[i][1]) + + if res[0] < dp[i][0]: + res = dp[i] + elif res[0] == dp[i][0]: + res = min(res, dp[i]) + + return total_sum - res[1] From 984132d7db3ce9fa23d631d4245e159127957861 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 17:06:39 +0530 Subject: [PATCH 13/49] Covid Spread --- Python/GeeksforGeeks/covid-spread.py | 96 ++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Python/GeeksforGeeks/covid-spread.py diff --git a/Python/GeeksforGeeks/covid-spread.py b/Python/GeeksforGeeks/covid-spread.py new file mode 100644 index 0000000..3e8b3ec --- /dev/null +++ b/Python/GeeksforGeeks/covid-spread.py @@ -0,0 +1,96 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/269f61832b146dd5e6d89b4ca18cbd2a2654ebbe/1 + +Aterp is the head nurse at a city hospital. City hospital contains R*C number of wards and the structure of a hospital +is in the form of a 2-D matrix. + +Given a matrix of dimension R*C where each cell in the matrix can have values 0, 1, or 2 which has the following meaning: +0: Empty ward +1: Cells have uninfected patients +2: Cells have infected patients + +An infected patient at ward [i,j] can infect other uninfected patient at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] +(up, down, left and right) in unit time. Help Aterp determine the minimum units of time after which there won't +remain any uninfected patient i.e all patients would be infected. If all patients are not infected after infinite units +of time then simply return -1. + +Example 1: +Input: +3 5 +2 1 0 2 1 +1 0 1 2 1 +1 0 0 2 1 +Output: +2 +Explanation: +Patients at positions {0,0}, {0, 3}, {1, 3} +and {2, 3} will infect patient at {0, 1}, +{1, 0},{0, 4}, {1, 2}, {1, 4}, {2, 4} during 1st +unit time. And, during 2nd unit time, patient at +{1, 0} will get infected and will infect patient +at {2, 0}. Hence, total 2 unit of time is +required to infect all patients. + +Example 2: +Input: +3 5 +2 1 0 2 1 +0 0 1 2 1 +1 0 0 2 1 +Output: +-1 +Explanation: +All patients will not be infected. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function helpaterp() which takes a +2-D Matrix hospital as input parameter and returns the minimum units of time in which all patients will be infected +or -1 if it is impossible. + +Expected Time Complexity: O(R*C) +Expected Auxiliary Space: O(R*C) + +Constraints: +1 ≤ R,C ≤ 1000 +0 ≤ mat[i][j] ≤ 2 +""" +class Solution: + def helpaterp(self, hospital): + directions = [[1, 0], [-1, 0], [0, 1], [0, -1]] + queue = [] + total_uninfected_patients = 0 + + for i in range(len(hospital)): + for j in range(len(hospital[0])): + if hospital[i][j] == 2: + queue.append([i, j]) + elif hospital[i][j] == 1: + total_uninfected_patients += 1 + + if not total_uninfected_patients: + return 0 + + time_taken = 0 + while queue and total_uninfected_patients: + time_taken += 1 + + for _ in range(len(queue)): + row, col = queue.pop(0) + + for direction in directions: + next_row = row + direction[0] + next_col =col + direction[1] + + if not self.is_valid(next_row, next_col, hospital): + continue + + total_uninfected_patients -= 1 + hospital[next_row][next_col] = 2 + queue.append([next_row, next_col]) + + return time_taken if not total_uninfected_patients else -1 + + def is_valid(self, row, col, hospital): + if row >= 0 and col >= 0 and row < len(hospital) and col < len(hospital[0]) and hospital[row][col] == 1: + return True + return False From db46f2724309c088340bdd1ed872abe64f9cb209 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 17:31:20 +0530 Subject: [PATCH 14/49] K-th element of two sorted Arrays --- .../k-th-element-of-two-sorted-array1.py | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Python/GeeksforGeeks/k-th-element-of-two-sorted-array1.py diff --git a/Python/GeeksforGeeks/k-th-element-of-two-sorted-array1.py b/Python/GeeksforGeeks/k-th-element-of-two-sorted-array1.py new file mode 100644 index 0000000..7f47e87 --- /dev/null +++ b/Python/GeeksforGeeks/k-th-element-of-two-sorted-array1.py @@ -0,0 +1,64 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/k-th-element-of-two-sorted-array1317/1 + +Given two sorted arrays arr1 and arr2 of size M and N respectively and an element K. The task is to find the element that +would be at the k’th position of the final sorted array. + +Example 1: +Input: +arr1[] = {2, 3, 6, 7, 9} +arr2[] = {1, 4, 8, 10} +k = 5 +Output: +6 +Explanation: +The final sorted array would be - +1, 2, 3, 4, 6, 7, 8, 9, 10 +The 5th element of this array is 6. + +Example 2: +Input: +arr1[] = {100, 112, 256, 349, 770} +arr2[] = {72, 86, 113, 119, 265, 445, 892} +k = 7 +Output: +256 +Explanation: +Final sorted array is - 72, 86, 100, 112, +113, 119, 256, 265, 349, 445, 770, 892 +7th element of this array is 256. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function kthElement() +which takes the arrays arr1[], arr2[], its size N and M respectively and an integer K as inputs and returns the element +at the Kth position. + +Expected Time Complexity: O(Log(N) + Log(M)) +Expected Auxiliary Space: O(Log (N)) + +Constraints: +1 <= N, M <= 106 +1 <= arr1i, arr2i <= 106 +1 <= K <= N+M +""" +class Solution: + def kthElement(self, arr1, arr2, n, m, k): + if m < n: + return self.kthElement(arr2, arr1, m, n, k) + + k -= 1 + arr1_index = 0 + arr2_index = 0 + + while arr1_index < n and arr2_index < m: + k -= 1 + + if arr1[arr1_index] < arr2[arr2_index]: + arr1_index += 1 + else: + arr2_index += 1 + + if k == 0: + return min(arr1[arr1_index] if arr1_index < n else float('inf'), arr2[arr2_index] if arr2_index < m else float('inf')) + + return arr2[arr2_index + k] From e4073c5f39160ea45d63b063b4803b277faee527 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 17:51:25 +0530 Subject: [PATCH 15/49] Shortest direction --- Python/GeeksforGeeks/shortest-direction.py | 56 ++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 Python/GeeksforGeeks/shortest-direction.py diff --git a/Python/GeeksforGeeks/shortest-direction.py b/Python/GeeksforGeeks/shortest-direction.py new file mode 100644 index 0000000..12dc211 --- /dev/null +++ b/Python/GeeksforGeeks/shortest-direction.py @@ -0,0 +1,56 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/shortest-direction4201/1 + +A person wants to go from origin to a particular location, he can move in only 4 directions(i.e East, West, North, South) +but his friend gave him a long route, help a person to find minimum Moves so that he can reach to the destination. +Note: You need to print the lexicographically sorted string. Assume the string will have only ‘E’ ‘N’ ‘S’ ‘W’ characters. + +Example 1: +Input: +S = "SSSNEEEW" +Output: EESS +Explanation: Following the path SSSNEEEW +and EESS gets you at the same final point. +There's no shorter path possible. + +Example 2: +Input: +S = "NESNWES" +Output: E +Explanation: Following the path NESNWES +and E gets you at the same final point. +There's no shorter path possible. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function shortestPath() which takes the string +S as input and returns the resultant string denoting the shortest path in lexicographic order. + +Expected Time Complexity: O(|S|). +Expected Auxiliary Space: O(|S|) for output. + +Constraints: +1<=|S|<=105 +""" +class Solution: + def shortestPath(self, s): + count = { + "E": 0, + "W": 0, + "S": 0, + "N": 0 + } + + for direction in s: + count[direction] += 1 + + res = "" + if count["E"] > count["W"]: + res += ("E" * (count["E"] - count["W"])) + if count["S"] < count["N"]: + res += ("N" * (count["N"] - count["S"])) + if count["S"] > count["N"]: + res += ("S" * (count["S"] - count["N"])) + if count["E"] < count["W"]: + res += ("W" * (count["W"] - count["E"])) + + return res From 967f93b45f6257ea7e10e71f949e82ffef32abb7 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 18:58:50 +0530 Subject: [PATCH 16/49] Gold Mine Problem --- Python/GeeksforGeeks/gold-mine-problem.py | 96 +++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 Python/GeeksforGeeks/gold-mine-problem.py diff --git a/Python/GeeksforGeeks/gold-mine-problem.py b/Python/GeeksforGeeks/gold-mine-problem.py new file mode 100644 index 0000000..eab81a1 --- /dev/null +++ b/Python/GeeksforGeeks/gold-mine-problem.py @@ -0,0 +1,96 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/gold-mine-problem2608/1 + +Given a gold mine called M of (n x m) dimensions. Each field in this mine contains a positive integer which is the amount +of gold in tons. Initially the miner can start from any row in the first column. From a given cell, the miner can move +to the cell diagonally up towards the right +to the right +to the cell diagonally down towards the right +Find out maximum amount of gold which he can collect. + +Example 1: +Input: n = 3, m = 3 +M = {{1, 3, 3}, + {2, 1, 4}, + {0, 6, 4}}; +Output: 12 + +Explaination: +The path is {(1,0) -> (2,1) -> (2,2)}. + +Example 2: +Input: n = 4, m = 4 +M = {{1, 3, 1, 5}, + {2, 2, 4, 1}, + {5, 0, 2, 3}, + {0, 6, 1, 2}}; +Output: 16 +Explaination: +The path is {(2,0) -> (3,1) -> (2,2) +-> (2,3)} or {(2,0) -> (1,1) -> (1,2) +-> (0,3)}. + +Your Task: +You do not need to read input or print anything. Your task is to complete the function maxGold() which takes the +values n, m and the mine M as input parameters and returns the maximum amount of gold that can be collected. + +Expected Time Complexity: O(n*m) +Expected Auxiliary Space: O(n*m) + +Constraints: +1 ≤ n, m ≤ 50 +1 ≤ M[i][j] ≤ 100 +""" +class Solution: + def maxGold(self, n, m, M): + cache = [[0] * m for _ in range(n)] + + directions = [[0, 1], [-1, 1], [1, 1]] + + max_gold = 0 + for col in range(m-1, -1, -1): + for row in range(n-1, -1, -1): + max_val = 0 + for direction in directions: + new_row = row + direction[0] + new_col = col + direction[1] + + if not (new_row >= 0 and new_row < n and new_col < m): + continue + + max_val = max(max_val, cache[new_row][new_col]) + + cache[row][col] = M[row][col] + max_val + + if col == 0: + max_gold = max(max_gold, cache[row][col]) + + return max_gold + + +class Solution1: + def maxGold(self, n, m, M): + cache = [[0] * m for _ in range(n)] + + directions = [[0, 1], [-1, 1], [1, 1]] + queue = [] + for row in range(n): + queue.append([row, 0, M[row][0]]) + + max_gold = 0 + while queue: + + for _ in range(len(queue)): + row, col, cur_gold = queue.pop(0) + cache[row][col] = cur_gold + max_gold = max(max_gold, cur_gold) + + for direction in directions: + next_row = row + direction[0] + next_col = col + direction[1] + if not (next_row >= 0 and next_row < n and next_col < m and cache[next_row][next_col] < cur_gold + M[next_row][next_col]): + continue + + queue.append([next_row, next_col, cur_gold + M[next_row][next_col]]) + + return max_gold From 8d0a7eeb5af3c0312ff10aa8b1bba9c7439c47c8 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 16 May 2021 20:43:20 +0530 Subject: [PATCH 17/49] Consecutive 1's not allowed --- .../consecutive-1s-not-allowed.py | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/GeeksforGeeks/consecutive-1s-not-allowed.py diff --git a/Python/GeeksforGeeks/consecutive-1s-not-allowed.py b/Python/GeeksforGeeks/consecutive-1s-not-allowed.py new file mode 100644 index 0000000..1c2cea6 --- /dev/null +++ b/Python/GeeksforGeeks/consecutive-1s-not-allowed.py @@ -0,0 +1,54 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/consecutive-1s-not-allowed1912/1 + +Input: +N = 3 +Output: 5 +Explanation: 5 strings are (000, +001, 010, 100, 101). + +Example 2: +Input: +N = 2 +Output: 3 +Explanation: 3 strings are +(00,01,10). + +Your Task: +Complete the function countStrings() which takes single integer n, as input parameters and returns an integer denoting the answer. +You don't to print answer or take inputs. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(N) + +Constraints: +1 ≤ N ≤ 105 +""" +class Solution: + + def countStrings(self,n): + zero_count = 1 + one_count = 1 + + for i in range(1, n): + zero_count, one_count = (zero_count + one_count) % 1000000007, zero_count + + return (zero_count + one_count) % 1000000007 + + +# TLE +class Solution1: + + def countStrings(self,n): + return len(self.helper(n)) + + def helper(self, n): + if n == 1: + return ["0", "1"] + numbers = self.helper(n-1) + res = [] + for num in numbers: + res.append(num + "0") + if num[-1] != "1": + res.append(num + "1") + return res From 8f71b66a62452b31eb81b06bd2b20c803df0849b Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 10:47:18 +0530 Subject: [PATCH 18/49] 0-1 Knapsack Problem --- Python/GeeksforGeeks/0-1-knapsack-problem.py | 88 ++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 Python/GeeksforGeeks/0-1-knapsack-problem.py diff --git a/Python/GeeksforGeeks/0-1-knapsack-problem.py b/Python/GeeksforGeeks/0-1-knapsack-problem.py new file mode 100644 index 0000000..d0e4b9b --- /dev/null +++ b/Python/GeeksforGeeks/0-1-knapsack-problem.py @@ -0,0 +1,88 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem0945/1 + +You are given weights and values of N items, put these items in a knapsack of capacity W to get the maximum total value in the +knapsack. Note that we have only one quantity of each item. +In other words, given two integer arrays val[0..N-1] and wt[0..N-1] which represent values and weights associated with N +items respectively. Also given an integer W which represents knapsack capacity, find out the maximum value subset of val[] +such that sum of the weights of this subset is smaller than or equal to W. You cannot break an item, either pick the +complete item, or don’t pick it (0-1 property). + +Example 1: +Input: +N = 3 +W = 4 +values[] = {1,2,3} +weight[] = {4,5,1} +Output: 3 + +Example 2: +Input: +N = 3 +W = 3 +values[] = {1,2,3} +weight[] = {4,5,6} +Output: 0 + +Your Task: +Complete the function knapSack() which takes maximum capacity W, weight array wt[], value array val[] and number of items +n as a parameter and returns the maximum possible value you can get. +Expected Time Complexity: O(N*W). +Expected Auxiliary Space: O(N*W) +Constraints: +1 ≤ N ≤ 1000 +1 ≤ W ≤ 1000 +1 ≤ wt[i] ≤ 1000 +1 ≤ v[i] ≤ 1000 +""" +# Time Complexity -> O(N*W) +class Solution: + + #Function to return max value that can be put in knapsack of capacity W. + def knapSack(self,W, wt, val, n): + dp = [[0] * (W+1) for _ in range(n+1)] + + for i in range(1, n+1): + for j in range(1, W+1): + if wt[i-1] <= j: + dp[i][j] = max(val[i-1] + dp[i-1][j-wt[i-1]], dp[i-1][j]) + else: + dp[i][j] = dp[i-1][j] + + return dp[-1][-1] + +# Time Complexity -> O(N*W) +class Solution1: + + def knapSack(self,W, wt, val, n): + self.cache = {} + + def helper(w, wt, val, index): + + if index == -1 or w == 0: + return 0 + + if (w, index) not in self.cache: + if w >= wt[index]: + self.cache[w, index] = max(val[index] + helper(w-wt[index], wt, val, index-1), helper(w, wt, val, index-1)) + else: + self.cache[w, index] = helper(w, wt, val, index-1) + + return self.cache[w, index] + + return helper(W, wt, val, n-1) + +# TLE +# Time Complexity -> O(2^N) +class Solution2: + + def knapSack(self,W, wt, val, n): + + def helper(w, wt, val, index): + if index == -1 or w == 0: + return 0 + if w >= wt[index]: + return max(val[index] + helper(w-wt[index], wt, val, index-1), helper(w, wt, val, index-1)) + return helper(w, wt, val, index-1) + + return helper(W, wt, val, n-1) From 860800369eb9b841abf7e8a08230393da8357cbd Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 10:59:37 +0530 Subject: [PATCH 19/49] Sum of dependencies in a graph --- .../sum-of-dependencies-in-a-graph.py | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Python/GeeksforGeeks/sum-of-dependencies-in-a-graph.py diff --git a/Python/GeeksforGeeks/sum-of-dependencies-in-a-graph.py b/Python/GeeksforGeeks/sum-of-dependencies-in-a-graph.py new file mode 100644 index 0000000..1626608 --- /dev/null +++ b/Python/GeeksforGeeks/sum-of-dependencies-in-a-graph.py @@ -0,0 +1,50 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/sum-of-dependencies-in-a-graph5311/1 + +Given a directed graph with V nodes and E edges. If there is an edge from u to v then u depends on v. +Find out the sum of dependencies for every node. Duplicate edges should be counted as separate edges. + +Example 1: +Input: +V=4 +E=4 +Edges={ {0,2},{0,3},{1,3},{2,3} } + +Output: +4 +Explanation: +For the graph in diagram, A depends +on C and D i.e. 2, B depends on D i.e. +1, C depends on D i.e. 1 +and D depends on none. +Hence answer -> 0 + 1 + 1 + 2 = 4 + +Example 2: +Input: +V=4 +E=3 +Edges={ {0,3},{0,2},{0,1} } +Output: +3 + +Explanation: +The sum of dependencies=3+0+0+0=3. + +Your Task: +You don't need to read input or print anything.Your task is to complete the function sumOfDependencies() +which takes the adj (Adjacency list) and V (Number of nodes)as input parameters and returns the total sum of dependencies +of all nodes. + +Expected Time Complexity:O(V) +Expected Auxillary Space:O(1) + +Constraints: +1<=V,E<=150 +0<= Edges[i][0],Edges[i][1] <= V-1 +""" +class Solution: + def sumOfDependencies(self,adj,V): + count = 0 + for edges in adj: + count += len(edges) + return count From bc3251b75a527a0fef58a0291bb93243895db8b6 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 11:59:46 +0530 Subject: [PATCH 20/49] Search in a Rotated Array --- .../search-in-a-rotated-array.py | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/GeeksforGeeks/search-in-a-rotated-array.py diff --git a/Python/GeeksforGeeks/search-in-a-rotated-array.py b/Python/GeeksforGeeks/search-in-a-rotated-array.py new file mode 100644 index 0000000..b0d24a2 --- /dev/null +++ b/Python/GeeksforGeeks/search-in-a-rotated-array.py @@ -0,0 +1,54 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/search-in-a-rotated-array4618/1 + +Given a sorted and rotated array A of N distinct elements which is rotated at some point, and given an element key. +The task is to find the index of the given element key in the array A. + +Example 1: +Input: +N = 9 +A[] = {5, 6, 7, 8, 9, 10, 1, 2, 3} +key = 10 +Output: +5 +Explanation: 10 is found at index 5. + +Example 2: +Input: +N = 4 +A[] = {3, 5, 1, 2} +key = 6 +Output: +-1 +Explanation: There is no element that has value 6. + +Your Task: +Complete the function search() which takes an array arr[] and start, end index of the array and the K as input parameters, +and returns the answer. +Expected Time Complexity: O(log N). +Expected Auxiliary Space: O(1). + +Constraints: +1 ≤ N ≤ 107 +0 ≤ A[i] ≤ 108 +1 ≤ key ≤ 108 +""" +class Solution: + def search(self, A : list, l : int, h : int, key : int): + while l < h: + mid = (l+h)//2 + + if A[mid] == key: + return mid + if A[l] < A[h]: + if A[mid] < key: + l = mid + 1 + else: + h = mid - 1 + else: + if (A[mid] < A[h] and (key <= A[h] and key > A[mid])) or (A[mid] > A[h] and (key <= A[h] or key > A[mid])): + l = mid + 1 + else: + h = mid - 1 + + return l if A[l] == key else -1 From b6e9ea80931bcfd68cded5013f3722d844476bf9 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 12:26:52 +0530 Subject: [PATCH 21/49] Clone a stack without usinig extra space --- ...lone-a-stack-without-usinig-extra-space.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 Python/GeeksforGeeks/clone-a-stack-without-usinig-extra-space.py diff --git a/Python/GeeksforGeeks/clone-a-stack-without-usinig-extra-space.py b/Python/GeeksforGeeks/clone-a-stack-without-usinig-extra-space.py new file mode 100644 index 0000000..3a9b821 --- /dev/null +++ b/Python/GeeksforGeeks/clone-a-stack-without-usinig-extra-space.py @@ -0,0 +1,39 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/clone-a-stack-without-usinig-extra-space/1 + +Given elements of a stack, clone the stack without using extra space. + +Example 1: +Input: +N = 10 +st[] = {1, 1, 2, 2, 3, 4, 5, 5, 6, 7} +Output: +1 + +Your Task: +You don't need to read input or print anything. Your task is to complete the function clonestack() which takes the input stack +st[], an empty stack cloned[], you have to clone the stack st into stack cloned. +The driver code itself prints 1 in the output if the stack st is cloned properly and prints 0 otherwise. + +Expected Time Complexity: O(N*N) +Expected Auxiliary Space: O(1) + +Constraints: +1 <= N <= 1000 +1<= st[i] <= 105 +""" +class Solution: + def clonestack(self, st, cloned): + length = len(st) + for i in range(length-1): + val = st.pop() + + for _ in range(len(st) - i): + cloned.append(st.pop()) + + st.append(val) + while cloned: + st.append(cloned.pop()) + + while st: + cloned.append(st.pop()) From 54d8533c8a7704624089d085d872957d514319cc Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 15:35:20 +0530 Subject: [PATCH 22/49] Doubling the value --- Python/GeeksforGeeks/doubling-the-value.py | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Python/GeeksforGeeks/doubling-the-value.py diff --git a/Python/GeeksforGeeks/doubling-the-value.py b/Python/GeeksforGeeks/doubling-the-value.py new file mode 100644 index 0000000..6e867c1 --- /dev/null +++ b/Python/GeeksforGeeks/doubling-the-value.py @@ -0,0 +1,44 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/doubling-the-value4859/1 + +Given an array and an integer B, traverse the array (from the beginning) and if the element in array is B, +double B and continue traversal. Find the value of B after the complete traversal. + +Example 1: +Input: +N = 5, B = 2 +arr[] = {1 2 3 4 8} +Output: 16 +Explanation: B is initially 2. We get 2 at +the 1st index, hence B becomes 4. +Next, we get B at the 3rd index, hence B +becomes 8. Next, we get B at 4-th index, +hence B becomes 16. + +Example 1: +Input: +N = 5, B = 3 +arr[] = {1 2 3 4 8} +Output: 6 +Explanation: B is initially 3. We get 3 at +the 2nd index, hence B becomes 6. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function solve () which takes the array arr[], +its size N and an integer B as inputs and returns the final value of B after the complete traversal of the array. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(1). + +Constraints: +1<=N<=50 +1<=B<=1000 +1<=arr[i]<=1018 +""" +class Solution: + def solve(self,n : int, a : list, b : int): + for num in a: + if num == b: + b *= 2 + + return b From 9bbbb78ea161c97d5fa7f4a0bba3361e766a4aa3 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 16:13:46 +0530 Subject: [PATCH 23/49] Print Bracket Number --- Python/GeeksforGeeks/print-bracket-number.py | 46 ++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/GeeksforGeeks/print-bracket-number.py diff --git a/Python/GeeksforGeeks/print-bracket-number.py b/Python/GeeksforGeeks/print-bracket-number.py new file mode 100644 index 0000000..bcc8741 --- /dev/null +++ b/Python/GeeksforGeeks/print-bracket-number.py @@ -0,0 +1,46 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/print-bracket-number4058/1 + +Given a string S, the task is to find the bracket numbers. + +Example 1: +Input: S = "(aa(bdc))p(dee)​" +Output: 1 2 2 1 3 3 +Explanation: The highlighted brackets in +the given string (aa(bdc))p(dee) has been +assigned the numbers as: 1 2 2 1 3 3. + +Example 2: +Input: S = "(((()(" +Output: 1 2 3 4 4 5 +Explanation: The highlighted brackets in +the given string (((()( has been assigned +the numbers as: 1 2 3 4 4 5 + +User Task: +Your task is to complete the function barcketNumbers() which takes a single string as input and returns a list of numbers. +You do not need to take any input or print anything. + +Expected Time Complexity: O(|S|) +Expected Auxiliary Space: O(|S|) + +Constraints: +1 <= |S| <= 105 +S contains lower case English alphabets, and '(', ')' characters +At any time the number of opening brackets are greater than closing brackets +""" +class Solution: + def barcketNumbers(self, S): + stack, res = [], [] + count = 0 + + for c in S: + if c == "(": + count += 1 + stack.append(count) + res.append(count) + elif c == ")": + c = stack.pop() + res.append(c) + + return res From 80eac5378e8ddf77d7cf3f9dc803ef403a022bd3 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sat, 22 May 2021 19:52:14 +0530 Subject: [PATCH 24/49] Left View of Binary Tree --- .../GeeksforGeeks/left-view-of-binary-tree.py | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 Python/GeeksforGeeks/left-view-of-binary-tree.py diff --git a/Python/GeeksforGeeks/left-view-of-binary-tree.py b/Python/GeeksforGeeks/left-view-of-binary-tree.py new file mode 100644 index 0000000..ea22adf --- /dev/null +++ b/Python/GeeksforGeeks/left-view-of-binary-tree.py @@ -0,0 +1,74 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/left-view-of-binary-tree/1 + +Given a Binary Tree, print Left view of it. Left view of a Binary Tree is set of nodes visible when tree is visited +from Left side. The task is to complete the function leftView(), which accepts root of the tree as argument. + +Left view of following tree is 1 2 4 8. + + 1 + / \ + 2 3 + / \ / \ + 4 5 6 7 + \ + 8 + +Example 1: +Input: + 1 + / \ +3 2 +Output: 1 3 + +Example 2: +Input: +Output: 10 20 40 + +Your Task: +You just have to complete the function leftView() that prints the left view. The newline is automatically appended by the +driver code. +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(Height of the Tree). + +Constraints: +0 <= Number of nodes <= 100 +1 <= Data of a node <= 1000 +""" +# DFS +def LeftViewDFS(root): + + def helper(root, level, res): + if not root: + return res + + if level > len(res): + res.append(root.data) + + helper(root.left, level+1, res) + helper(root.right, level+1, res) + + return res + + return helper(root, 1, []) + +# BFS +def LeftView(root): + if not root: + return [] + + level = [root] + res = [] + + while level: + for index in range(len(level)): + node = level.pop(0) + if index == 0: + res.append(node.data) + + if node.left: + level.append(node.left) + if node.right: + level.append(node.right) + + return res From de2fae5a0fccb551c1405d92463b9fb8149b4c15 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 23 May 2021 12:24:13 +0530 Subject: [PATCH 25/49] Bottom View of Binary Tree --- .../bottom-view-of-binary-tree.py | 86 +++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 Python/GeeksforGeeks/bottom-view-of-binary-tree.py diff --git a/Python/GeeksforGeeks/bottom-view-of-binary-tree.py b/Python/GeeksforGeeks/bottom-view-of-binary-tree.py new file mode 100644 index 0000000..e0555a4 --- /dev/null +++ b/Python/GeeksforGeeks/bottom-view-of-binary-tree.py @@ -0,0 +1,86 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/bottom-view-of-binary-tree/1 + +Given a binary tree, print the bottom view from left to right. +A node is included in bottom view if it can be seen when we look at the tree from bottom. + + 20 + / \ + 8 22 + / \ \ + 5 3 25 + / \ + 10 14 + +For the above tree, the bottom view is 5 10 3 14 25. +If there are multiple bottom-most nodes for a horizontal distance from root, then print the later one in level traversal. +For example, in the below diagram, 3 and 4 are both the bottommost nodes at horizontal distance 0, we need to print 4. + 20 + / \ + 8 22 + / \ / \ + 5 3 4 25 + / \ + 10 14 +For the above tree the output should be 5 10 4 14 25. + +Example 1: +Input: + 1 + / \ + 3 2 +Output: 3 1 2 +Explanation: +First case represents a tree with 3 nodes +and 2 edges where root is 1, left child of +1 is 3 and right child of 1 is 2. +Thus nodes of the binary tree will be +printed as such 3 1 2. + +Example 2: +Input: + 10 + / \ + 20 30 + / \ + 40 60 +Output: 40 20 60 30 + +Your Task: +This is a functional problem, you don't need to care about input, just complete the function bottomView() +which takes the root node of the tree as input and returns an array containing the bottom view of the given tree. + +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(N). + +Constraints: +1 <= Number of nodes <= 105 +1 <= Data of a node <= 105 +""" +def bottomView(root): + if not root: + return [] + + res = {} + + min_level = max_level = 0 + level = [(root, 0)] + + while level: + for _ in range(len(level)): + node, vertical_level = level.pop(0) + + res[vertical_level] = node.data + min_level = min(min_level, vertical_level) + max_level = max(max_level, vertical_level) + + if node.left: + level.append((node.left, vertical_level-1)) + if node.right: + level.append((node.right, vertical_level+1)) + + new_res = [] + for level_val in range(min_level, max_level+1): + new_res.append(res[level_val]) + + return new_res From de75b7ee919d4d3d5dc42733cd17fb56ceb98138 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 23 May 2021 12:28:28 +0530 Subject: [PATCH 26/49] Next Greater Element --- Python/GeeksforGeeks/next-larger-element.py | 53 +++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 Python/GeeksforGeeks/next-larger-element.py diff --git a/Python/GeeksforGeeks/next-larger-element.py b/Python/GeeksforGeeks/next-larger-element.py new file mode 100644 index 0000000..2fd7ed4 --- /dev/null +++ b/Python/GeeksforGeeks/next-larger-element.py @@ -0,0 +1,53 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/next-larger-element-1587115620/1 + +Given an array arr[ ] of size N having distinct elements, the task is to find the next greater element for each element of +the array in order of their appearance in the array. +Next greater element of an element in the array is the nearest element on the right which is greater than the current element. +If there does not exist next greater of current element, then next greater element for current element is -1. For example, +next greater of the last element is always -1. + +Example 1: +Input: +N = 4, arr[] = [1 3 2 4] +Output: +3 4 4 -1 +Explanation: +In the array, the next larger element +to 1 is 3 , 3 is 4 , 2 is 4 and for 4 ? +since it doesn't exist, it is -1. + +Example 2: +Input: +N = 5, arr[] [6 8 0 1 3] +Output: +8 -1 1 3 -1 +Explanation: +In the array, the next larger element to +6 is 8, for 8 there is no larger elements +hence it is -1, for 0 it is 1 , for 1 it +is 3 and then for 3 there is no larger +element on right and hence -1. + +Your Task: +This is a function problem. You only need to complete the function nextLargerElement() that takes list of integers arr[ ] +and N as input parameters and returns list of integers of length N denoting the next greater elements for all the +corresponding elements in the input array. + +Expected Time Complexity : O(N) +Expected Auxilliary Space : O(N) + +Constraints: +1 ≤ N ≤ 106 +1 ≤ Ai ≤ 1018 +""" +class Solution: + def nextLargerElement(self,arr,n): + stack = [] + res = [] + for i in range(n-1, -1, -1): + while stack and stack[-1] <= arr[i]: + stack.pop() + res.append(stack[-1] if stack else -1) + stack.append(arr[i]) + return res[::-1] From f8113606af7a182abfdabf467c01e56bf2060825 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 23 May 2021 13:20:33 +0530 Subject: [PATCH 27/49] Find duplicates in an array --- .../find-duplicates-in-an-array.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/GeeksforGeeks/find-duplicates-in-an-array.py diff --git a/Python/GeeksforGeeks/find-duplicates-in-an-array.py b/Python/GeeksforGeeks/find-duplicates-in-an-array.py new file mode 100644 index 0000000..41c231a --- /dev/null +++ b/Python/GeeksforGeeks/find-duplicates-in-an-array.py @@ -0,0 +1,46 @@ +""" +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. + +Example 1: +Input: +N = 4 +a[] = {0,3,1,2} +Output: -1 +Explanation: N=4 and all elements from 0 +to (N-1 = 3) are present in the given +array. Therefore output is -1. + +Example 2: +Input: +N = 5 +a[] = {2,3,1,2,3} +Output: 2 3 +Explanation: 2 and 3 occur more than once +in the given array. + +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 <= N <= 105 +0 <= A[i] <= N-1, for each valid i +""" +class Solution: + def duplicates(self, arr, n): + for num in arr: + arr[num % n] += n + + res = [] + for index in range(n): + if arr[index] // n > 1: + res.append(index) + + return res if res else [-1] +Find duplicates in an array \ No newline at end of file From ebabf7477e67a6c0463dee9828c835d52d611de3 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Sun, 23 May 2021 19:11:26 +0530 Subject: [PATCH 28/49] Maximum path sum in matrix --- Python/GeeksforGeeks/path-in-matrix.py | 57 ++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Python/GeeksforGeeks/path-in-matrix.py diff --git a/Python/GeeksforGeeks/path-in-matrix.py b/Python/GeeksforGeeks/path-in-matrix.py new file mode 100644 index 0000000..ba238b7 --- /dev/null +++ b/Python/GeeksforGeeks/path-in-matrix.py @@ -0,0 +1,57 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/path-in-matrix3805/1 + +Given a NxN matrix of positive integers. There are only three possible moves from a cell Matrix[r][c]. +Matrix [r+1] [c] +Matrix [r+1] [c-1] +Matrix [r+1] [c+1] +Starting from any column in row 0, return the largest sum of any of the paths up to row N-1. + +Example 1: +Input: N = 2 +Matrix = {{348, 391}, + {618, 193}} +Output: 1009 +Explaination: The best path is 391 -> 618. +It gives the sum = 1009. + +Example 2: +Input: N = 2 +Matrix = {{2, 2}, + {2, 2}} +Output: 4 +Explaination: No matter which path is +chosen, the output is 4. + +Your Task: +You do not need to read input or print anything. Your task is to complete the function maximumPath() which takes the size N +and the Matrix as input parameters and returns the highest maximum path sum. + +Expected Time Complexity: O(N*N) +Expected Auxiliary Space: O(N*N) + +Constraints: +1 ≤ N ≤ 100 +1 ≤ Matrix[i][j] ≤ 1000 +""" +class Solution: + def maximumPath(self, N, Matrix): + dp = [[0] * N for _ in range(N)] + + directions = [[1, 1], [1, -1], [1, 0]] + + max_path_sum = 0 + + for row in range(N-1, -1, -1): + for col in range(N): + max_val = 0 + for r, c in directions: + new_row = r + row + new_col = c + col + if new_row >= 0 and new_col >= 0 and new_row < N and new_col < N: + max_val = max(max_val, dp[new_row][new_col]) + + dp[row][col] = Matrix[row][col] + max_val + max_path_sum = max(max_path_sum, dp[row][col]) + + return max_path_sum From 93e7a2c5f857370fa82ff415ded130d94efb4da1 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Mon, 26 Jul 2021 23:32:42 +0530 Subject: [PATCH 29/49] Life, the Universe, and Everything --- .../life_universe_and_everything.clj | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Clojure/hackerearth/life_universe_and_everything.clj diff --git a/Clojure/hackerearth/life_universe_and_everything.clj b/Clojure/hackerearth/life_universe_and_everything.clj new file mode 100644 index 0000000..cbed394 --- /dev/null +++ b/Clojure/hackerearth/life_universe_and_everything.clj @@ -0,0 +1,36 @@ +;; Problem Link: https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/life-the-universe-and-everything/ + +;; Your program is to use the brute-force approach in order to find the Answer to Life, the Universe, and Everything. More precisely... +;; rewrite small numbers from input to output. Stop processing input after reading in the number 42. All numbers at input are integers of one or two digits. + +;; Sample Input +;; 1 +;; 2 +;; 88 +;; 42 +;; 99 +;; Sample Output +;; 1 +;; 2 +;; 88 + +;; Method 1 +(loop [] + (def x (read-line)) + (if (not= x "42") + (do (println x) + (recur)) + ) +) + + +;; Method 2 +(defn life-the-universe-and-everthing + [] + (def x (read-line)) + (if (not= x "42") + (do (println x) + (life-the-universe-and-everthing)) + ) +) +(life-the-universe-and-everthing) From fbd63130d89de4ce8890b4cf26018dfe4b932c38 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Tue, 27 Jul 2021 10:31:17 +0530 Subject: [PATCH 30/49] Factorial --- Clojure/hackerearth/factorial.clj | 32 +++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Clojure/hackerearth/factorial.clj diff --git a/Clojure/hackerearth/factorial.clj b/Clojure/hackerearth/factorial.clj new file mode 100644 index 0000000..ccc8cca --- /dev/null +++ b/Clojure/hackerearth/factorial.clj @@ -0,0 +1,32 @@ +;; Problem Link: https://www.hackerearth.com/practice/basic-programming/input-output/basics-of-input-output/practice-problems/algorithm/find-factorial/ + +;; Problem +;; You have been given a positive integer N. You need to find and print the Factorial of this number. The Factorial of a positive integer N refers to the product of +;; all number in the range from 1 to N. You can read more about the factorial of a number here. + +;; Input Format: +;; The first and only line of the input contains a single integer N denoting the number whose factorial you need to find. + +;; Output Format +;; Output a single line denoting the factorial of the number N. + +;; Constraints + +;; Sample Input +;; 2 +;; Sample Output +;; 2 + +;; Method 1 +(defn factorial + [n fact] + (if (= n 1) + fact + (factorial (- n 1) (* fact n)) + ) +) +(def x (Integer/parseInt (read-line))) +(println (factorial x 1)) + +;; Method 2 +(println (reduce * (range 1 (inc (Integer/parseInt (read-line)))))) From 54352e5608cc4563eb11b38f9ae16f7d17d5d407 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Wed, 28 Jul 2021 09:13:02 +0530 Subject: [PATCH 31/49] Solve Me First --- Clojure/hackerrank/solve-me-first.clj | 42 +++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 Clojure/hackerrank/solve-me-first.clj diff --git a/Clojure/hackerrank/solve-me-first.clj b/Clojure/hackerrank/solve-me-first.clj new file mode 100644 index 0000000..d2dd020 --- /dev/null +++ b/Clojure/hackerrank/solve-me-first.clj @@ -0,0 +1,42 @@ +;; Problem Link: https://www.hackerrank.com/challenges/solve-me-first/problem + +;; Complete the function solveMeFirst to compute the sum of two integers. + +;; Example +;; a = 7 +;; b = 3 +;; Return 10. + +;; Function Description + +;; Complete the solveMeFirst function in the editor below. + +;; solveMeFirst has the following parameters: + +;; int a: the first value +;; int b: the second value +;; Returns +;; - int: the sum of a and b + +;; Sample Input +;; a = 2 +;; b = 3 + +;; Sample Output +;; 5 + +;; Method 1 + +(defn solveMeFirst + [x y] + (+ x y) +) + + +(def a (read-line)) +(def b (read-line)) + +(println (solveMeFirst (Integer/parseInt a) (Integer/parseInt b))) + +;; Method 2 +(println (#(+ %1 %2) (Integer/parseInt (read-line)) (Integer/parseInt (read-line)))) From 01ea0c7f3c40828ef259a6029b4d1a38ba84b054 Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Wed, 28 Jul 2021 09:19:34 +0530 Subject: [PATCH 32/49] Simple Array Sum --- Clojure/hackerrank/simple-array-sum.clj | 37 +++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Clojure/hackerrank/simple-array-sum.clj diff --git a/Clojure/hackerrank/simple-array-sum.clj b/Clojure/hackerrank/simple-array-sum.clj new file mode 100644 index 0000000..cf79212 --- /dev/null +++ b/Clojure/hackerrank/simple-array-sum.clj @@ -0,0 +1,37 @@ +;; Problem Link: https://www.hackerrank.com/challenges/simple-array-sum/problem + +;; Given an array of integers, find the sum of its elements. + +;; Function Description +;; Complete the simpleArraySum function in the editor below. It must return the sum of the array elements as an integer. +;; simpleArraySum has the following parameter(s): +;; ar: an array of integers + +;; Input Format +;; The first line contains an integer, n, denoting the size of the array. +;; The second line contains n space-separated integers representing the array's elements. + +;; Output Format +;; Print the sum of the array's elements as a single integer. + +;; Sample Input +;; 6 +;; 1 2 3 4 10 11 + +;; Sample Output +;; 31 + +(defn simpleArraySum + [ar] + (reduce + ar) +) + +(def fptr (get (System/getenv) "OUTPUT_PATH")) + +(def ar-count (Integer/parseInt (clojure.string/trim (read-line)))) + +(def ar (vec (map #(Integer/parseInt %) (clojure.string/split (clojure.string/trimr (read-line)) #" ")))) + +(def result (simpleArraySum ar)) + +(spit fptr (str result "\n") :append true) From 76b08992af1c3695a57299a9dbdeb54dbb052f3c Mon Sep 17 00:00:00 2001 From: Anant Kaushik Date: Wed, 28 Jul 2021 14:48:34 +0530 Subject: [PATCH 33/49] Query params parser added --- Clojure/other/query_params_parser.clj | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 Clojure/other/query_params_parser.clj diff --git a/Clojure/other/query_params_parser.clj b/Clojure/other/query_params_parser.clj new file mode 100644 index 0000000..a1eea72 --- /dev/null +++ b/Clojure/other/query_params_parser.clj @@ -0,0 +1,15 @@ +;; Given a query string "param1=v1¶m2=v2¶m3=v3" generate a map of the form: +;; {:param1 "v1", param2 "v2", :param3 "v3"} for now you can try it with simple string values. + +(require '[clojure.string :as s]) + +(defn convert-key-value + [key-value] + (vector (keyword (first key-value)) (second key-value)) +) + +(defn generate-params-map + [params-str] + (into {} (map #(convert-key-value (s/split % #"=")) (s/split params-str #"&"))) +) +(println (generate-params-map "param1=v1¶m2=v2¶m3=v3")) From b4cc6a870d4ca15f668c9a11dc1a56d3803b1b8f Mon Sep 17 00:00:00 2001 From: anant Date: Thu, 29 Jul 2021 21:05:47 +0530 Subject: [PATCH 34/49] Query Params Parser Add another approach to solve the problem using "reduce". --- Clojure/other/query_params_parser.clj | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Clojure/other/query_params_parser.clj b/Clojure/other/query_params_parser.clj index a1eea72..af141f7 100644 --- a/Clojure/other/query_params_parser.clj +++ b/Clojure/other/query_params_parser.clj @@ -3,6 +3,7 @@ (require '[clojure.string :as s]) +;Method 1 (defn convert-key-value [key-value] (vector (keyword (first key-value)) (second key-value)) @@ -13,3 +14,21 @@ (into {} (map #(convert-key-value (s/split % #"=")) (s/split params-str #"&"))) ) (println (generate-params-map "param1=v1¶m2=v2¶m3=v3")) + + +;Method 2 +(defn generate-params-map + "Function to convert query param string to map" + [params-str] + (reduce (fn [params-map param-key-val] + (conj params-map + (#((fn [key-value] + (hash-map (keyword (first key-value)) (second key-value))) + (s/split % #"=")) + param-key-val))) + {} + (s/split params-str #"&") + ) + ) + +(println (generate-params-map "param1=v1¶m2=v2¶m3=v3")) From 87210650478d60978a547537a85f0ab4d6f20bfe Mon Sep 17 00:00:00 2001 From: anant Date: Fri, 30 Jul 2021 23:59:21 +0530 Subject: [PATCH 35/49] FizzBuzz --- Clojure/hackerearth/fizzbuzz.clj | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) create mode 100644 Clojure/hackerearth/fizzbuzz.clj diff --git a/Clojure/hackerearth/fizzbuzz.clj b/Clojure/hackerearth/fizzbuzz.clj new file mode 100644 index 0000000..55190b0 --- /dev/null +++ b/Clojure/hackerearth/fizzbuzz.clj @@ -0,0 +1,25 @@ +;Problem Link: https://www.hackerearth.com/problem/algorithm/fizzbuzz/ +; +;Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number +;and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. +;Print a new line after each string or number. + +(defn fizz-buzz + [number] + (map + (fn [n] + (let [result + (str + (if (zero? (mod n 3)) + "Fizz") + (if (zero? (mod n 5)) + "Buzz"))] + (if (empty? result) + (println n) + (println result)) + )) + (range 1 (inc number))) + ) +(def x (Integer/parseInt (read-line))) +(println x) +(fizz-buzz x) From 613a2e12ccc705029f881fc417e48ba217d1e152 Mon Sep 17 00:00:00 2001 From: anant Date: Sat, 31 Jul 2021 22:46:58 +0530 Subject: [PATCH 36/49] Update .gitignore Add .idea/ in .gitignore. --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index f8fffd6..dc824b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ Python/GeeksforGeeks/.DS_Store +.idea/ From 85c67b6b753a87cc7e1f7dd56d95fc7f4caed693 Mon Sep 17 00:00:00 2001 From: anant Date: Sat, 31 Jul 2021 22:48:27 +0530 Subject: [PATCH 37/49] Fizzbuzz --- Clojure/hackerearth/fizzbuzz.clj | 42 ++++++++++++++++---------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/Clojure/hackerearth/fizzbuzz.clj b/Clojure/hackerearth/fizzbuzz.clj index 55190b0..f205a71 100644 --- a/Clojure/hackerearth/fizzbuzz.clj +++ b/Clojure/hackerearth/fizzbuzz.clj @@ -1,25 +1,25 @@ -;Problem Link: https://www.hackerearth.com/problem/algorithm/fizzbuzz/ -; -;Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number -;and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”. -;Print a new line after each string or number. +;; Problem Link: https://www.hackerearth.com/problem/algorithm/fizzbuzz/ +;; Write a program that prints the numbers from 1 to 100. But for +;; multiples of three print “Fizz” instead of the number +;; and for the multiples of five print “Buzz”. For numbers which are +;; multiples of both three and five print “FizzBuzz”. +;; Print a new line after each string or number. (defn fizz-buzz - [number] - (map - (fn [n] - (let [result - (str - (if (zero? (mod n 3)) - "Fizz") - (if (zero? (mod n 5)) - "Buzz"))] - (if (empty? result) - (println n) - (println result)) - )) - (range 1 (inc number))) - ) + [number] + (map + (fn [n] + (let [result + (str + (if (zero? (mod n 3)) + "Fizz") + (if (zero? (mod n 5)) + "Buzz"))] + (println (if (empty? result) + n + result)))) + (range 1 (inc number)))) + + (def x (Integer/parseInt (read-line))) -(println x) (fizz-buzz x) From f446c5d96e7c2abbeb4ef655776ecc9fad679cb3 Mon Sep 17 00:00:00 2001 From: anant Date: Sun, 1 Aug 2021 23:17:11 +0530 Subject: [PATCH 38/49] Fibonacci Series --- Clojure/hackerearth/fibonacci-series.clj | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 Clojure/hackerearth/fibonacci-series.clj diff --git a/Clojure/hackerearth/fibonacci-series.clj b/Clojure/hackerearth/fibonacci-series.clj new file mode 100644 index 0000000..e1d0a53 --- /dev/null +++ b/Clojure/hackerearth/fibonacci-series.clj @@ -0,0 +1,24 @@ +;; Problem Statement: https://www.hackerearth.com/problem/algorithm/fibonacci-seris/ + +;; Write a program to display nth term of fibonacci series of n terms. +;; Sample Input +;; 13 +;; Sample Output +;; 144 +;; Explanation +;; Here, the given input is 13, so 13th term of fibonacci series is 144 and it will be printed +;; out as the answer. + +(def x (Integer/parseInt (read-line))) + + +(defn generate-fibonacci-number + ([number previous current] + (if (= number 1) + (str current) + (recur (- number 1) current (+ current previous)))) + ([number] + (generate-fibonacci-number (- number 1) (bigint 0) (bigint 1)))) + + +(println (generate-fibonacci-number x)) From b696c8a2c1982c60bf886bc9574a4b5ab0ea3e1e Mon Sep 17 00:00:00 2001 From: anant Date: Mon, 2 Aug 2021 23:49:32 +0530 Subject: [PATCH 39/49] Word Frequency counter --- .../hackerearth/word-frequency-counter.clj | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Clojure/hackerearth/word-frequency-counter.clj diff --git a/Clojure/hackerearth/word-frequency-counter.clj b/Clojure/hackerearth/word-frequency-counter.clj new file mode 100644 index 0000000..ac648a1 --- /dev/null +++ b/Clojure/hackerearth/word-frequency-counter.clj @@ -0,0 +1,48 @@ +; Problem Link: https://www.hackerearth.com/problem/algorithm/word-frequency-counter/ + +; You will be provided with a passage (no special characters, no punctuations). Your task is to +; find the frequency of the words occurring in the text, in other words find the number of times a +; word occurs in the given passage. +; Input +; A string with no special characters or punctuations. +; Output +; Output should be in the format: +; Word Count +; where Word is a string in the passage, and count is an integer representing number of times the +; Word has appeared in the passage. Word and the count must be separated by a space. +; Words and their count must be listed out in same order as given in the passage. +; Passage will be given as a single string, and not in paragraphs. +; +; Constrains +; 0 <= W <= 1000 +; where W is the number of words in the passage. +; Note +; strings 'apple', 'APPLE', 'Apple' are all considered to be instances of the same word 'APPLE'. +; In Output, all letters of the words must be converted into UPPERCASE.(Refer Sample Input/Output) + +; Sample Input +; My name is Xyz He is Abc Is he allright +; Sample Output +; MY 1 +; NAME 1 +; IS 3 +; XYZ 1 +; HE 2 +; ABC 1 +; ALLRIGHT 1 + +(require '[clojure.string :as s]) +(def input-sentence (read-line)) + +(defn get-words-frequencies + [sentence] + (reduce (fn [words-frequencies-map word] + (if (empty? word) + words-frequencies-map + (let [key (s/upper-case word)] + (assoc words-frequencies-map + key (+ (get words-frequencies-map key 0) 1))))) + {} + (s/split sentence #" "))) + +(map (fn [[key val]] (println key val)) (get-words-frequencies input-sentence)) From fdaf7617296ff6b49b38aa94500a895fd33939a3 Mon Sep 17 00:00:00 2001 From: anant Date: Sat, 16 Oct 2021 12:46:15 +0530 Subject: [PATCH 40/49] Check for BST --- Python/GeeksforGeeks/check-for-bst.py | 174 ++++++++++---------------- 1 file changed, 65 insertions(+), 109 deletions(-) diff --git a/Python/GeeksforGeeks/check-for-bst.py b/Python/GeeksforGeeks/check-for-bst.py index b503f25..a75a3b0 100644 --- a/Python/GeeksforGeeks/check-for-bst.py +++ b/Python/GeeksforGeeks/check-for-bst.py @@ -1,119 +1,75 @@ """ -Problem Link: https://practice.geeksforgeeks.org/problems/check-for-bst/1 +Given the root of a binary tree. Check whether it is a BST or not. +Note: We are considering that BSTs can not contain duplicate Nodes. +A BST is defined as follows: -Given a binary tree, return true if it is BST, else false. For example, the following tree is not BST, because 11 is in left subtree of 10. -The task is to complete the function isBST() which takes one argument, root of Binary Tree. +The left subtree of a node contains only nodes with keys less than the node's key. +The right subtree of a node contains only nodes with keys greater than the node's key. +Both the left and right subtrees must also be binary search trees. + - 10 - / \ - 7 39 - \ - 11 +Example 1: Input: -The input contains T, denoting number of testcases. For each testcase there will be two lines. The first line contains number of edges. -The second line contains two nodes and a character separated by space. The first node denotes data value, second node denotes -where it will be assigned to the previous node which will depend on character 'L' or 'R' i.e. the 2nd node will be assigned as -left child to the 1st node if character is 'L' and so on. The first node of second line is root node. The struct or class Node -has a data part which stores the data, pointer to left child and pointer to right child. There are multiple test cases. -For each test case, the function will be called individually. - -Output: -The function should return 1 if BST else return 0. - -User Task: -Since this is a functional problem you don't have to worry about input, you just have to complete the function isBST(). - -Constraints: -1 <= T <= 30 -1 <= Number of edges <= 100 -1 <= Data of a node <= 1000 + 2 + / \ +1 3 +Output: 1 +Explanation: +The left subtree of root node contains node +with key lesser than the root node’s key and +the right subtree of root node contains node +with key greater than the root node’s key. +Hence, the tree is a BST. +Example 2: -Example: Input: -2 -2 -1 2 R 1 3 L -4 -10 20 L 10 30 R 20 40 L 20 60 R - -Output: -0 -0 - -Explanation: -Testcases 1: The given binary tree is not BST, hence the answer is 0. -""" -class Node: - def __init__(self, value): - self.left = None - self.data = value - self.right = None -class Tree: # Binary tree Class - def createNode(self, data): - return Node(data) - def insert(self, node, data, ch): - if node is None: - return self.createNode(data) - if (ch == 'L'): - node.left = self.insert(node.left, data, ch) - return node.left - else: - node.right = self.insert(node.right, data, ch) - return node.right - def search(self, lis, data): - # if root is None or root is the search data. - for i in lis: - if i.data == data: - return i -if __name__=='__main__': - t=int(input()) - for i in range(t): - n=int(input()) - arr = input().strip().split() - if n==0: - print(1) - continue - tree = Tree() - lis=[] - root = None - root = tree.insert(root, int(arr[0]), 'L') - lis.append(root) - k=0 - for j in range(n): - ptr = None - ptr = tree.search(lis, int(arr[k])) - lis.append(tree.insert(ptr, int(arr[k+1]), arr[k+2])) - k+=3 - # tree.traverseInorder(root) - # print '' - if isBST(root): - print(1) - else: - print(0) + 2 + \ + 7 + \ + 6 + \ + 5 + \ + 9 + \ + 2 + \ + 6 +Output: 0 +Explanation: +Since the node with value 7 has right subtree +nodes with keys less than 7, this is not a BST. +Your Task: +You don't need to read input or print anything. Your task is to complete the function isBST() which takes the root of the tree +as a parameter and returns true if the given binary tree is BST, else returns false. -''' Please note that it's Function problem i.e. -you need to write your solution in the form of Function(s) only. -Driver Code to call/invoke your function is mentioned above. ''' +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(Height of the BST). -# Node definition +Constraints: +0 <= Number of edges <= 100000 """ -class Node: - def __init__(self, value): - self.left = None - self.data = value - self.right = None -""" -# Your task is to complete this function -# Function should return an 1/0 or True/False -def isBST(root,minn = float('-inf'), maxx=float('inf')): - # Code here - if not root: - return 1 - if root.data <= minn or root.data > maxx: - return 0 - if not isBST(root.left,minn,root.data): - return 0 - if not isBST(root.right,root.data,maxx): - return 0 - return 1 \ No newline at end of file +class Solution: + + #Function to check whether a Binary Tree is BST or not. + def isBST(self, root): + if not root: + return True + + stack = [] + cur = root + prev = None + + while stack or cur: + if cur: + stack.append(cur) + cur = cur.left + else: + node = stack.pop() + if prev and prev.data >= node.data: + return False + prev = node + cur = node.right + return True From 8926366ff7338c1a20828c3db68f4e90dd42271f Mon Sep 17 00:00:00 2001 From: anant Date: Mon, 18 Oct 2021 21:59:18 +0530 Subject: [PATCH 41/49] Sum Tree --- Python/GeeksforGeeks/sum-tree.py | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Python/GeeksforGeeks/sum-tree.py diff --git a/Python/GeeksforGeeks/sum-tree.py b/Python/GeeksforGeeks/sum-tree.py new file mode 100644 index 0000000..fae8563 --- /dev/null +++ b/Python/GeeksforGeeks/sum-tree.py @@ -0,0 +1,61 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/sum-tree/1 + +Given a Binary Tree. Return 1 if, for every node X in the tree other than the leaves, +its value is equal to the sum of its left subtree's value and its right subtree's value. Else return 0. +An empty tree is also a Sum Tree as the sum of an empty tree can be considered to be 0. +A leaf node is also considered a Sum Tree. + +Example 1: +Input: + 3 + / \ + 1 2 +Output: 1 +Explanation: +The sum of left subtree and right subtree is +1 + 2 = 3, which is the value of the root node. +Therefore,the given binary tree is a sum tree. + +Example 2: +Input: + + 10 + / \ + 20 30 + / \ + 10 10 +Output: 0 +Explanation: +The given tree is not a sum tree. +For the root node, sum of elements +in left subtree is 40 and sum of elements +in right subtree is 30. Root element = 10 +which is not equal to 30+40. + +Your Task: +You don't need to read input or print anything. Complete the function isSumTree() which takes root node +as input parameter and returns true if the tree is a SumTree else it returns false. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(Height of the Tree) + +Constraints: +1 ≤ number of nodes ≤ 104 +""" +class Solution: + def isSumTree(self,root): + return self.helper(root) != -1 + + def helper(self, root): + if not root: + return 0 + if not root.left and not root.right: + return root.data + + l = self.helper(root.left) + r = self.helper(root.right) + + if l == -1 or r == -1 or (l+r) != root.data: + return -1 + return root.data + l + r From e3c7b386e87abec8f121d0e9a00c3539f3044f9e Mon Sep 17 00:00:00 2001 From: anant Date: Tue, 19 Oct 2021 22:21:16 +0530 Subject: [PATCH 42/49] Preorder Traversal --- Python/GeeksforGeeks/preorder-traversal.py | 59 ++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/GeeksforGeeks/preorder-traversal.py diff --git a/Python/GeeksforGeeks/preorder-traversal.py b/Python/GeeksforGeeks/preorder-traversal.py new file mode 100644 index 0000000..8a3d3fc --- /dev/null +++ b/Python/GeeksforGeeks/preorder-traversal.py @@ -0,0 +1,59 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/preorder-traversal/1 + +Given a binary tree, find its preorder traversal. + +Example 1: +Input: + 1 + / + 4 + / \ +4 2 +Output: 1 4 4 2 + +Example 2: +Input: + 6 + / \ + 3 2 + \ / + 1 2 +Output: 6 3 1 2 2 + +Your Task: +You just have to complete the function preorder() which takes the root +node of the tree as input and returns an array containing the preorder +traversal of the tree. +Expected Time Complexity: O(N). +Expected Auxiliary Space: O(N). + +Constraints: +1 <= Number of nodes <= 104 +0 <= Data of a node <= 105 +""" +def preorder_iterative(root): + res = [] + stack = [root] + + while stack: + node = stack.pop() + res.append(node.data) + if node.right: + stack.append(node.right) + if node.left: + stack.append(node.left) + + return res + + +def preorder(root, res=None): + if not root: + return res + + if not res: + res = [] + res.append(root.data) + preorder(root.left, res) + preorder(root.right, res) + return res From 9739e2c3f0ebaf40fe2017761b3a11dce646e02c Mon Sep 17 00:00:00 2001 From: anant Date: Tue, 19 Oct 2021 22:36:50 +0530 Subject: [PATCH 43/49] Max Level Sum in Binary Tree --- .../max-level-sum-in-binary-tree.py | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Python/GeeksforGeeks/max-level-sum-in-binary-tree.py diff --git a/Python/GeeksforGeeks/max-level-sum-in-binary-tree.py b/Python/GeeksforGeeks/max-level-sum-in-binary-tree.py new file mode 100644 index 0000000..b17ef18 --- /dev/null +++ b/Python/GeeksforGeeks/max-level-sum-in-binary-tree.py @@ -0,0 +1,59 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1/ + +Given a Binary Tree having positive and negative nodes. +Find the maximum sum of a level in the given Binary Tree. + +Example 1: +Input : + 4 + / \ + 2 -5 + / \ / \ + -1 3 -2 6 +Output: 6 +Explanation : +Sum of all nodes of 0'th level is 4 +Sum of all nodes of 1'th level is -3 +Sum of all nodes of 2'th level is 6 +Hence maximum sum is 6 + +Example 2: +Input : + 1 + / \ + 2 3 + / \ \ + 4 5 8 + / \ + 6 7 +Output : 17 + +Explanation: Maximum sum is at level 2. + +Your Task: +You dont need to read input or print anything. Complete the function +maxLevelSum() which takes root node as input parameter and +returns the maximum sum of any horizontal level in the given Binary Tree. + +Expected Time Complexity: O(N) +Expected Auxiliary Space: O(N) +""" +class Solution: + def maxLevelSum(self, root): + return max(self.helper(root)) + + def helper(self, root, level=0, levels_sum=None): + if not root: + return 0 + + if not levels_sum: + levels_sum = [] + if level == len(levels_sum): + levels_sum.append(0) + + levels_sum[level] += root.data + + self.helper(root.left, level+1, levels_sum) + self.helper(root.right, level+1, levels_sum) + return levels_sum From 40bbccb90bd65590cc58ce1b6978db5b3186cb34 Mon Sep 17 00:00:00 2001 From: anant Date: Fri, 22 Oct 2021 10:28:07 +0530 Subject: [PATCH 44/49] Find the element that appears once --- .../GeeksforGeeks/element-appearing-once.py | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Python/GeeksforGeeks/element-appearing-once.py diff --git a/Python/GeeksforGeeks/element-appearing-once.py b/Python/GeeksforGeeks/element-appearing-once.py new file mode 100644 index 0000000..e377aef --- /dev/null +++ b/Python/GeeksforGeeks/element-appearing-once.py @@ -0,0 +1,46 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/element-appearing-once2552/1 + +Given a sorted array A[] of N positive integers having all the numbers +occurring exactly twice, except for one number which will occur only once. +Find the number occurring only once. + +Example 1: +Input: +N = 5 +A = {1, 1, 2, 5, 5} +Output: 2 +Explanation: +Since 2 occurs once, while +other numbers occur twice, +2 is the answer. + +Example 2: +Input: +N = 7 +A = {2, 2, 5, 5, 20, 30, 30} +Output: 20 +Explanation: +Since 20 occurs once, while +other numbers occur twice, +20 is the answer. +Your Task: +You don't need to read input or print anything. +Your task is to complete the function search() which takes two +arguments(array A and integer N) and returns the number occurring only once. + +Expected Time Complexity: O(Log(N)). +Expected Auxiliary Space: O(1). + +Constraints +0 < N <= 10^6 +0 <= A[i] <= 10^9 +""" +class Solution: + def search(self, A, N): + unique_element = A[0] + + for index in range(1, N): + unique_element ^= A[index] + + return unique_element From b1ccffcc65a81390a34dacdbf6af5217296c7742 Mon Sep 17 00:00:00 2001 From: anant Date: Sun, 16 Jan 2022 12:15:24 +0530 Subject: [PATCH 45/49] Topological sort --- Python/GeeksforGeeks/topological-sort.py | 31 ++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 Python/GeeksforGeeks/topological-sort.py diff --git a/Python/GeeksforGeeks/topological-sort.py b/Python/GeeksforGeeks/topological-sort.py new file mode 100644 index 0000000..08d24ac --- /dev/null +++ b/Python/GeeksforGeeks/topological-sort.py @@ -0,0 +1,31 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/topological-sort/1/ + +Given a Directed Acyclic Graph (DAG) with V vertices and E edges, Find any Topological Sorting of that Graph. + +Your Task: +You don't need to read input or print anything. Your task is to complete the function topoSort() +which takes the integer V denoting the number of vertices and adjacency list as input parameters and +returns an array consisting of a the vertices in Topological order. As there are multiple +Topological orders possible, you may return any of them. If your returned topo sort is correct +then console output will be 1 else 0. +""" +class Solution: + + #Function to return list containing vertices in Topological order. + def topoSort(self, V, adj): + visited = set() + res = [] + for v in range(V): + self.topologicalSort(v, adj, visited, res) + return res[::-1] + + def topologicalSort(self, node, adj, visited, res): + if node in visited: + return + + visited.add(node) + for neighbour in adj[node]: + self.topologicalSort(neighbour, adj, visited, res) + + res.append(node) From c1ad1734b40cacd2e200ab9bdec44bb62d661702 Mon Sep 17 00:00:00 2001 From: anant Date: Wed, 19 Jan 2022 14:02:33 +0530 Subject: [PATCH 46/49] Candy Crush --- Python/other/candy-crush.py | 38 +++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Python/other/candy-crush.py diff --git a/Python/other/candy-crush.py b/Python/other/candy-crush.py new file mode 100644 index 0000000..d7e7851 --- /dev/null +++ b/Python/other/candy-crush.py @@ -0,0 +1,38 @@ +""" +Implement 1-d Candy crush. Any sequence of 3 or more like items should be removed from left. +Input: "aabbbacd" +Output: "cd" +""" + +def candy_crush(input): + if not input: + return "" + + stack = [] + char = input[0] + f = 1 + + for index in range(1, len(input)): + if char == input[index]: # abccccbbaa f - 3 char-a stack = [] + f += 1 + else: + if f >= 3: + char = input[index] + if stack and char == stack[-1][0]: + f = stack.pop()[1] + 1 + else: + f = 1 + else: + stack.append([char, f]) + char = input[index] + f = 1 + + if f < 3: + stack.append([char, f]) + + res = [] + while stack: + char, f = stack.pop() + res.append(char*f) + + return "".join(res[::-1]) From 2dba1834880b661a58a527bda72efbf06c7aabf7 Mon Sep 17 00:00:00 2001 From: anant Date: Wed, 19 Jan 2022 21:54:46 +0530 Subject: [PATCH 47/49] Candy Crush --- Python/other/candy-crush.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Python/other/candy-crush.py b/Python/other/candy-crush.py index d7e7851..937c596 100644 --- a/Python/other/candy-crush.py +++ b/Python/other/candy-crush.py @@ -13,7 +13,7 @@ def candy_crush(input): f = 1 for index in range(1, len(input)): - if char == input[index]: # abccccbbaa f - 3 char-a stack = [] + if char == input[index]: f += 1 else: if f >= 3: From a4627e0dc613b8f8ca6f13412a2291271bcbd8fb Mon Sep 17 00:00:00 2001 From: anant Date: Thu, 20 Jan 2022 19:14:54 +0530 Subject: [PATCH 48/49] K Nearest Stars --- Python/other/k-nearest-stars.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 Python/other/k-nearest-stars.py diff --git a/Python/other/k-nearest-stars.py b/Python/other/k-nearest-stars.py new file mode 100644 index 0000000..8590fc5 --- /dev/null +++ b/Python/other/k-nearest-stars.py @@ -0,0 +1,27 @@ +""" +Given coordinates of stars in a galaxy and coordinate of planet. +Find the nearest K stars to the given planet. Assume the number of stars are large. +coordinate - (x, y, z) +""" +def find_nearest_stars(planet, stars, K): + if not stars: + return [] + + heap = [] + + for star in stars: + d = calculate_distance(planet, star) + if len(heap) < K: + heapq.heappush(heap, (-d, star)) + else: + heapq.heappushpop(heap, (-d, star)) + + res = [] + for _, star in heap: + res.append(star) + + return res + + +def calculate_distance(planet, star): + return math.sqrt((planet[0] - star[0]) ** 2 + (planet[1] - star[1]) ** 2 + (planet[2] - star[2]) ** 2) From 6dba38fd7aa4e71b5196d01d64e81f9336d08b13 Mon Sep 17 00:00:00 2001 From: anant Date: Mon, 21 Feb 2022 17:30:37 +0530 Subject: [PATCH 49/49] Minimum number of jumps --- .../GeeksforGeeks/minimum-number-of-jumps.py | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 Python/GeeksforGeeks/minimum-number-of-jumps.py diff --git a/Python/GeeksforGeeks/minimum-number-of-jumps.py b/Python/GeeksforGeeks/minimum-number-of-jumps.py new file mode 100644 index 0000000..9251755 --- /dev/null +++ b/Python/GeeksforGeeks/minimum-number-of-jumps.py @@ -0,0 +1,54 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/minimum-number-of-jumps-1587115620/1 + +Given an array of N integers arr[] where each element represents the max number of steps that can be made +forward from that element. Find the minimum number of jumps to reach the end of the array +(starting from the first element). If an element is 0, then you cannot move through that element. +Note: Return -1 if you can't reach the end of the array. + +Example 1: +Input: +N = 11 +arr[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9} +Output: 3 +Explanation: +First jump from 1st element to 2nd +element with value 3. Now, from here +we jump to 5th element with value 9, +and from here we will jump to last. + +Example 2: +Input : +N = 6 +arr = {1, 4, 3, 2, 6, 7} +Output: 2 +Explanation: +First we jump from the 1st to 2nd element +and then jump to the last element. + +Your task: +You don't need to read input or print anything. Your task is to complete function minJumps() +which takes the array arr and it's size N as input parameters and returns the minimum number of jumps. +If not possible returns -1. + +Expected Time Complexity: O(N) +Expected Space Complexity: O(1) + +Constraints: +1 ≤ N ≤ 107 +0 ≤ arri ≤ 107 +""" +class Solution: + def minJumps(self, arr, n): + max_reach = cur_reach = jumps = 0 + + for index in range(len(arr)): + if index > max_reach: + return -1 + + max_reach = max(max_reach, index + arr[index]) + if index == cur_reach and index != len(arr) - 1: + jumps += 1 + cur_reach = max_reach + + return jumps