diff --git a/.gitignore b/.gitignore index f8fffd6..dc824b6 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ Python/GeeksforGeeks/.DS_Store +.idea/ 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)))))) 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)) diff --git a/Clojure/hackerearth/fizzbuzz.clj b/Clojure/hackerearth/fizzbuzz.clj new file mode 100644 index 0000000..f205a71 --- /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"))] + (println (if (empty? result) + n + result)))) + (range 1 (inc number)))) + + +(def x (Integer/parseInt (read-line))) +(fizz-buzz x) 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) 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)) 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) 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)))) diff --git a/Clojure/other/query_params_parser.clj b/Clojure/other/query_params_parser.clj new file mode 100644 index 0000000..af141f7 --- /dev/null +++ b/Clojure/other/query_params_parser.clj @@ -0,0 +1,34 @@ +;; 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]) + +;Method 1 +(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")) + + +;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")) 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) 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 diff --git a/Python/Rock_Paper_Scissor.py b/Python/GeeksforGeeks/Rock_Paper_Scissor.py similarity index 100% rename from Python/Rock_Paper_Scissor.py rename to Python/GeeksforGeeks/Rock_Paper_Scissor.py diff --git a/Python/GeeksforGeeks/add-two-numbers-represented-by-linked-lists.py b/Python/GeeksforGeeks/add-two-numbers-represented-by-linked-lists.py new file mode 100644 index 0000000..3f4daca --- /dev/null +++ b/Python/GeeksforGeeks/add-two-numbers-represented-by-linked-lists.py @@ -0,0 +1,140 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/add-two-numbers-represented-by-linked-lists/1 + +Given two numbers represented by two linked lists of size N and M. The task is to return a sum list. +The sum list which is a linked list representation of addition of two input numbers. + +Input: +First line of input contains number of testcases T. For each testcase, first line of input +contains length of first linked list and next line contains N elements of the linked list. +Again, next line contains M, and following line contains M elements of the linked list. + +Output: +Output the resultant linked list. + +User Task: +The task is to complete the function addTwoLists() which has node reference of both the +linked lists and returns the head of new list. + +Constraints: +1 <= T <= 100 +1 <= N, M <= 100 + +Example: +Input: +2 +2 +4 5 +3 +3 4 5 +2 +6 3 +1 +7 + +Output: +0 9 3 +0 7 + +Explaination: +5->4 // linked list repsentation of 45. +5->4->3 // linked list representation of 345. +0->9 ->3 // linked list representation of 390 resultant linked list. +""" +import atexit +import io +import sys +_INPUT_LINES = sys.stdin.read().splitlines() +input = iter(_INPUT_LINES).__next__ +_OUTPUT_BUFFER = io.StringIO() +sys.stdout = _OUTPUT_BUFFER +@atexit.register +def write(): + sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) + +# Node Class +class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None +# Linked List Class +class LinkedList: + def __init__(self): + self.head = None + # creates a new node with given value and appends it at the end of the linked list + def append(self, new_value): + new_node = Node(new_value) + if self.head is None: + self.head = new_node + return + curr_node = self.head + while curr_node.next is not None: + curr_node = curr_node.next + curr_node.next = new_node +# prints the elements of linked list starting with head +def printList(head): + if head is None: + print(' ') + return + curr_node = head + while curr_node: + print(curr_node.data,end=" ") + curr_node=curr_node.next + print(' ') +if __name__ == '__main__': + t=int(input()) + for cases in range(t): + n_a = int(input()) + a = LinkedList() # create a new linked list 'a'. + nodes_a = list(map(int, input().strip().split())) + nodes_a = nodes_a[::-1] # reverse the input array + for x in nodes_a: + a.append(x) # add to the end of the list + n_b =int(input()) + b = LinkedList() # create a new linked list 'b'. + nodes_b = list(map(int, input().strip().split())) + nodes_b = nodes_b[::-1] # reverse the input array + for x in nodes_b: + b.append(x) # add to the end of the list + result_head = addBoth(a.head,b.head) + printList(result_head) +''' This is a function problem.You only need to complete the function given below ''' +#User function Template for python3 +''' + Function to add two numbers represented + in the form of the linked list. + + Function Arguments: head_a and head_b (heads of both the linked lists) + Return Type: head of the resultant linked list. + + __>IMP : numbers are represented in reverse in the linked list. + Ex: + 145 is represented as 5->4->1. + + resultant head is expected in the same format. + +# Node Class +class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None +''' +def addBoth(head_a,head_b): + #code here + res = Node(0) + cur = res + carry = 0 + while head_a or head_b: + x = head_a.data if head_a else 0 + y = head_b.data if head_b else 0 + summ = carry + x + y + carry = summ // 10 + cur.next = Node(summ%10) + cur = cur.next + if head_a: + head_a = head_a.next + if head_b: + head_b = head_b.next + if carry > 0: + cur.next = Node(carry) + return res.next \ No newline at end of file diff --git a/Python/GeeksforGeeks/anagram-palindrome.py b/Python/GeeksforGeeks/anagram-palindrome.py index db54983..05fa2fe 100644 --- a/Python/GeeksforGeeks/anagram-palindrome.py +++ b/Python/GeeksforGeeks/anagram-palindrome.py @@ -25,20 +25,16 @@ Yes No """ -import collections def palindromePermutation(s): - countOdd = 0 - d = collections.defaultdict(int) - for i in s: - d[i] += 1 - if d[i] % 2 == 1: - countOdd += 1 + alphabets = set() + for c in s: + if c in alphabets: + alphabets.remove(c) else: - countOdd -= 1 - return countOdd <= 1 + alphabets.add(c) + return len(alphabets) <= 1 + for _ in range(int(input())): - if palindromePermutation(input()): - print("Yes") - else: - print("No") \ No newline at end of file + print("Yes" if palindromePermutation(input()) else "No") + \ No newline at end of file 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 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 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 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()) 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 diff --git a/Python/GeeksforGeeks/count-alphabets.py b/Python/GeeksforGeeks/count-alphabets.py new file mode 100644 index 0000000..80ce292 --- /dev/null +++ b/Python/GeeksforGeeks/count-alphabets.py @@ -0,0 +1,36 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/count-alphabets/0 + +Given a string, print the number of alphabets present in the string. + +Input: +The first line of input contains an integer T denoting the number of test cases. +The description of T test cases follows.Each test case contains a single string. + +Output: +Print the number of alphabets present in the string. + +Constraints: +1<=T<=30 +1<=size of string <=100 + +Example: +Input: +2 +adjfjh23 +njnfn_+-jf + +Output: +6 +7 +""" +def count_alphabets(s): + count = 0 + for c in s: + if c.isalpha(): + count += 1 + return count + +for _ in range(int(input())): + s = input() + print(count_alphabets(s)) \ No newline at end of file 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 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 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 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 diff --git a/Python/GeeksforGeeks/delete-without-head-pointer.py b/Python/GeeksforGeeks/delete-without-head-pointer.py index 16db421..7041ed2 100644 --- a/Python/GeeksforGeeks/delete-without-head-pointer.py +++ b/Python/GeeksforGeeks/delete-without-head-pointer.py @@ -33,6 +33,85 @@ Explanation: Testcase 1: After deleting 20 from the linked list, we have remaining nodes as 10, 4 and 30. """ -def deleteNode(node): - node.val = node.next.val - node.next = node.next.next \ No newline at end of file +import atexit +import io +import sys +_INPUT_LINES = sys.stdin.read().splitlines() +input = iter(_INPUT_LINES).__next__ +_OUTPUT_BUFFER = io.StringIO() +sys.stdout = _OUTPUT_BUFFER +@atexit.register +def write(): + sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) + +# Node Class +class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None +# Linked List Class +class LinkedList: + def __init__(self): + self.head = None + # creates a new node with given value and appends it at the end of the linked list + def append(self, new_value): + new_node = Node(new_value) + if self.head is None: + self.head = new_node + return + curr_node = self.head + while curr_node.next is not None: + curr_node = curr_node.next + curr_node.next = new_node + def getNode(self,value): # return node with given value, if not present return None + curr_node=self.head + while(curr_node.next and curr_node.data != value): + curr_node=curr_node.next + if(curr_node.data==value): + return curr_node + else: + return None + # prints the elements of linked list starting with head + def printList(self): + if self.head is None: + print(' ') + return + curr_node = self.head + while curr_node: + print(curr_node.data,end=" ") + curr_node=curr_node.next + print(' ') +if __name__ == '__main__': + t=int(input()) + for cases in range(t): + n = int(input()) + a = LinkedList() # create a new linked list 'a'. + nodes = list(map(int, input().strip().split())) + for x in nodes: + a.append(x) + del_elem = int(input()) + to_delete=a.getNode(del_elem) + deleteNode(to_delete) + a.printList() +''' This is a function problem.You only need to complete the function given below ''' +#User function Template for python3 +''' + Your task is to delete the given node from + the linked list, without using head pointer. + + Function Arguments: node (given node to be deleted) + Return Type: None, just delete the given node from the linked list. + { + # Node Class + class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None + } +''' +def deleteNode(curr_node): + #code here + if not curr_node: + return None + curr_node.data = curr_node.next.data + curr_node.next = curr_node.next.next \ No newline at end of file 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 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 diff --git a/Python/GeeksforGeeks/equilibrium-point.py b/Python/GeeksforGeeks/equilibrium-point.py new file mode 100644 index 0000000..de4c8cd --- /dev/null +++ b/Python/GeeksforGeeks/equilibrium-point.py @@ -0,0 +1,53 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/equilibrium-point/0/ + +Given an array A of N positive numbers. The task is to find the position where equilibrium +first occurs in the array. Equilibrium position in an array is a position such that the +sum of elements before it is equal to the sum of elements after it. + +Input: +The first line of input contains an integer T, denoting the number of test cases. +Then T test cases follow. First line of each test case contains an integer N denoting +the size of the array. Then in the next line are N space separated values of the array A. + +Output: +For each test case in a new line print the position at which the elements are at equilibrium +if no equilibrium point exists print -1. + +Constraints: +1 <= T <= 100 +1 <= N <= 106 +1 <= Ai <= 108 + +Example: +Input: +2 +1 +1 +5 +1 3 5 2 2 + +Output: +1 +3 + +Explanation: +Testcase 1: Since its the only element hence its the only equilibrium point. +Testcase 2: For second test case equilibrium point is at position 3 as elements +below it (1+3) = elements after it (2+2). +""" +def findEquilibrium(arr): + right_sum = sum(arr) + index = 0 + left_sum = 0 + for i in range(len(arr)): + right_sum -= arr[i] + if left_sum == right_sum: + return i+1 + left_sum += arr[i] + return -1 + +for _ in range(int(input())): + n = int(input()) + arr = list(map(int,input().split())) + print(findEquilibrium(arr)) \ No newline at end of file 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 diff --git a/Python/GeeksforGeeks/find-the-closest-number.py b/Python/GeeksforGeeks/find-the-closest-number.py index 93050d1..63ba5ae 100644 --- a/Python/GeeksforGeeks/find-the-closest-number.py +++ b/Python/GeeksforGeeks/find-the-closest-number.py @@ -31,26 +31,20 @@ 3 5 """ -def binarySearch(arr,target): +def binarySearch(arr, target): l = len(arr) - 1 - start,end = 0,l + start,end = 1,l-1 while start <= end: mid = (start+end)//2 if arr[mid] == target: - return mid + return arr[mid] elif arr[mid] > target: end = mid - 1 else: start = mid + 1 - return mid + return arr[end] if target - nums[end] < nums[end+1] - target else arr[end+1] for _ in range(int(input())): n,k = map(int,input().split()) - a = list(map(int,input().split())) - mid = binarySearch(a, k) - if mid < n-1 and (a[mid+1]-k) <= (k-a[mid]): - print(a[mid+1]) - elif mid > 1 and (k-a[mid-1])<(a[mid]-k): - print(a[mid-1]) - else: - print(a[mid]) \ No newline at end of file + nums = list(map(int,input().split())) + print(binarySearch(nums, k)) 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 diff --git a/Python/GeeksforGeeks/intersection-point-in-y-shapped-linked-lists.py b/Python/GeeksforGeeks/intersection-point-in-y-shapped-linked-lists.py new file mode 100644 index 0000000..6015035 --- /dev/null +++ b/Python/GeeksforGeeks/intersection-point-in-y-shapped-linked-lists.py @@ -0,0 +1,124 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/intersection-point-in-y-shapped-linked-lists/1/ + +There are two singly linked lists of size N and M in a system. But, due to some programming +error the end node of one of the linked list got linked into one of the node of second list, +forming a inverted Y shaped list. Write a program to get the point where two linked lists +intersect each other. + +Input: +First line of input is the number of test cases T. Every test case has four lines. +First line of every test case contains three numbers, x (number of nodes before +merge point in 1st list), y (number of nodes before merge point in 11nd list) +and z (number of nodes after merge point). Next three lines contain x, y and z values. + +Output: +Print the data of the node in the linked list where two linked lists intersects. + +Your Task: +The task is to complete the function intersetPoint() which finds the point of intersection +of two linked list. The function should return data value of a node where two linked lists merge. +If linked list do not merge at any point, then it shoudl return -1. + +Constraints: +1 <= T <= 50 +1 <= N <= 100 +1 <= value <= 1000 + +Example: +Input: +2 +2 3 2 +10 20 +30 40 50 +5 10 +2 3 2 +10 20 +30 40 50 +10 20 + +Output: +5 +10 + +Explanation: +Testcase 1: The point of intersection of two linked list is 5, means both of them get +linked (intersects) with each other at node whose value is 5. +""" +import atexit +import io +import sys +_INPUT_LINES = sys.stdin.read().splitlines() +input = iter(_INPUT_LINES).__next__ +_OUTPUT_BUFFER = io.StringIO() +sys.stdout = _OUTPUT_BUFFER +@atexit.register +def write(): + sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) +# Node Class +class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None +# Linked List Class +class LinkedList: + def __init__(self): + self.head = None + # creates a new node with given value and appends it at the end of the linked list + def append(self, new_node): + if self.head is None: + self.head = new_node + return + curr_node = self.head + while curr_node.next is not None: + curr_node = curr_node.next + curr_node.next = new_node +if __name__ == '__main__': + t=int(input()) + for cases in range(t): + x,y,z = map(int,input().strip().split()) + a = LinkedList() # create a new linked list 'a'. + b = LinkedList() # create a new linked list 'b'. + nodes_a = list(map(int, input().strip().split())) + nodes_b = list(map(int, input().strip().split())) + nodes_common = list(map(int, input().strip().split())) + for x in nodes_a: + node=Node(x) + a.append(node) # add to the end of the list + for x in nodes_b: + node=Node(x) + b.append(node) # add to the end of the list + for i in range(len(nodes_common)): + node=Node(nodes_common[i]) + a.append(node) # add to the end of the list a + if i== 0: + b.append(node) # add to the end of the list b, only the intersection + if intersetPoint(a.head,b.head) == -1: + print(-1) + else: + print(intersetPoint(a.head,b.head).data) #print data present at the node. +''' This is a function problem.You only need to complete the function given below ''' +#User function Template for python3 +''' + Your task is to return the point of intersection + in two linked list, connected in y shaped form. + + Function Arguments: head_a, head_b (heads of both the lists) + + Return Type: NODE present at the point of intersection, or -1 if no common point. + { + # Node Class + class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None + } +''' +def intersetPoint(head_a,head_b): + #code here + APointer = head_a + BPointer = head_b + while APointer != BPointer: + APointer = APointer.next if APointer.next else head_b + BPointer = BPointer.next if BPointer.next else head_a + return APointer \ No newline at end of file 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=" ") 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] diff --git a/Python/GeeksforGeeks/largest-subarray-of-0s-and-1s.py b/Python/GeeksforGeeks/largest-subarray-of-0s-and-1s.py new file mode 100644 index 0000000..93a36c9 --- /dev/null +++ b/Python/GeeksforGeeks/largest-subarray-of-0s-and-1s.py @@ -0,0 +1,59 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/largest-subarray-of-0s-and-1s/1/ + +Given an array of 0's and 1's your task is to complete the function maxLen which returns +size of the largest sub array with equal number of 0's and 1's. The function maxLen +takes 2 arguments. The first argument is the array A[] and second argument is the +size 'N' of the array A[]. + +Input: +The first line of the input is T denoting the number of test cases. Then T test cases follow. +Each test case contains two lines. The first line of each test case is a number N denoting +the size of the array and in the next line are N space separated values of A []. + +Output: +For each test case output in a new line the max length of the subarray. + +Constraints: +1 <= T <= 100 +1 <= N <= 100 +0 <= A[] <= 1 + +Example: +Input +2 +4 +0 1 0 1 +5 +0 0 1 0 0 + +Output +4 +2 + +Explanation: +Testacase 1: The array from index [0...3] contains equal number of 0's and 1's. +Thus maximum length of subarray having equal number of 0's and 1's is 4. +""" +if __name__=='__main__': + t=int(input()) + for i in range(t): + n = int(input()) + arr = list(map(int, input().strip().split())) + print(maxLen(n, arr)) +''' This is a function problem.You only need to complete the function given below ''' +# Your task is to complete this function +# Function should return an integer +def maxLen(n, lis): + #code here + d = {} + d[0] = -1 + maxLen = count = 0 + for i in range(len(lis)): + count += 1 if lis[i] == 1 else -1 + if count in d: + maxLen = max(maxLen, i-d[count]) + else: + d[count] = i + return maxLen + diff --git a/Python/last_index.py b/Python/GeeksforGeeks/last_index.py similarity index 100% rename from Python/last_index.py rename to Python/GeeksforGeeks/last_index.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 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) 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 diff --git a/Python/GeeksforGeeks/maximum-difference.py b/Python/GeeksforGeeks/maximum-difference.py new file mode 100644 index 0000000..a71255e --- /dev/null +++ b/Python/GeeksforGeeks/maximum-difference.py @@ -0,0 +1,46 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/maximum-difference/0 + +You are given an array A (distinct elements) of size N. Find out the maximum difference +between any two elements such that larger element appears after the smaller number in A. + +Input: +The first line of input contains an integer T denoting the number of test cases. T testcases follow. +Each testcase contains two lines of input. The first line of each test case is N,N is the size of array. The second line of each test case contains N elements separated by spaces. + +Output: +For each testcase, print the maximum difference between two element. Otherwise print -1 + +Constraints: +1 <= T <= 100 +2 <= N <= 107 +0 <= Ai <= 107 + +Example: +Input: +2 +7 +2 3 10 6 4 8 1 +6 +7 9 5 6 3 2 + +Output: +8 +2 +Explanation: +Testcase1: Array is [2, 3, 10, 6, 4, 8, 1] then returned value is 8 (Diff between 10 and 2). +Testcase2: Array is [ 7, 9, 5, 6, 3, 2 ] then returned value is 2 (Diff between 7 and 9). +""" +def maxDifference(arr): + maxDiff = -1 + curMin = arr[0] + for i in range(1,len(arr)): + maxDiff = max(maxDiff,arr[i]-curMin) + if arr[i] < curMin: + curMin = arr[i] + return maxDiff + +for _ in range(int(input())): + n = int(input()) + arr = list(map(int,input().split())) + print(maxDifference(arr)) \ No newline at end of file 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] diff --git a/Python/GeeksforGeeks/merge-k-sorted-linked-lists.py b/Python/GeeksforGeeks/merge-k-sorted-linked-lists.py new file mode 100644 index 0000000..6a71843 --- /dev/null +++ b/Python/GeeksforGeeks/merge-k-sorted-linked-lists.py @@ -0,0 +1,148 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/merge-k-sorted-linked-lists/1 + +Given K sorted linked lists of different sizes. The task is to merge them in such a +way that after merging they will be a single sorted linked list. + +Input: +First line of input contains number of testcases T. For each testcase, first line +of input contains number of linked lists N and next line contains data of nodes of +all K linked lists, with first element as M, the length of linked list and +next M elements for the same linked list. + +Output: +For each testcase, in a new line, print the merged linked list. + +Your Task: +The task is to complete the function mergeKList() which merges the K given lists into a sorted one. +The printing is done automatically by the driver code. + +Constraints +1 <= T <= 50 +1 <= N <= 103 + +Example: +Input: +2 +4 +3 1 2 3 2 4 5 2 5 6 2 7 8 +3 +2 1 3 3 4 5 6 1 8 + +Output: +1 2 3 4 5 5 6 7 8 +1 2 3 4 5 6 8 + +Explanation : +Testcase 1: The test case has 4 sorted linked list of size 3, 2, 2, 2 +1st list 1 -> 2-> 3 +2nd list 4->5 +3rd list 5->6 +4th list 7->8 +The merged list will be 1->2->3->4->5->5->6->7->8. +""" +#Initial Template for Python 3 +import atexit +import io +import sys +_INPUT_LINES = sys.stdin.read().splitlines() +input = iter(_INPUT_LINES).__next__ +_OUTPUT_BUFFER = io.StringIO() +sys.stdout = _OUTPUT_BUFFER +@atexit.register +def write(): + sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) +# Node Class +class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None +# Linked List Class +class LinkedList: + def __init__(self): + self.head = None + # creates a new node with given value and appends it at the end of the linked list + def append(self, new_value): + new_node = Node(new_value) + if self.head is None: + self.head = new_node + return + curr_node = self.head + while curr_node.next is not None: + curr_node = curr_node.next + curr_node.next = new_node +# prints the elements of linked list starting with head +def printList(head): + if head is None: + print(' ') + return + curr_node = head + while curr_node: + print(curr_node.data,end=" ") + curr_node=curr_node.next + print(' ') +if __name__ == '__main__': + t=int(input()) + for cases in range(t): + n = int(input()) + a= [] + for i in range(n): + a.append(LinkedList()) + list_info = list(map(int,input().strip().split())) + curr_ind = 0 + curr_list_ind = 0 + while curr_ind < len(list_info): + nodes= list_info[curr_ind] + curr_ind+=1 + for i in range(nodes): + a[curr_list_ind].append(list_info[curr_ind]) + curr_ind += 1 + curr_list_ind += 1 + heads = [] + for i in range(n): + heads.append(a[i].head) + printList(merge(heads,n)) + +''' This is a function problem.You only need to complete the function given below ''' +#User function Template for python3 +''' + Your task is to merge the given k sorted + linked lists into one list and return + the head of the new formed linked list. + + Function Arguments: array "heads" (containing heads of linked lists), n size of array a. + Return Type: head node.; + { + # Node Class + class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None + } +''' +def merge(lists,n): + if not lists: return None + length = len(lists) + interval = 1 + while interval < length: + for i in range(0, length - interval, interval*2): + lists[i] = mergeLists(lists[i], lists[i+interval]) + interval *= 2 + return lists[0] + +def mergeLists(l1, l2): + if not l1 or not l2: + return l1 or l2 + head = Node(0) + cur = head + while l1 and l2: + if l1.data < l2.data: + cur.next = l1 + l1 = l1.next + else: + cur.next = l2 + l2 = l2.next + cur = cur.next + if l1 or l2: + cur.next = l1 or l2 + return head.next \ No newline at end of file diff --git a/Python/GeeksforGeeks/merge-two-sorted-linked-lists.py b/Python/GeeksforGeeks/merge-two-sorted-linked-lists.py new file mode 100644 index 0000000..575a864 --- /dev/null +++ b/Python/GeeksforGeeks/merge-two-sorted-linked-lists.py @@ -0,0 +1,117 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/merge-two-sorted-linked-lists/1 + +Given two sorted linked lists consisting of N and M nodes respectively. The task is to merge +both of the list (in-place) and return head of the merged list. +Note: It is strongly recommended to do merging in-place using O(1) extra space. + +Input: +First line of input contains number of testcases T. For each testcase, first line of +input contains N and M, and next two line contains N and M sorted elements in two lines for each. + +Output: +For each testcase, print the merged list in sorted form. + +User Task: +The task is to complete the function sortedMerge() which takes references to the heads of +two linked lists as the arguments and returns the head of merged linked list. + +Constraints: +1 <= T <= 200 +1 <= N, M <= 103 +1 <= Node's data <= 103 + +Example: +Input: +2 +4 3 +5 10 15 40 +2 3 20 +2 2 +1 1 +2 4 + +Output: +2 3 5 10 15 20 40 +1 1 2 4 + +Explanation: +Testcase 1: After merging the two linked lists, we have merged list as 2, 3, 5, 10, 15, 20, 40. +""" +#Initial Template for Python 3 +# Node Class +class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None +# Linked List Class +class LinkedList: + def __init__(self): + self.head = None + # creates a new node with given value and appends it at the end of the linked list + def append(self, new_value): + new_node = Node(new_value) + if self.head is None: + self.head = new_node + return + curr_node = self.head + while curr_node.next is not None: + curr_node = curr_node.next + curr_node.next = new_node + # prints the elements of linked list starting with head + def printList(self): + if self.head is None: + print(' ') + return + curr_node = self.head + while curr_node: + print(curr_node.data,end=" ") + curr_node=curr_node.next + print(' ') +if __name__ == '__main__': + t=int(input()) + for cases in range(t): + n,m = map(int, input().strip().split()) + a = LinkedList() # create a new linked list 'a'. + b = LinkedList() # create a new linked list 'b'. + nodes_a = list(map(int, input().strip().split())) + nodes_b = list(map(int, input().strip().split())) + for x in nodes_a: + a.append(x) + for x in nodes_b: + b.append(x) + a.head = merge(a.head,b.head) + a.printList() +''' This is a function problem.You only need to complete the function given below ''' +#User function Template for python3 +''' + Function to merge two sorted lists in one + using constant space. + + Function Arguments: head_a and head_b (head reference of both the sorted lists) + Return Type: head of the obtained list after merger. + { + # Node Class + class Node: + def __init__(self, data): # data -> value stored in node + self.data = data + self.next = None + } +''' +def merge(head_a,head_b): + #code here + if not head_a or not head_b: + return head_a or head_b + newHead = Node(0) + prev = newHead + while head_a and head_b: + if head_a.data < head_b.data: + prev.next = head_a + prev = head_a + head_a = head_a.next + else: + prev.next = head_b + prev = head_b + head_b = head_b.next + prev.next = head_a or head_b + return newHead.next \ No newline at end of file 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 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 diff --git a/Python/minimum-product-pair.py b/Python/GeeksforGeeks/minimum-product-pair.py similarity index 100% rename from Python/minimum-product-pair.py rename to Python/GeeksforGeeks/minimum-product-pair.py diff --git a/Python/GeeksforGeeks/missing-number-in-array.py b/Python/GeeksforGeeks/missing-number-in-array.py index 09c3158..1487a52 100644 --- a/Python/GeeksforGeeks/missing-number-in-array.py +++ b/Python/GeeksforGeeks/missing-number-in-array.py @@ -33,7 +33,6 @@ for _ in range(int(input())): n = int(input()) arr = list(map(int,input().split())) - summ = 0 - for i in range(n-1): - summ += arr[i] - print(((n*(n+1))//2)-summ) \ No newline at end of file + actual_sum = n*(n+1)//2 + arr_sum = sum(arr) + print(actual_sum-arr_sum) \ No newline at end of file diff --git a/Python/GeeksforGeeks/missing-number.py b/Python/GeeksforGeeks/missing-number.py index edf3b90..3594cfa 100644 --- a/Python/GeeksforGeeks/missing-number.py +++ b/Python/GeeksforGeeks/missing-number.py @@ -30,9 +30,9 @@ For the second case Vaibhav placed 5 integers on the board, but picked up only 4 integers, so the missing number will be 4 so that it will become 1,2,3,4,5. """ -t = int(input()) -while t > 0: +for _ in range(int(input())): n = int(input()) - nums = list(map(int,input().split())) - print((n*(n+1))//2 - sum(nums)) - t -= 1 \ No newline at end of file + arr = list(map(int,input().split())) + actual_sum = n*(n+1)//2 + arr_sum = sum(arr) + print(actual_sum-arr_sum) \ No newline at end of file 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] diff --git a/Python/odd_even.py b/Python/GeeksforGeeks/odd_even.py similarity index 100% rename from Python/odd_even.py rename to Python/GeeksforGeeks/odd_even.py diff --git a/Python/palindromic_string.py b/Python/GeeksforGeeks/palindromic_string.py similarity index 100% rename from Python/palindromic_string.py rename to Python/GeeksforGeeks/palindromic_string.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 diff --git a/Python/pattern_number.py b/Python/GeeksforGeeks/pattern_number.py similarity index 100% rename from Python/pattern_number.py rename to Python/GeeksforGeeks/pattern_number.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 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 diff --git a/Python/remove_element.py b/Python/GeeksforGeeks/remove_element.py similarity index 100% rename from Python/remove_element.py rename to Python/GeeksforGeeks/remove_element.py diff --git a/Python/GeeksforGeeks/reverse-a-string-using-stack.py b/Python/GeeksforGeeks/reverse-a-string-using-stack.py new file mode 100644 index 0000000..2074e5a --- /dev/null +++ b/Python/GeeksforGeeks/reverse-a-string-using-stack.py @@ -0,0 +1,47 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/reverse-a-string-using-stack/1 + +An string of words is given, the task is to reverse the string using stack. + +Input Format: +The first line of input will contains an integer T denoting the no of test cases. +Then T test cases follow. Each test case contains a string s of words without spaces. + +Output Format: +For each test case ,print the reverse of the string in new line. + +Your Task: +Since this is a function problem, you don't need to take any input. Just complete the provided function. + +Constraints: +1 <= T <= 100 +1 <= length of the string <= 100 + +Example: +Input: +2 +GeeksQuiz +GeeksforGeeks +Output: +ziuQskeeG +skeeGrofskeeG +""" +{ + +if __name__=='__main__': + t=int(input()) + for i in range(t): + str1=input() + print(reverse(str1)) +} +''' This is a function problem.You only need to complete the function given below ''' + +def reverse(string): + stack = [] + for c in string: + stack.append(c) + reversedString = [] + while stack: + reversedString.append(stack.pop()) + return "".join(reversedString) + \ No newline at end of file diff --git a/Python/GeeksforGeeks/reverse-array-in-groups.py b/Python/GeeksforGeeks/reverse-array-in-groups.py new file mode 100644 index 0000000..f79b60d --- /dev/null +++ b/Python/GeeksforGeeks/reverse-array-in-groups.py @@ -0,0 +1,49 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/reverse-array-in-groups/0 + +Given an array arr[] of positive integers of size N. Reverse every sub-array of K group elements. + +Input: +The first line of input contains a single integer T denoting the number of test cases. Then T test cases follow. +Each test case consist of two lines of input. The first line of each test case consists of an integer N(size of array) and an integer K separated by a space. The second line of each test case contains N space separated integers denoting the array elements. + +Output: +For each test case, print the modified array. + +Constraints: +1 ≤ T ≤ 200 +1 ≤ N, K ≤ 107 +1 ≤ A[i] ≤ 1018 + +Example: +Input +2 +5 3 +1 2 3 4 5 +6 2 +10 20 30 40 50 60 + +Output +3 2 1 5 4 +20 10 40 30 60 50 + +Explanation: +Testcase 1: Reversing groups in size 3, first group consists of elements 1, 2, 3. +Reversing this group, we have elements in order as 3, 2, 1. +""" +def reverseInGroups(arr,k): + i = 0 + while i < len(arr): + index = i+k-1 if i+k-1 < len(arr) else len(arr)-1 + newIndex = index + 1 + while i < index: + arr[i],arr[index] = arr[index],arr[i] + index -= 1 + i += 1 + i = newIndex + return arr + +for _ in range(int(input())): + n,k = map(int,input().split()) + arr = list(map(int,input().split())) + print(*reverseInGroups(arr,k)) \ No newline at end of file diff --git a/Python/GeeksforGeeks/rock-paper-scissors.py b/Python/GeeksforGeeks/rock-paper-scissors.py deleted file mode 100644 index 4eb9b8c..0000000 --- a/Python/GeeksforGeeks/rock-paper-scissors.py +++ /dev/null @@ -1,62 +0,0 @@ -""" -Problem Link: https://practice.geeksforgeeks.org/problems/rock-paper-scissors/0 - -The RPS world championship is here. Here two players A and B play the game. -You need to determine who wins. -Both players can choose moves from the set {R,P,S}. -The game is a draw if both players choose the same item. -The winning rules of RPS are given below: - -Rock crushes scissor -Scissor cuts paper -Paper envelops rock -Input: -The first line of input contains T denoting the number of testcases. T testcases follow. -Each testcase contains single line of input that contains two characters sidebyside. -These characters denote the moves of players A and B respectively. - -Output: -For each testcase, in a newline, print the winner. If match is draw, print 'DRAW'. - -Constraints: -1<= T <= 50 - -Example: -Input: -7 -RR -RS -SR -SP -PP -PS -RP - -Output: -DRAW -A -B -A -DRAW -B -B -""" -def rock_paper_scissor(game): - if game[0] == game[1]: - return "DRAW" - if game[0] == "R": - if game[1] == "S": - return "A" - return "B" - if game[0] == "P": - if game[1] == "R": - return "A" - return "B" - if game[0] == "S": - if game[1] == "P": - return "A" - return "B" - -for _ in range(int(input())): - game = input() - print(rock_paper_scissor(game)) \ No newline at end of file diff --git a/Python/GeeksforGeeks/rotate-a-linked-list.py b/Python/GeeksforGeeks/rotate-a-linked-list.py new file mode 100644 index 0000000..b8d6b85 --- /dev/null +++ b/Python/GeeksforGeeks/rotate-a-linked-list.py @@ -0,0 +1,112 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/rotate-a-linked-list/1 + +Given a singly linked list of size N. The task is to rotate the linked list counter-clockwise by k nodes, +where k is a given positive integer smaller than or equal to length of the linked list. + +Input Format: +First line of input contains number of testcases T. For each testcase, first line of input contains length of +linked list and next line contains linked list elements and last line contains k, by which linked list is to be rotated. + +Output Format: +For each testcase, print the rotated linked list. + +User Task: +The task is to complete the function rotate() which takes head reference as the first argument and k as the second argument. +The printing is done automatically by the driver code. + +Constratints: +1 <= T <= 100 +1 <= N <= 103 +1 <= k <= 103 + +Example: +Input: +3 +8 +1 2 3 4 5 6 7 8 +4 +5 +2 4 7 8 9 +3 +2 +1 2 +4 + +Output: +5 6 7 8 1 2 3 4 +8 9 2 4 7 +1 2 + +Explanation: +Testcase 1: After rotating the linked list by 4 elements (anti-clockwise), we reached to node 5, which is (k+1)th node +from beginning, now becomes head and tail of the linked list is joined to the previous head. +""" +class Node: + def __init__(self, data): + self.data = data + self.next = None +class LinkedList: + def __init__(self): + self.head = None + def push(self, new_data): + new_node = Node(new_data) + new_node.next = self.head + self.head = new_node + def printList(self): + temp = self.head + while(temp): + print(temp.data, end=" ") + # arr.append(str(temp.data)) + temp = temp.next + print("") +if __name__ == '__main__': + start = LinkedList() + t = int(input()) + while(t > 0): + llist = LinkedList() + n = int(input()) + values = list(map(int, input().strip().split())) + for i in reversed(values): + llist.push(i) + k = int(input()) + new_head = rotateList(llist.head, k) + llist.head = new_head + llist.printList() + t -= 1 + +''' This is a function problem.You only need to complete the function given below ''' +# Your task is to complete this function +''' +class Node: + def __init__(self, data): + self.data = data + self.next = None +''' +# This function should rotate list counter- +# clockwise by k and return new head (if changed) +def rotateList(head, k): + # code here + if not head: + return None + l = length(head) + k = k%l + if not k: + return head + cur = head + for _ in range(k-1): + cur = cur.next + newHead = cur.next + newCur = cur.next + cur.next = None + while newCur.next: + newCur = newCur.next + newCur.next = head + return newHead + +def length(head): + l = 0 + while head: + l += 1 + head = head.next + return l \ No newline at end of file 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 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 diff --git a/Python/strange_sum.py b/Python/GeeksforGeeks/strange_sum.py similarity index 100% rename from Python/strange_sum.py rename to Python/GeeksforGeeks/strange_sum.py diff --git a/Python/GeeksforGeeks/subarray-range-with-given-sum.py b/Python/GeeksforGeeks/subarray-range-with-given-sum.py index e186dac..181f151 100644 --- a/Python/GeeksforGeeks/subarray-range-with-given-sum.py +++ b/Python/GeeksforGeeks/subarray-range-with-given-sum.py @@ -34,14 +34,17 @@ Explanation: Testcase 1: Subarrays with sum -10 are: [10, 2, -2, -20], [2, -2, -20, 10] and [-20, 10]. """ -def countSubSum(arr,target): - count,summ,d = 0,0,{0:1} - for i in arr: - summ += i - if summ - target in d: - count += d[summ-target] - d[summ] = d.get(summ,0) + 1 - return count +def subArraySum(arr,target): + summ = 0 + d= {} + d[0] = 0 + for i in range(len(arr)): + summ += arr[i] + difference = summ - target + if difference in d: + return [d[difference]+1,i+1] + d[summ] = i+1 + return [-1] for _ in range(int(input())): n = int(input()) diff --git a/Python/sum-of-ap-series.py b/Python/GeeksforGeeks/sum-of-ap-series.py similarity index 100% rename from Python/sum-of-ap-series.py rename to Python/GeeksforGeeks/sum-of-ap-series.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 diff --git a/Python/sum-of-digits-modified.py b/Python/GeeksforGeeks/sum-of-digits-modified.py similarity index 100% rename from Python/sum-of-digits-modified.py rename to Python/GeeksforGeeks/sum-of-digits-modified.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 diff --git a/Python/sum_of_even_factors.py b/Python/GeeksforGeeks/sum_of_even_factors.py similarity index 100% rename from Python/sum_of_even_factors.py rename to Python/GeeksforGeeks/sum_of_even_factors.py diff --git a/Python/sum_of_first_n_terms.py b/Python/GeeksforGeeks/sum_of_first_n_terms.py similarity index 100% rename from Python/sum_of_first_n_terms.py rename to Python/GeeksforGeeks/sum_of_first_n_terms.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 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) diff --git a/Python/uppercase_conversion.py b/Python/GeeksforGeeks/uppercase_conversion.py similarity index 100% rename from Python/uppercase_conversion.py rename to Python/GeeksforGeeks/uppercase_conversion.py diff --git a/Python/GeeksforGeeks/value-equal-to-index-value.py b/Python/GeeksforGeeks/value-equal-to-index-value.py new file mode 100644 index 0000000..994935b --- /dev/null +++ b/Python/GeeksforGeeks/value-equal-to-index-value.py @@ -0,0 +1,51 @@ +""" +Problem Link: https://practice.geeksforgeeks.org/problems/value-equal-to-index-value/0 + +Given an array of positive integers. Your task is to find that element whose value is equal +to that of its index value. + +Input: +The first line of input contains an integer T denoting the number of test cases. +The first line of each test case is N, size of array. The second line of each test case +contains array elements. + +Output: +Print the element whose value is equal to index value. Print "Not Found" when index value does +not match with value. +Note: There can be more than one element in the array which have same value as their index. +You need to print every such element's index separated by a single space. +Follows 1-based indexing of the array. + +Constraints: +1 ≤ T ≤ 30 +1 ≤ N ≤ 50 +1 ≤ A[i] ≤ 1000 + +Example: +Input: +2 +5 +15 2 45 12 7 +1 +1 + +Output: +2 +1 +""" +def fixed_point(arr): + res = [] + for i in range(len(arr)): + if arr[i] == i+1: + res.append(arr[i]) + return res + + +for _ in range(int(input())): + n = int(input()) + arr = list(map(int,input().split())) + res = fixed_point(arr) + if res: + print(*res) + else: + print("Not Found") \ No newline at end of file diff --git a/Python/Interviewbit/Arrays/add-one-to-number.py b/Python/Interviewbit/Arrays/add-one-to-number.py new file mode 100644 index 0000000..05546be --- /dev/null +++ b/Python/Interviewbit/Arrays/add-one-to-number.py @@ -0,0 +1,46 @@ +""" +Problem Link: https://www.interviewbit.com/problems/add-one-to-number/ + +Given a non-negative number represented as an array of digits, +add 1 to the number ( increment the number represented by the digits ). +The digits are stored such that the most significant digit is at the head of the list. + +Example: +If the vector has [1, 2, 3] +the returned vector should be [1, 2, 4] +as 123 + 1 = 124. + +NOTE: Certain things are intentionally left unclear in this question which you should practice +asking the interviewer. +For example, for this problem, following are some good questions to ask : +Q : Can the input have 0’s before the most significant digit. Or in other words, is 0 1 2 3 a +valid input? +A : For the purpose of this question, YES +Q : Can the output have 0’s before the most significant digit? Or in other words, is 0 1 2 4 +a valid output? +A : For the purpose of this question, NO. Even if the input has zeroes before the most significant +digit. +""" +class Solution: + # @param A : list of integers + # @return a list of integers + def plusOne(self, A): + rem = 0 + carry = 1 + i = len(A) - 1 + while i >= 0: + if A[i] < 9: + A[i] += 1 + carry = 0 + break + else: + A[i] = 0 + i -= 1 + + if carry: + A.insert(0, 1) + i = 0 + while i < len(A) and A[i] == 0: + i += 1 + + return A[i:] diff --git a/Python/Interviewbit/Arrays/balance-array.py b/Python/Interviewbit/Arrays/balance-array.py new file mode 100644 index 0000000..38eb396 --- /dev/null +++ b/Python/Interviewbit/Arrays/balance-array.py @@ -0,0 +1,69 @@ +""" +Problem Link: https://www.interviewbit.com/problems/balance-array/ + +Problem Description +Given an integer array A of size N. You need to count the number of special elements in the given array. +A element is special if removal of that element make the array balanced. +Array will be balanced if sum of even index element equal to sum of odd index element. + +Problem Constraints +1 <= N <= 105 +1 <= A[i] <= 109 + +Input Format +First and only argument is an integer array A of size N. + +Output Format +Return an integer denoting the count of special elements. + +Example Input +Input 1: +A = [2, 1, 6, 4] +Input 2: +A = [5, 5, 2, 5, 8] + +Example Output +Output 1: +1 + +Output 2: +2 + +Example Explanation +Explanation 1: +After deleting 1 from array : {2,6,4} +(2+4) = (6) +Hence 1 is the only special element, so count is 1 + +Explanation 2: +If we delete A[0] or A[1] , array will be balanced +(5+5) = (2+8) +So A[0] and A[1] are special elements, so count is 2. +""" +class Solution: + # @param A : list of integers + # @return an integer + def solve(self, A): + right_even = right_odd = 0 + for i in range(len(A)): + if i % 2 == 0: + right_odd += A[i] + else: + right_even += A[i] + + res = left_odd = left_even = 0 + for i in range(len(A)): + if i % 2 == 0: + right_odd -= A[i] + else: + right_even -= A[i] + + if right_odd + left_even == left_odd + right_even: + res += 1 + + if i % 2 == 0: + left_odd += A[i] + else: + left_even += A[i] + + return res diff --git a/Python/Interviewbit/Arrays/kth-row-of-pascals-triangle.py b/Python/Interviewbit/Arrays/kth-row-of-pascals-triangle.py new file mode 100644 index 0000000..3e1eb18 --- /dev/null +++ b/Python/Interviewbit/Arrays/kth-row-of-pascals-triangle.py @@ -0,0 +1,24 @@ +""" +Problem Link: https://www.interviewbit.com/problems/kth-row-of-pascals-triangle/ + +Given an index k, return the kth row of the Pascal’s triangle. +Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1. + +Example: +Input : k = 3 +Return : [1,3,3,1] + +NOTE : k is 0 based. k = 0, corresponds to the row [1]. +Note:Could you optimize your algorithm to use only O(k) extra space? +""" +class Solution: + # @param A : integer + # @return a list of integers + def getRow(self, A): + A += 1 + res = [0] * A + res[0] = 1 + for i in range(1, A): + for j in range(i, 0, -1): + res[j] += res[j-1] + return res diff --git a/Python/Interviewbit/Arrays/large-factorial.py b/Python/Interviewbit/Arrays/large-factorial.py new file mode 100644 index 0000000..0f31585 --- /dev/null +++ b/Python/Interviewbit/Arrays/large-factorial.py @@ -0,0 +1,45 @@ +""" +Problem Link: https://www.interviewbit.com/problems/large-factorial/ + +Problem Description +Given a number A. Find the fatorial of the number. + +Problem Constraints +1 <= A <= 100 + +Input Format +First and only argument is the integer A. + +Output Format +Return a string, the factorial of A. + + +Example Input +Input 1: +A = 2 + +Input 2: +A = 3 + +Example Output +Output 1: +2 + +Output 2: +6 + +Example Explanation +Explanation 1: +2! = 2 . + +Explanation 2: +3! = 6 . +""" +class Solution: + # @param A : integer + # @return a strings + def solve(self, A): + res = 1 + for num in range(2, A+1): + res *= num + return str(res) diff --git a/Python/Interviewbit/Arrays/largest-number.py b/Python/Interviewbit/Arrays/largest-number.py new file mode 100644 index 0000000..9c2b80c --- /dev/null +++ b/Python/Interviewbit/Arrays/largest-number.py @@ -0,0 +1,18 @@ +""" +Problem Link: https://www.interviewbit.com/problems/largest-number/ + +Given a list of non negative integers, arrange them such that they form the largest number. +For example: +Given [3, 30, 34, 5, 9], the largest formed number is 9534330. +Note: The result may be very large, so you need to return a string instead of an integer. +""" +class LargerNumKey(str): + def __lt__(x, y): + return x+y > y+x + +class Solution: + # @param A : tuple of integers + # @return a strings + def largestNumber(self, nums): + largest_num = ''.join(sorted(map(str, nums), key=LargerNumKey)) + return '0' if largest_num[0] == '0' else largest_num diff --git a/Python/Interviewbit/Arrays/leaders-in-an-array.py b/Python/Interviewbit/Arrays/leaders-in-an-array.py new file mode 100644 index 0000000..0145dd3 --- /dev/null +++ b/Python/Interviewbit/Arrays/leaders-in-an-array.py @@ -0,0 +1,56 @@ +""" +Problem Link: https://www.interviewbit.com/problems/leaders-in-an-array/ + +Problem Description +Given an integer array A containing N distinct integers, you have to find all the leaders in the +array A. +An element is leader if it is strictly greater than all the elements to its right side. +NOTE:The rightmost element is always a leader. + +Problem Constraints +1 <= N <= 105 +1 <= A[i] <= 108 + +Input Format +First and only argument is an integer array A. + +Output Format +Return an integer array denoting all the leader elements of the array. +NOTE: Ordering in the output doesn't matter. + +Example Input +Input 1: +A = [16, 17, 4, 3, 5, 2] + +Input 2: +A = [1, 2] + +Example Output +Output 1: +[17, 2, 5] + +Output 2: +[2] + +Example Explanation +Explanation 1: +Element 17 is strictly greater than all the elements on the right side to it. +Element 2 is strictly greater than all the elements on the right side to it. +Element 5 is strictly greater than all the elements on the right side to it. +So we will return this three elements i.e [17, 2, 5], we can also return [2, 5, 17] +or [5, 2, 17] or any other ordering. + +Explanation 2: +Only 2 the rightmost element is the leader in the array. +""" +class Solution: + # @param A : list of integers + # @return a list of integers + def solve(self, A): + res = [] + max_num = float('-inf') + for i in range(len(A)-1, -1, -1): + if A[i] > max_num: + res.append(A[i]) + max_num = A[i] + return res diff --git a/Python/Interviewbit/Arrays/max-min.py b/Python/Interviewbit/Arrays/max-min.py new file mode 100644 index 0000000..5685f71 --- /dev/null +++ b/Python/Interviewbit/Arrays/max-min.py @@ -0,0 +1,50 @@ +""" +Problem Link: https://www.interviewbit.com/problems/max-min-05542f2f-69aa-4253-9cc7-84eb7bf739c4/ + +Problem Description +Given an array A of size N. You need to find the sum of Maximum and Minimum element in the given array. +NOTE: You should make minimum number of comparisons. + +Problem Constraints +1 <= N <= 105 +-109 <= A[i] <= 109 + +Input Format +First and only argument is an integer array A of size N. + +Output Format +Return an integer denoting the sum Maximum and Minimum element in the given array. + +Example Input +Input 1: +A = [-2, 1, -4, 5, 3] + +Input 2: +A = [1, 3, 4, 1] + +Example Output +Output 1: +1 + +Output 2: +5 + +Example Explanation +Explanation 1: +Maximum Element is 5 and Minimum element is -4. (5 + (-4)) = 1. + +Explanation 2: +Maximum Element is 4 and Minimum element is 1. (4 + 1) = 5. +""" +class Solution: + # @param A : list of integers + # @return an integer + def solve(self, A): + min_num = float('inf') + max_num = float('-inf') + for num in A: + if num > max_num: + max_num = num + if num < min_num: + min_num = num + return max_num + min_num diff --git a/Python/Interviewbit/Arrays/max-sum-contiguous-subarray.py b/Python/Interviewbit/Arrays/max-sum-contiguous-subarray.py new file mode 100644 index 0000000..6dfde0d --- /dev/null +++ b/Python/Interviewbit/Arrays/max-sum-contiguous-subarray.py @@ -0,0 +1,43 @@ +""" +Problem Link: https://www.interviewbit.com/problems/max-sum-contiguous-subarray/ + +Find the contiguous subarray within an array, A of length N which has the largest sum. + +Input Format: +The first and the only argument contains an integer array, A. + +Output Format: +Return an integer representing the maximum possible sum of the contiguous subarray. + +Constraints: +1 <= N <= 1e6 +-1000 <= A[i] <= 1000 + +For example: +Input 1: +A = [1, 2, 3, 4, -10] + +Output 1: +10 + +Explanation 1: +The subarray [1, 2, 3, 4] has the maximum possible sum of 10. + +Input 2: +A = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + +Output 2: +6 + +Explanation 2: +The subarray [4,-1,2,1] has the maximum possible sum of 6. +""" +class Solution: + # @param A : tuple of integers + # @return an integer + def maxSubArray(self, A): + max_sum = cur_sum = float('-inf') + for num in A: + cur_sum = max(cur_sum + num, num) + max_sum = max(cur_sum, max_sum) + return max_sum diff --git a/Python/Interviewbit/Arrays/maximum-absolute-difference.py b/Python/Interviewbit/Arrays/maximum-absolute-difference.py new file mode 100644 index 0000000..6c38bcc --- /dev/null +++ b/Python/Interviewbit/Arrays/maximum-absolute-difference.py @@ -0,0 +1,29 @@ +""" +Problem Link: https://www.interviewbit.com/problems/maximum-absolute-difference/ + +You are given an array of N integers, A1, A2 ,…, AN. Return maximum value of f(i, j) +for all 1 ≤ i, j ≤ N. +f(i, j) is defined as |A[i] - A[j]| + |i - j|, where |x| denotes absolute value of x. + +For example, +A=[1, 3, -1] +f(1, 1) = f(2, 2) = f(3, 3) = 0 +f(1, 2) = f(2, 1) = |1 - 3| + |1 - 2| = 3 +f(1, 3) = f(3, 1) = |1 - (-1)| + |1 - 3| = 4 +f(2, 3) = f(3, 2) = |3 - (-1)| + |2 - 3| = 5 +So, we return 5. +""" +class Solution: + # @param A : list of integers + # @return an integer + def maxArr(self, A): + min_pair1 = min_pair2 = float('inf') + max_pair1 = max_pair2 = float('-inf') + for i in range(len(A)): + min_pair1 = min(min_pair1, A[i] + i) + max_pair1 = max(max_pair1, A[i] + i) + + min_pair2 = min(min_pair2, A[i] - i) + max_pair2 = max(max_pair2, A[i] - i) + + return max(max_pair1 - min_pair1, max_pair2 - min_pair2) diff --git a/Python/Interviewbit/Arrays/maximum-sum-triplet.py b/Python/Interviewbit/Arrays/maximum-sum-triplet.py new file mode 100644 index 0000000..df7a894 --- /dev/null +++ b/Python/Interviewbit/Arrays/maximum-sum-triplet.py @@ -0,0 +1,72 @@ +""" +Problem Link: https://www.interviewbit.com/problems/maximum-sum-triplet/ + +Problem Description + +Given an array A containing N integers. +You need to find the maximum sum of triplet ( Ai + Aj + Ak ) such that 0 <= i < j < k < N and +Ai < Aj < Ak. +If no such triplet exist return 0. + +Problem Constraints +3 <= N <= 105. +1 <= A[i] <= 108. + +Input Format +First argument is an integer array A. + +Output Format +Return a single integer denoting the maximum sum of triplet as described in the question. + +Example Input +Input 1: +A = [2, 5, 3, 1, 4, 9] + +Input 2: +A = [1, 2, 3] + +Example Output +Output 1: +16 + +Output 2: +6 + +Example Explanation +Explanation 1: +All possible triplets are:- +2 3 4 => sum = 9 +2 5 9 => sum = 16 +2 3 9 => sum = 14 +3 4 9 => sum = 16 +1 4 9 => sum = 14 +Maximum sum = 16 +Explanation 2: + +All possible triplets are:- +1 2 3 => sum = 6 +Maximum sum = 6 +""" +from bisect import bisect_left +def BinarySearch(a, x): + i = bisect_left(a, x) + return i-1 if i else -1 + +class Solution: + # @param A : list of integers + # @return an integer + def solve(self, A): + max_values_right = [0] * len(A) + max_values_right[-1] = A[-1] + for i in range(len(A)-2, -1, -1): + max_values_right[i] = max(A[i], max_values_right[i+1]) + + lst = [] + res = 0 + lst.append(A[0]) + for i in range(1,len(A)-1): + val = BinarySearch(lst, A[i]) + if val != -1 and max_values_right[i+1] > A[i]: + res = max(res, lst[val] + A[i] + max_values_right[i+1]) + lst.insert(val+1,A[i]) + return res diff --git a/Python/Interviewbit/Arrays/min-steps-in-infinite-grid.py b/Python/Interviewbit/Arrays/min-steps-in-infinite-grid.py new file mode 100644 index 0000000..1574555 --- /dev/null +++ b/Python/Interviewbit/Arrays/min-steps-in-infinite-grid.py @@ -0,0 +1,59 @@ +""" +Problem Link: https://www.interviewbit.com/problems/min-steps-in-infinite-grid/ + +Problem Description + +You are in an infinite 2D grid where you can move in any of the 8 directions + + (x,y) to + (x+1, y), + (x - 1, y), + (x, y+1), + (x, y-1), + (x-1, y-1), + (x+1,y+1), + (x-1,y+1), + (x+1,y-1) +You are given a sequence of points and the order in which you need to cover the points. +Give the minimum number of steps in which you can achieve it. You start from the first point. +NOTE: This question is intentionally left slightly vague. Clarify the question by trying out +a few cases in the “See Expected Output” section. + +Input Format +Given two integer arrays A and B, where A[i] is x coordinate and B[i] is y coordinate of ith +point respectively. + +Output Format +Return an Integer, i.e minimum number of steps. + +Example Input +Input 1: +A = [0, 1, 1] +B = [0, 1, 2] + +Example Output +Output 1: +2 + +Example Explanation +Explanation 1: +Given three points are: (0, 0), (1, 1) and (1, 2). +It takes 1 step to move from (0, 0) to (1, 1). It takes one more step to move from (1, 1) to (1, 2) +""" +class Solution: + # @param A : list of integers + # @param B : list of integers + # @return an integer + def coverPoints(self, A, B): + steps = 0 + for i in range(1, len(A)): + steps += max(abs(A[i] - A[i-1]), abs(B[i] - B[i-1])) + return steps + +# Pythonic +class Solution1: + # @param A : list of integers + # @param B : list of integers + # @return an integer + def coverPoints(self, A, B): + return sum(max(abs(A[i] - A[i-1]), abs(B[i] - B[i-1])) for i in range(1, len(A))) diff --git a/Python/Interviewbit/Arrays/minimum-lights-to-activate.py b/Python/Interviewbit/Arrays/minimum-lights-to-activate.py new file mode 100644 index 0000000..f40eca0 --- /dev/null +++ b/Python/Interviewbit/Arrays/minimum-lights-to-activate.py @@ -0,0 +1,71 @@ +""" +Problem Link: https://www.interviewbit.com/problems/minimum-lights-to-activate/ + +Problem Description +There is a corridor in a Jail which is N units long. Given an array A of size N. The ith index of this array is 0 +if the light at ith position is faulty otherwise it is 1. +All the lights are of specific power B which if is placed at position X, it can light the corridor from [ X-B+1, X+B-1]. +Initially all lights are off. +Return the minimum number of lights to be turned ON to light the whole corridor or -1 if the whole corridor cannot be lighted. + +Problem Constraints +1 <= N <= 1000 +1 <= B <= 1000 + +Input Format +First argument is an integer array A where A[i] is either 0 or 1. +Second argument is an integer B. + +Output Format +Return the minimum number of lights to be turned ON to light the whole corridor or -1 if the whole corridor cannot be lighted. + + +Example Input +Input 1: +A = [ 0, 0, 1, 1, 1, 0, 0, 1]. +B = 3 + +Input 2: +A = [ 0, 0, 0, 1, 0]. +B = 3 + +Example Output +Output 1: +2 + +Output 2: +-1 + +Example Explanation +Explanation 1: +In the first configuration, Turn on the lights at 3rd and 8th index. +Light at 3rd index covers from [ 1, 5] and light at 8th index covers [ 6, 8]. + +Explanation 2: +In the second configuration, there is no light which can light the first corridor. +""" +class Solution: + # @param A : list of integers + # @param B : integer + # @return an integer + def solve(self, A, B): + n = len(A) + ans = 0 + last = -1 + while (last < n - 1): + pos = -1 + end = max(-1,last - B + 1) + start = min(n-1,last + B) + for i in range( start, end , -1): + if (A[i] == 1 and i - B <= last): + pos = i; + break; + + + if (pos == -1): + return -1 + + ans = ans + 1 + last = pos + B - 1 + + return ans diff --git a/Python/Interviewbit/Arrays/noble-integer.py b/Python/Interviewbit/Arrays/noble-integer.py new file mode 100644 index 0000000..f6ab6e8 --- /dev/null +++ b/Python/Interviewbit/Arrays/noble-integer.py @@ -0,0 +1,48 @@ +""" +Problem Link: https://www.interviewbit.com/problems/noble-integer/ + +Problem Description +Given an integer array A, find if an integer p exists in the array such that the number of +integers greater than p in the array equals to p. + +Input Format +First and only argument is an integer array A. + +Output Format +Return 1 if any such integer p is found else return -1. + +Example Input +Input 1: +A = [3, 2, 1, 3] + +Input 2: +A = [1, 1, 3, 3] + +Example Output +Output 1: +1 + +Output 2: +-1 + + +Example Explanation +Explanation 1: +For integer 2, there are 2 greater elements in the array. So, return 1. + +Explanation 2: +There is no such integer exists. +""" +class Solution: + # @param A : list of integers + # @return an integer + def solve(self, A): + A.sort() + + if A[-1] == 0: + return 1 + + for i in range(len(A)): + if A[i] == len(A) - (i + 1) and A[i] != A[i+1]: + return 1 + return -1 diff --git a/Python/Interviewbit/Arrays/pascal-triangle.py b/Python/Interviewbit/Arrays/pascal-triangle.py new file mode 100644 index 0000000..fbb2908 --- /dev/null +++ b/Python/Interviewbit/Arrays/pascal-triangle.py @@ -0,0 +1,31 @@ +""" +Problem Link: https://www.interviewbit.com/problems/pascal-triangle/ + +Given numRows, generate the first numRows of Pascal’s triangle. +Pascal’s triangle : To generate A[C] in row R, sum up A’[C] and A’[C-1] from previous row R - 1. + +Example: +Given numRows = 5, + +Return +[ + [1], + [1,1], + [1,2,1], + [1,3,3,1], + [1,4,6,4,1] +] +""" +class Solution: + # @param A : integer + # @return a list of list of integers + def solve(self, A): + if A == 1: + return [[1]] + res = [] + for i in range(A): + row = [1]*(i+1) + res.append(row) + for j in range(1,len(row)-1): + res[i][j] = res[i-1][j-1]+res[i-1][j] + return res diff --git a/Python/Interviewbit/Arrays/perfect-peak-of-array.py b/Python/Interviewbit/Arrays/perfect-peak-of-array.py new file mode 100644 index 0000000..4733a38 --- /dev/null +++ b/Python/Interviewbit/Arrays/perfect-peak-of-array.py @@ -0,0 +1,65 @@ +""" +Problem Link: https://www.interviewbit.com/problems/perfect-peak-of-array/ + +Problem Description +Given an integer array A of size N. +You need to check that whether there exist a element which is strictly greater than all the elements on left of it and +strictly smaller than all the elements on right of it. +If it exists return 1 else return 0. + +NOTE: +Do not consider the corner elements i.e A[0] and A[N-1] as the answer. + +Problem Constraints +3 <= N <= 105 +1 <= A[i] <= 109 + +Input Format +First and only argument is an integer array A containing N integers. + +Output Format +Return 1 if there exist a element that is strictly greater than all the elements on left of it and +strictly smaller than all the elements on right of it else return 0. + + +Example Input +Input 1: +A = [5, 1, 4, 3, 6, 8, 10, 7, 9] + +Input 2: +A = [5, 1, 4, 4] + +Example Output +Output 1: +1 + +Output 2: +0 + +Example Explanation +Explanation 1: + + A[4] = 6 is the element we are looking for. + All elements on left of A[4] are smaller than it and all elements on right are greater. +Explanation 2: + + No such element exits. +""" +class Solution: + # @param A : list of integers + # @return an integer + def perfectPeak(self, A): + left_max = [0] * len(A) + max_num = float('-inf') + for i in range(len(A)): + if A[i] > max_num: + max_num = A[i] + left_max[i] = max_num + + right_min = A[-1] + for i in range(len(A) - 2, 0, -1): + if A[i] > left_max[i-1] and right_min > A[i]: + return 1 + if A[i] < right_min: + right_min = A[i] + return 0 diff --git a/Python/Interviewbit/Arrays/pick-from-both-sides.py b/Python/Interviewbit/Arrays/pick-from-both-sides.py new file mode 100644 index 0000000..9429ebf --- /dev/null +++ b/Python/Interviewbit/Arrays/pick-from-both-sides.py @@ -0,0 +1,67 @@ +""" +Problem Link: https://www.interviewbit.com/problems/pick-from-both-sides/ + +Problem Description + +Given an integer array A of size N. +You can pick B elements from either left or right end of the array A to get maximum sum. +Find and return this maximum possible sum. +NOTE: Suppose B = 4 and array A contains 10 elements then: +You can pick first four elements or can pick last four elements or can pick 1 from front and +3 from back etc . you need to return the maximum possible sum of elements you can pick. + +Problem Constraints +1 <= N <= 105 +1 <= B <= N +-103 <= A[i] <= 103 + +Input Format +First argument is an integer array A. +Second argument is an integer B. + +Output Format +Return an integer denoting the maximum possible sum of elements you picked. + +Example Input +Input 1: +A = [5, -2, 3 , 1, 2] +B = 3 + +Input 2: +A = [1, 2] +B = 1 + +Example Output +Output 1: +8 + +Output 2: +2 + +Example Explanation +Explanation 1: +Pick element 5 from front and element (1, 2) from back so we get 5 + 1 + 2 = 8 + +Explanation 2: +Pick element 2 from end as this is the maximum we can get +""" +class Solution: + # @param A : list of integers + # @param B : integer + # @return an integer + def solve(self, A, B): + cur_sum = 0 + for i in range(B): + cur_sum += A[i] + + if B == len(A): + return cur_sum + + max_sum = cur_sum + index = B-1 + for i in range(len(A)-1, len(A)-B-1, -1): + cur_sum += (A[i] - A[index]) + max_sum = max(max_sum, cur_sum) + index -= 1 + return max_sum + \ No newline at end of file diff --git a/Python/Interviewbit/Arrays/sort-array-with-squares.py b/Python/Interviewbit/Arrays/sort-array-with-squares.py new file mode 100644 index 0000000..7041238 --- /dev/null +++ b/Python/Interviewbit/Arrays/sort-array-with-squares.py @@ -0,0 +1,61 @@ +""" +Problem Link: https://www.interviewbit.com/problems/sort-array-with-squares/ + +Problem Description +Given a sorted array A containing N integers both positive and negative. +You need to create another array containing the squares of all the elements in A and +return it in non-decreasing order. +Try to this in O(N) time. + +Problem Constraints +1 <= N <= 105. +-103 <= A[i] <= 103 + +Input Format +First and only argument is an integer array A. + +Output Format +Return a integer array as described in the problem above. + + +Example Input +Input 1: +A = [-6,- 3, -1, 2, 4, 5] + +Input 2: +A = [-5, -4, -2, 0, 1] + +Example Output +Output 1: +[1, 4, 9, 16, 25, 36] + +Output 2: +[0, 1, 4, 16, 25] +""" +class Solution: + # @param A : list of integers + # @return a list of integers + def solve(self, A): + for i in range(len(A)): + if A[i] >= 0: + break + + j = i + i -= 1 + + res = [] + while i >= 0 or j < len(A): + if i >= 0 and j < len(A): + if -1 * A[i] < A[j]: + res.append(A[i]*A[i]) + i -= 1 + else: + res.append(A[j]*A[j]) + j += 1 + elif i >= 0: + res.append(A[i]*A[i]) + i -= 1 + else: + res.append(A[j]*A[j]) + j += 1 + return res diff --git a/Python/Interviewbit/Arrays/wave-array.py b/Python/Interviewbit/Arrays/wave-array.py new file mode 100644 index 0000000..5237b4e --- /dev/null +++ b/Python/Interviewbit/Arrays/wave-array.py @@ -0,0 +1,23 @@ +""" +Problem Link: https://www.interviewbit.com/problems/wave-array/ + +Given an array of integers, sort the array into a wave like array and return it, +In other words, arrange the elements into a sequence such that +a1 >= a2 <= a3 >= a4 <= a5..... + +Example +Given [1, 2, 3, 4] +One possible answer : [2, 1, 4, 3] +Another possible answer : [4, 1, 3, 2] + +NOTE : If there are multiple answers possible, return the one thats lexicographically smallest. +So, in example case, you will return [2, 1, 4, 3] +""" +class Solution: + # @param A : list of integers + # @return a list of integers + def wave(self, A): + A.sort() + for i in range(1, len(A), 2): + A[i], A[i-1] = A[i-1], A[i] + return A 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 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 diff --git a/Python/Interviewbit/Linked_Lists/list-cycle.py b/Python/Interviewbit/Linked_Lists/list-cycle.py new file mode 100644 index 0000000..39b938c --- /dev/null +++ b/Python/Interviewbit/Linked_Lists/list-cycle.py @@ -0,0 +1,39 @@ +""" +Problem Link: https://www.interviewbit.com/problems/list-cycle/ + +Given a linked list, return the node where the cycle begins. If there is no cycle, return null. +Try solving it using constant additional space. + +Example : +Input : + + ______ + | | + \/ | + 1 -> 2 -> 3 -> 4 +Return the node corresponding to node 3. +""" +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param A : head node of linked list + # @return the first node in the cycle in the linked list + def detectCycle(self, A): + slow = fast = A + while fast and fast.next: + if slow == fast: + break + slow = slow.next + fast = fast.next.next + + if not fast or fast.next: + return None + fast = A + while fast != slow: + fast = fast.next + slow = slow.next + return fast diff --git a/Python/Interviewbit/Linked_Lists/remove-nth-node-from-list-end.py b/Python/Interviewbit/Linked_Lists/remove-nth-node-from-list-end.py new file mode 100644 index 0000000..8fe4ca6 --- /dev/null +++ b/Python/Interviewbit/Linked_Lists/remove-nth-node-from-list-end.py @@ -0,0 +1,39 @@ +""" +Problem Link: https://www.interviewbit.com/problems/remove-nth-node-from-list-end/ + +Given a linked list, remove the nth node from the end of list and return its head. + +For example, +Given linked list: 1->2->3->4->5, and n = 2. +After removing the second node from the end, the linked list becomes 1->2->3->5. + +Note: +If n is greater than the size of the list, remove the first node of the list. +Try doing it using constant additional space. +""" +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param A : head node of linked list + # @param B : integer + # @return the head node in the linked list + def removeNthFromEnd(self, A, B): + fast = A + for _ in range(B): + if fast: + fast = fast.next + else: + break + if not fast or not fast.next: + return A.next + + slow = A + while fast and fast.next: + fast = fast.next + slow = slow.next + slow.next = slow.next.next + return A diff --git a/Python/Interviewbit/Linked_Lists/reverse-linked-list.py b/Python/Interviewbit/Linked_Lists/reverse-linked-list.py new file mode 100644 index 0000000..b14b85d --- /dev/null +++ b/Python/Interviewbit/Linked_Lists/reverse-linked-list.py @@ -0,0 +1,23 @@ +""" +Problem Link: https://www.interviewbit.com/problems/reverse-linked-list/ + +Reverse a linked list. Do it in-place and in one-pass. + +For example: +Given 1->2->3->4->5->NULL, +return 5->4->3->2->1->NULL. +""" +# Definition for singly-linked list. +# class ListNode: +# def __init__(self, x): +# self.val = x +# self.next = None + +class Solution: + # @param A : head node of linked list + # @return the head node in the linked list + def reverseList(self, A): + head = None + while A: + A.next, A, head = head, A.next, A + return head diff --git a/Python/Interviewbit/Math/excel-column-number.py b/Python/Interviewbit/Math/excel-column-number.py new file mode 100644 index 0000000..ad01507 --- /dev/null +++ b/Python/Interviewbit/Math/excel-column-number.py @@ -0,0 +1,52 @@ +""" +Problem Link: https://www.interviewbit.com/problems/excel-column-number/ + +Problem Description +Given a column title A as appears in an Excel sheet, return its corresponding column number. + +Problem Constraints +1 <= |A| <= 100 + +Input Format +First and only argument is string A. + +Output Format +Return an integer + +Example Input +Input 1: +1 + +Input 2: +28 + +Example Output +Output 1: +"A" + +Output 2: +"AB" + +Example Explanation +Explanation 1: +1 -> "A" + +Explanation 2: +A -> 1 +B -> 2 +C -> 3 +... +Z -> 26 +AA -> 27 +AB -> 28 +""" +class Solution: + # @param A : string + # @return an integer + def titleToNumber(self, A): + res = 0 + index = 0 + for c in A[::-1]: + res += (26**index) * (ord(c) - ord("A") + 1) + index += 1 + return res diff --git a/Python/Interviewbit/Math/fizzbuzz.py b/Python/Interviewbit/Math/fizzbuzz.py new file mode 100644 index 0000000..b4e8685 --- /dev/null +++ b/Python/Interviewbit/Math/fizzbuzz.py @@ -0,0 +1,31 @@ +""" +Problem Link: https://www.interviewbit.com/problems/fizzbuzz/ + +Fizzbuzz is one of the most basic problems in the coding interview world. +Try to write a small and elegant code for this problem. + +Given a positive integer A, return an array of strings with all the integers from 1 to N. +But for multiples of 3 the array should have “Fizz” instead of the number. +For the multiples of 5, the array should have “Buzz” instead of the number. +For numbers which are multiple of 3 and 5 both, the array should have “FizzBuzz” instead of the number. + +Look at the example for more details. +Example +A = 5 +Return: [1 2 Fizz 4 Buzz] +""" +class Solution: + # @param A : integer + # @return a list of strings + def fizzBuzz(self, A): + res = [] + for i in range(1, A+1): + if not i % 3 and not i % 5: + res.append("FizzBuzz") + elif not i % 3: + res.append("Fizz") + elif not i % 5: + res.append("Buzz") + else: + res.append(str(i)) + return res diff --git a/Python/Interviewbit/Math/mathbug01.py b/Python/Interviewbit/Math/mathbug01.py new file mode 100644 index 0000000..1004307 --- /dev/null +++ b/Python/Interviewbit/Math/mathbug01.py @@ -0,0 +1,16 @@ +""" +Problem Link: https://www.interviewbit.com/problems/mathbug01/ + +Following code tries to figure out if a number is prime +However, it has a bug in it. +Please correct the bug and then submit the code. +""" +class Solution: + # @param A : integer + # @return an integer + def isPrime(self, A): + upperLimit = int(A**0.5) + for i in xrange(2, upperLimit + 1): + if A % i == 0: + return 0 + return int(A != 1) diff --git a/Python/Interviewbit/Math/palindrome-integer.py b/Python/Interviewbit/Math/palindrome-integer.py new file mode 100644 index 0000000..5394248 --- /dev/null +++ b/Python/Interviewbit/Math/palindrome-integer.py @@ -0,0 +1,27 @@ +""" +Problem Link: https://www.interviewbit.com/problems/palindrome-integer/ + +Determine whether an integer is a palindrome. Do this without extra space. +A palindrome integer is an integer x for which reverse(x) = x where reverse(x) is x with +its digit reversed. + +Negative numbers are not palindromic. + +Example : +Input : 12121 +Output : True + +Input : 123 +Output : False +""" +class Solution: + # @param A : integer + # @return an integer + def isPalindrome(self, x): + if x < 0 or (x % 10 == 0 and x != 0): + return 0 + rev = 0 + while x > rev: + rev = (rev*10) + (x%10) + x //= 10 + return int(rev == x or rev//10 == x) diff --git a/Python/Interviewbit/Strings/length-of-last-word.py b/Python/Interviewbit/Strings/length-of-last-word.py new file mode 100644 index 0000000..58f362d --- /dev/null +++ b/Python/Interviewbit/Strings/length-of-last-word.py @@ -0,0 +1,24 @@ +""" +Problem Link: https://www.interviewbit.com/problems/length-of-last-word/ + +Given a string s consists of upper/lower-case alphabets and empty space characters ' ', return the length of last word in the string. +If the last word does not exist, return 0. +Note: A word is defined as a character sequence consists of non-space characters only. + +Example: +Given s = "Hello World", +return 5 as length("World") = 5. +Please make sure you try to solve this problem without using library functions. Make sure you only traverse the string once. +""" +class Solution: + # @param A : string + # @return an integer + def lengthOfLastWord(self, A): + index = len(A) - 1 + while index >= 0 and A[index] == ' ': + index -= 1 + + for i in range(index, -1, -1): + if A[i] == ' ' and flag: + return len(A) - i - 1 + return index if index != -1 else 0 diff --git a/Python/Interviewbit/Strings/palindrome-string.py b/Python/Interviewbit/Strings/palindrome-string.py new file mode 100644 index 0000000..9a4f0db --- /dev/null +++ b/Python/Interviewbit/Strings/palindrome-string.py @@ -0,0 +1,26 @@ +""" +Problem Link: https://www.interviewbit.com/problems/palindrome-string/ + +Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. + +Example: +"A man, a plan, a canal: Panama" is a palindrome. +"race a car" is not a palindrome. +Return 0 / 1 ( 0 for false, 1 for true ) for this problem +""" +class Solution: + # @param A : string + # @return an integer + def isPalindrome(self, A): + start, end = 0, len(A) - 1 + while start < end: + if not A[start].isalnum(): + start += 1 + elif not A[end].isalnum(): + end -= 1 + elif A[start].lower() != A[end].lower(): + return 0 + else: + start += 1 + end -= 1 + return 1 diff --git a/Python/Interviewbit/Two_Pointers/container-with-most-water.py b/Python/Interviewbit/Two_Pointers/container-with-most-water.py new file mode 100644 index 0000000..28088f6 --- /dev/null +++ b/Python/Interviewbit/Two_Pointers/container-with-most-water.py @@ -0,0 +1,35 @@ +""" +Problem Link: https://www.interviewbit.com/problems/container-with-most-water/ + +Given n non-negative integers a1, a2, ..., an, +where each represents a point at coordinate (i, ai). +'n' vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). + +Find two lines, which together with x-axis forms a container, such that the container contains +the most water. +Your program should return an integer which corresponds to the maximum area of water +that can be contained ( Yes, we know maximum area instead of maximum volume sounds weird. +But this is 2D plane we are working with for simplicity ). + +Note: You may not slant the container. + +Example : +Input : [1, 5, 4, 3] +Output : 6 + +Explanation : 5 and 3 are distance 2 apart. So size of the base = 2. +Height of container = min(5, 3) = 3. +So total area = 3 * 2 = 6 +""" +class Solution: + # @param A : list of integers + # @return an integer + def maxArea(self, A): + maxarea, l, r = 0, 0, len(A)-1 + while l < r: + maxarea = max(maxarea, min(A[l], A[r]) * (r-l)) + if A[l] < A[r]: + l += 1 + else: + r -= 1 + return maxarea diff --git a/Python/Interviewbit/Two_Pointers/intersection-of-sorted-arrays.py b/Python/Interviewbit/Two_Pointers/intersection-of-sorted-arrays.py new file mode 100644 index 0000000..e836897 --- /dev/null +++ b/Python/Interviewbit/Two_Pointers/intersection-of-sorted-arrays.py @@ -0,0 +1,39 @@ +""" +Problem Link: https://www.interviewbit.com/problems/intersection-of-sorted-arrays/ + +Find the intersection of two sorted arrays. +OR in other words, +Given 2 sorted arrays, find all the elements which occur in both the arrays. + +Example : +Input : + A : [1 2 3 3 4 5 6] + B : [3 3 5] +Output : [3 3 5] + +Input : + A : [1 2 3 3 4 5 6] + B : [3 5] +Output : [3 5] + +NOTE : For the purpose of this problem ( as also conveyed by the sample case ), +assume that elements that appear more than once in both arrays should be included +multiple times in the final output. +""" +class Solution: + # @param A : tuple of integers + # @param B : tuple of integers + # @return a list of integers + def intersect(self, A, B): + res = [] + index1 = index2 = 0 + while index1 < len(A) and index2 < len(B): + if A[index1] == B[index2]: + res.append(A[index1]) + index1 += 1 + index2 += 1 + elif A[index1] > B[index2]: + index2 += 1 + else: + index1 += 1 + return res diff --git a/Python/Interviewbit/Two_Pointers/merge-two-sorted-lists-ii.py b/Python/Interviewbit/Two_Pointers/merge-two-sorted-lists-ii.py new file mode 100644 index 0000000..1dda5b1 --- /dev/null +++ b/Python/Interviewbit/Two_Pointers/merge-two-sorted-lists-ii.py @@ -0,0 +1,38 @@ +""" +Problem Link: https://www.interviewbit.com/problems/merge-two-sorted-lists-ii/ + +Given two sorted integer arrays A and B, merge B into A as one sorted array. + +Note: You have to modify the array A to contain the merge of A and B. Do not output anything in your code. + +If the number of elements initialized in A and B are m and n respectively, the resulting size of array A after +your code is executed should be m + n + +Example : +Input : + A : [1 5 8] + B : [6 9] +Modified A : [1 5 6 8 9] +""" +class Solution: + # @param A : list of integers + # @param B : list of integers + def merge(self, A, B): + m = len(A) - 1 + n = len(B) - 1 + index = len(A) + len(B) - 1 + A += [0] * len(B) + while m >= 0 and n >=0: + if A[m] > B[n]: + A[index] = A[m] + m -= 1 + else: + A[index] = B[n] + n -= 1 + index -= 1 + + while n >= 0: + A[index] = B[n] + n -= 1 + index -= 1 + return A diff --git a/Python/hackerearth/hamiltonian-and-lagrangian.py b/Python/hackerearth/hamiltonian-and-lagrangian.py new file mode 100644 index 0000000..a813201 --- /dev/null +++ b/Python/hackerearth/hamiltonian-and-lagrangian.py @@ -0,0 +1,39 @@ +""" +Problem Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/hamiltonian-and-lagrangian/ + +Students have become secret admirers of SEGP. They find the course exciting and the professors amusing. +After a superb Mid Semester examination its now time for the results. The TAs have released the +marks of students in the form of an array, where arr[i] represents the marks of the ith student. +Since you are a curious kid, you want to find all the marks that are not smaller than those on its +right side in the array. + +Input Format +The first line of input will contain a single integer n denoting the number of students. +The next line will contain n space separated integers representing the marks of students. + +Output Format +Output all the integers separated in the array from left to right that are not smaller than +those on its right side. + +Constraints +1 <= n <= 1000000 +0 <= arr[i] <= 10000 + +SAMPLE INPUT +6 +16 17 4 3 5 2 +SAMPLE OUTPUT +17 5 2 +""" +def maxMarks(marks): + res = [] + maxMark = -1 + for mark in marks[::-1]: + if mark >= maxMark: + maxMark = mark + res.append(mark) + return res[::-1] + +n = int(input()) +marks = list(map(int,input().split())) +print(*maxMarks(marks)) \ No newline at end of file diff --git a/Python/hackerearth/maximize-the-earning.py b/Python/hackerearth/maximize-the-earning.py new file mode 100644 index 0000000..5473de2 --- /dev/null +++ b/Python/hackerearth/maximize-the-earning.py @@ -0,0 +1,16 @@ +""" +Problem Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/maximize-the-earning-137963bc-323025a6/ +""" +def rupeesEarned(buildings,cost): + height = -1 + count = 0 + for building in buildings: + if building > height: + count += 1 + height = building + return count*cost + +for _ in range(int(input())): + n,r = map(int,input().split()) + buildings = list(map(int,input().split())) + print(rupeesEarned(buildings,r)) \ No newline at end of file diff --git a/Python/hackerearth/memorise-me.py b/Python/hackerearth/memorise-me.py new file mode 100644 index 0000000..3ba46cd --- /dev/null +++ b/Python/hackerearth/memorise-me.py @@ -0,0 +1,66 @@ +""" +Problem Link: https://www.hackerearth.com/practice/data-structures/arrays/1-d/practice-problems/algorithm/memorise-me/ + +Arijit is a brilliant boy. He likes memory games. He likes to participate alone but this time +he has to have a partner. So he chooses you. +In this Game , your team will be shown N numbers for few minutes . You will have to memorize +these numbers. +Now, the questioner will ask you Q queries, in each query He will give you a number , and you +have to tell him the total number of occurrences of that number in the array of numbers shown to your team . If the number is not present , then you will have to say “NOT PRESENT” (without quotes). + +INPUT And OUTPUT +The first line of input will contain N, an integer, which is the total number of numbers shown +to your team. +The second line of input contains N space separated integers . +The third line of input contains an integer Q , denoting the total number of integers. +The Next Q lines will contain an integer denoting an integer, B[i] , for which you have to +print the number of occurrences of that number (B[i]) in those N numbers on a new line. +If the number B[i] isn’t present then Print “NOT PRESENT” (without quotes) on a new line. + +SAMPLE INPUT +6 +1 1 1 2 2 0 +6 +1 +2 +1 +0 +3 +4 + +SAMPLE OUTPUT +3 +2 +3 +1 +NOT PRESENT +NOT PRESENT + +Explanation +The given array is (1,1,1,2,2,0) of size 6. +Total number of queries is 6 also. +For the first query i.e for 1 , the total of number of occurrences of 1 in the given array is 3. +Hence the corresponding output is 3. +For the second query i.e. for 2, the total of number of occurrences of 2 in the given array is 2. +Hence the corresponding output is 2. +For the fifth query i.e. for 3. 3 is not present in the array . So the corresponding output is +"NOT PRESENT" (without quotes). +""" +def countNo(arr): + count = {} + for n in arr: + if n in count: + count[n] += 1 + else: + count[n] = 1 + return count + +n = int(input()) +arr = list(map(int,input().split())) +count = countNo(arr) +for _ in range(int(input())): + no = int(input()) + if no in count: + print(count[no]) + else: + print("NOT PRESENT") \ No newline at end of file diff --git a/Python/reduce_the_fraction.py b/Python/hackerearth/reduce_the_fraction.py similarity index 100% rename from Python/reduce_the_fraction.py rename to Python/hackerearth/reduce_the_fraction.py diff --git a/Python/simple_search.py b/Python/hackerearth/simple_search.py similarity index 100% rename from Python/simple_search.py rename to Python/hackerearth/simple_search.py diff --git a/Python/special_series_sum.py b/Python/hackerearth/special_series_sum.py similarity index 100% rename from Python/special_series_sum.py rename to Python/hackerearth/special_series_sum.py diff --git a/Python/other/candy-crush.py b/Python/other/candy-crush.py new file mode 100644 index 0000000..937c596 --- /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]: + 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]) 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)