├── Arrays ├── 2D Array_HackerRank.py ├── Abstract.py ├── Apple.class ├── Bank.class ├── Bank.java ├── BinarySearch.java ├── Binary_Search ├── Campus.py ├── First.cpp ├── Fruit.class ├── GeneralBank.class ├── ICICIBank.class ├── Inflight.py ├── Kadane's_algorithm.py ├── KotMBank.class ├── Last.class ├── Last.java ├── Maximum_profit.java ├── Meeting.py ├── Merge.class ├── Merge.java ├── Merge.js ├── Merge.py ├── MonotonicArray.py ├── MoveElementToEnd.py ├── NumberLineJumps.py ├── Numbers.py ├── OddOneOut.py ├── Orange.class ├── PerfectString.py ├── PermutationPalindrome.py ├── PickingNumbers.py ├── Reverse of Lists.py ├── Sample.class ├── Sample.java ├── SmallestDifference.py ├── Solution.py ├── Stack.py ├── Sum.py ├── Task.py ├── Thanos.py ├── ThreeNumbersSum.py ├── TimeConversion.py ├── TopScores.py ├── Triplet.py ├── TwoNumbersSum.py ├── TwoSum(Returning index).py ├── UglyNumber.py ├── Unique.class ├── Unique.java ├── UserException.class ├── amazon.py ├── balance.py ├── candy.py ├── defuse.py ├── equivalent.py ├── fairarray.py ├── pattern.py ├── prefix.py ├── removedup.py ├── reverse.py ├── reversestring.py ├── reversewords.py ├── smallestString.py ├── wordcloud.py └── zeromatrix.py ├── CodeChef ├── Atm.py └── Enormous.py ├── Data Structures ├── Arrays │ ├── BillDivision.py │ ├── ClassObjects.py │ ├── Duplicate.py │ ├── HourGlass.py │ ├── Intersection.py │ ├── Iterator.py │ ├── Merge.py │ ├── MinMax.py │ ├── Missing.py │ ├── Move.py │ ├── MoveNegative.py │ ├── Palindrome.py │ ├── Reverse.py │ ├── Solution.py │ ├── SortZeroOne.py │ ├── Sorted.py │ ├── SortingColors.py │ ├── SortingZero.py │ ├── Spiral.py │ ├── StringCompression.py │ ├── StringMethods.py │ ├── Symmetric.py │ ├── ThreeNumber.py │ ├── TwoSum.py │ ├── Union.py │ ├── countpairs.py │ ├── findmissing.py │ ├── jumps.py │ ├── kadane.py │ ├── kadanes.py │ ├── kmaxmin.py │ ├── lonely.py │ ├── mergetwo.py │ ├── monotonic.py │ ├── oneaway.py │ ├── remove_duplicates.py │ ├── reversearray.py │ ├── reverseingroups.py │ ├── rotate.py │ ├── smallest.py │ ├── smallestDiv.py │ └── word.py ├── Java │ ├── Factorial.java │ ├── HelloWorld.java │ ├── Sample.class │ ├── Sample.java │ ├── factorial │ │ └── Factorial.class │ └── world │ │ └── HelloWorld.class ├── Queue │ └── Printermanagement ├── Queues │ ├── CreateQueue.class │ ├── Queue.java │ ├── QueueList.java │ ├── QueueList.py │ ├── circularqueue.py │ ├── queue.py │ └── queuestack.py └── Trees │ ├── prog.py │ └── tree.py ├── Doubly Linked List ├── HackerRank ├── Average.sql ├── Average_Population.sql ├── Binary_Tree_Node.sql ├── Count_Function.sql ├── Employee_Names.sql ├── Employee_Salary.sql ├── Higher_Than_75marks.sql ├── Japan_Population.sql ├── Japanese_City_Attribute.sql ├── Japanese_City_Names.sql ├── New_Companies.sql ├── Occupations.sql ├── Population_Density_Difference.sql ├── Select_All.sql ├── Select_ByID.sql ├── Select_Query(I).sql ├── Select_Query(II).sql ├── Sum_Function.sql ├── ThePads.sql ├── The_Blunder.sql ├── Top_Earners.sql ├── Triangle_Type.sql ├── Weather_Observation_1.sql ├── Weather_Observation_10.sql ├── Weather_Observation_11.sql ├── Weather_Observation_12.sql ├── Weather_Observation_13.sql ├── Weather_Observation_14.sql ├── Weather_Observation_15.sql ├── Weather_Observation_16.sql ├── Weather_Observation_17.sql ├── Weather_Observation_18.sql ├── Weather_Observation_19.sql ├── Weather_Observation_2.sql ├── Weather_Observation_20.sql ├── Weather_Observation_3.sql ├── Weather_Observation_4.sql ├── Weather_Observation_5.sql ├── Weather_Observation_6.sql ├── Weather_Observation_7.sql ├── Weather_Observation_8.sql └── Weather_Observation_9.sql ├── LICENSE.md ├── LeetCode └── multiply_strings.py ├── LinkedList ├── Circular.class ├── Circular.java ├── Circular.py ├── CircularLinkedList.class ├── Decorators.py ├── Doubly Linked List ├── Doubly-Linked-List.py ├── LabProgram.class ├── LabProgram.java ├── LinkedList.class ├── LinkedList.py ├── List.class ├── List.java ├── List.py ├── Node.class ├── Operator.py └── UserException.class ├── Matrix └── diagonal.py ├── Printermanagement ├── Problems ├── Insertion.class ├── Insertion.java ├── Negative.class ├── Negative.java ├── Prime.class ├── Prime.java ├── PrimeCheck.class ├── Prob1.py ├── Prob2.py ├── Selection.class ├── Selection.java ├── Shifting.class ├── Shifting.java ├── Test.class ├── Test.java ├── armstrong.py ├── codechef.py ├── generate.py ├── permutation.py ├── prob3.py ├── prob4.py ├── prob5.py ├── prob6.py └── shifting.py ├── Stack ├── Node.class ├── Stack.class ├── Stack.java ├── Stack.py ├── StackClass.class ├── StackList.class ├── StackList.java ├── StackList.py ├── Words.py ├── balance.py ├── infix.py └── paranthesis.py └── readme.md /Arrays/2D Array_HackerRank.py: -------------------------------------------------------------------------------- 1 | def hourglassSum(arr): 2 | maxsum=-63 3 | for i in range(4): 4 | for j in range(4): 5 | top=sum(arr[i][j:j+3]) 6 | mid=arr[i+1][j+1] 7 | bottom=sum(arr[i+2][j:j+3]) 8 | hourglass =top+mid+bottom 9 | if hourglass>maxsum: 10 | maxsum=hourglass 11 | return maxsum 12 | Test_cases=int(input()) 13 | while t>0: 14 | n=int(input("Size of The Array")) 15 | arr=[int(x) for x in input().split()] 16 | print(hourglassSum(arr)) 17 | t-=1 18 | -------------------------------------------------------------------------------- /Arrays/Abstract.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | class AbstractClass(ABC) : 4 | 5 | @abstractmethod 6 | def myabstractMethod(self) : 7 | pass 8 | 9 | 10 | 11 | if __name__ == '__main__' : 12 | 13 | arr = [1,2,3,4,5,6,7] 14 | print(len(arr)) 15 | print(arr.count(1)) 16 | 17 | 18 | -------------------------------------------------------------------------------- /Arrays/Apple.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Apple.class -------------------------------------------------------------------------------- /Arrays/Bank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Bank.class -------------------------------------------------------------------------------- /Arrays/Bank.java: -------------------------------------------------------------------------------- 1 | 2 | abstract class GeneralBank { 3 | 4 | abstract double getSavingInterestRate(); 5 | abstract double getFixedInterestRate(); 6 | 7 | } 8 | 9 | class ICICIBank extends GeneralBank { 10 | private double saving_rate; 11 | private double fixed_rate; 12 | 13 | public ICICIBank() { 14 | 15 | } 16 | 17 | public ICICIBank(double a, double b) { 18 | this.saving_rate = a; 19 | this.fixed_rate = b; 20 | } 21 | 22 | public double getFixedInterestRate () { 23 | return this.fixed_rate; 24 | } 25 | 26 | public double getSavingInterestRate() { 27 | return this.saving_rate; 28 | } 29 | 30 | } 31 | 32 | 33 | class KotMBank extends GeneralBank { 34 | private double saving_rate; 35 | private double fixed_rate; 36 | 37 | public KotMBank() { 38 | 39 | } 40 | 41 | public KotMBank(double a, double b) { 42 | this.saving_rate = a; 43 | this.fixed_rate = b; 44 | } 45 | 46 | public double getFixedInterestRate () { 47 | return this.fixed_rate; 48 | } 49 | 50 | public double getSavingInterestRate() { 51 | return this.saving_rate; 52 | } 53 | 54 | } 55 | 56 | 57 | class Bank { 58 | public static void main(String[] args) { 59 | ICICIBank ob = new ICICIBank(4.0, 8.5); 60 | KotMBank ob2 = new KotMBank(6.0, 9.0); 61 | GeneralBank ref = ob; 62 | System.out.println(ref.getSavingInterestRate()+" "+ref.getFixedInterestRate()); 63 | ref = ob2; 64 | System.out.println(ref.getSavingInterestRate()+" "+ref.getFixedInterestRate()); 65 | } 66 | } -------------------------------------------------------------------------------- /Arrays/BinarySearch.java: -------------------------------------------------------------------------------- 1 | 2 | class BinarySearch { 3 | 4 | public static void binarySearch(int[] arr, int ub, int lb) { 5 | int mid = (lb+ub)/2; 6 | } 7 | 8 | public static void main(String[] args) { 9 | 10 | } 11 | } -------------------------------------------------------------------------------- /Arrays/Binary_Search: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // A iterative binary search function. It returns 6 | // location of x in given array arr[l..r] if present, 7 | // otherwise -1 8 | int binarySearch(int arr[], int l, int r, int x) 9 | { 10 | while (l <= r) { 11 | int m = l + (r - l) / 2; 12 | 13 | // Check if x is present at mid 14 | if (arr[m] == x) 15 | return m; 16 | 17 | // If x greater, ignore left half 18 | if (arr[m] < x) 19 | l = m + 1; 20 | 21 | // If x is smaller, ignore right half 22 | else 23 | r = m - 1; 24 | } 25 | 26 | // if we reach here, then element was 27 | // not present 28 | return -1; 29 | } 30 | 31 | int main(void) 32 | { 33 | int arr[] = { 2, 3, 4, 10, 40 }; 34 | int x = 10; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | int result = binarySearch(arr, 0, n - 1, x); 37 | (result == -1) ? cout << "Element is not present in array" 38 | : cout << "Element is present at index " << result; 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Arrays/Campus.py: -------------------------------------------------------------------------------- 1 | 2 | # capgemini solution 3 | 4 | def solution(arr : list) : 5 | left = list();right=list(); 6 | length = len(arr) 7 | 8 | i = 0 9 | max_sum = -99999 10 | while length >= len(arr) // 2 : 11 | 12 | left = arr[i:i+length//2] 13 | right = arr[::-1][:length//2] 14 | length-=1 15 | i+=1 16 | 17 | c_sum = 0 18 | for j in range(len(left)) : 19 | c_sum+= left[j]*right[j] 20 | 21 | if c_sum > max_sum : 22 | max_sum = c_sum 23 | 24 | return max_sum 25 | 26 | 27 | if __name__ == '__main__' : 28 | arr = list(map(int, input().split())) 29 | print(solution(arr)) -------------------------------------------------------------------------------- /Arrays/First.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | -------------------------------------------------------------------------------- /Arrays/Fruit.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Fruit.class -------------------------------------------------------------------------------- /Arrays/GeneralBank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/GeneralBank.class -------------------------------------------------------------------------------- /Arrays/ICICIBank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/ICICIBank.class -------------------------------------------------------------------------------- /Arrays/Inflight.py: -------------------------------------------------------------------------------- 1 | # Inflight entertainment 2 | # This algorithm takes O(n) time complexity and o(n) space complexity 3 | 4 | def flight_entertainment(arr : list, target : int) -> bool : 5 | # movie already been seen 6 | has_seen = set() 7 | 8 | for el in arr : 9 | second_movie_length = target - el 10 | 11 | if second_movie_length in has_seen : 12 | return True 13 | 14 | has_seen.add(el) 15 | 16 | return False 17 | 18 | 19 | # this algorithm takes O(nlogn) time complexity and O(1) space complexity 20 | def flight_movies(arr : list, target : int) -> bool : 21 | left = 0;right = len(arr) - 1 22 | arr.sort() 23 | 24 | while left < right : 25 | csum = arr[left] + arr[right] 26 | if csum == target : 27 | return True 28 | elif csum < target : 29 | left+=1 30 | else : 31 | right =- 1 32 | 33 | return False 34 | 35 | 36 | if __name__ == "__main__": 37 | print(flight_entertainment([1,2,1,4,5,6], 4)) -------------------------------------------------------------------------------- /Arrays/Kadane's_algorithm.py: -------------------------------------------------------------------------------- 1 | # Python program to find maximum contiguous subarray 2 | #Kadane's algorithm 3 | # Function to find the maximum contiguous subarray 4 | from sys import maxint 5 | def maxSubArraySum(a,size): 6 | 7 | max_so_far = -maxint - 1 8 | max_ending_here = 0 9 | 10 | for i in range(0, size): 11 | max_ending_here = max_ending_here + a[i] 12 | if (max_so_far < max_ending_here): 13 | max_so_far = max_ending_here 14 | 15 | if max_ending_here < 0: 16 | max_ending_here = 0 17 | return max_so_far 18 | 19 | # Driver function to check the above function 20 | a = [-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7] 21 | print "Maximum contiguous sum is", maxSubArraySum(a,len(a)) 22 | -------------------------------------------------------------------------------- /Arrays/KotMBank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/KotMBank.class -------------------------------------------------------------------------------- /Arrays/Last.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Last.class -------------------------------------------------------------------------------- /Arrays/Last.java: -------------------------------------------------------------------------------- 1 | 2 | class UserException extends Exception { 3 | 4 | public UserException(){ 5 | 6 | } 7 | 8 | public String toString() { 9 | return "You have entered an invalid name or age"; 10 | } 11 | } 12 | 13 | public class Last { 14 | 15 | public static void main(String[] args) { 16 | String name = args[0]; 17 | int age = Integer.parseInt(args[1]); 18 | 19 | try { 20 | if(age >=18 && age<60) { 21 | System.out.println("Valid name and age entered"); 22 | }else{ 23 | throw new UserException(); 24 | } 25 | }catch(UserException exception) { 26 | System.out.println("Exception found = " + exception.toString()); 27 | } 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Arrays/Maximum_profit.java: -------------------------------------------------------------------------------- 1 | You have made a smartphone app and want to set its price such that the profit earned is maximised. There are certain buyers who will buy your app only if their budget is greater than or equal to your price. 2 | You will be provided with a list of size N having budgets of buyers and you need to return the maximum profit that you can earn. 3 | Lets say you decide that price of your app is Rs. x and there are N number of buyers. So maximum profit you can earn is : 4 | m * x 5 | where m is total number of buyers whose budget is greater than or equal to x. 6 | Input format : 7 | Line 1 : N (No. of buyers) 8 | Line 2 : Budget of buyers (separated by space) 9 | Output Format : 10 | Maximum profit 11 | Constraints : 12 | 1 <= N <= 10^6 13 | Sample Input 1 : 14 | 4 15 | 30 20 53 14 16 | Sample Output 1 : 17 | 60 18 | Sample Output 1 Explanation : 19 | Price of your app should be Rs. 20 or Rs. 30. For both prices, you can get the profit Rs. 60. 20 | Sample Input 2 : 21 | 5 22 | 34 78 90 15 67 23 | Sample Output 2 : 24 | 201 25 | Sample Output 2 Explanation : 26 | Price of your app should be Rs. 67. You can get the profit Rs. 201 (i.e. 3 * 67). 27 | 28 | 29 | Below is the implementation of above approach 30 | import java.util.Arrays; 31 | public class solution { 32 | 33 | public static int maximumProfit(int budget[]) { 34 | 35 | Arrays.sort(budget); 36 | int max=0; 37 | for(int x=0;xmax) 41 | max=p; 42 | } 43 | return max; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Arrays/Meeting.py: -------------------------------------------------------------------------------- 1 | """ 2 | Your company built an in-house calendar tool called hiCal. You want to add a feature to see the times in a day when everyone is available. 3 | """ 4 | 5 | def hiCal(arr : list) -> list : 6 | # sorting by the order of start time 7 | arr.sort() 8 | 9 | merged_meetinds = [arr[0]] 10 | 11 | for current_start_time, current_end_time in arr[1:] : 12 | last_start_time, last_end_time = merged_meetinds[-1] 13 | 14 | if current_start_time <= last_end_time : 15 | merged_meetinds[-1] = (last_start_time, max(current_start_time, last_end_time)) 16 | 17 | else : 18 | merged_meetinds.append((current_start_time, current_end_time)) 19 | 20 | 21 | return merged_meetinds 22 | 23 | if __name__ == '__main__' : 24 | print(hiCal([(5,8),(1,4),(6,8)])) -------------------------------------------------------------------------------- /Arrays/Merge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Merge.class -------------------------------------------------------------------------------- /Arrays/Merge.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.ArrayList; 3 | import java.util.*; 4 | 5 | public class Merge { 6 | 7 | public static int[] mergeArrays(int[] arr1, int[] arr2) { 8 | int i=0, j=0; 9 | 10 | int[] temp_arr = new int[arr1.length+arr2.length]; 11 | 12 | for(;i arr2[j]) { 14 | int temp = arr1[i]; 15 | arr1[i] = arr2[j]; 16 | arr2[j] = temp; 17 | Arrays.sort(arr2); 18 | } 19 | } 20 | 21 | i=0; 22 | for(int el : arr1) { 23 | temp_arr[i++] = el; 24 | } 25 | 26 | for(int el: arr2) { 27 | temp_arr[i++] = el; 28 | } 29 | 30 | return temp_arr; 31 | 32 | } 33 | 34 | 35 | public static void main(String[] args) { 36 | int[] arr1 = {1,3,5,7,9}; 37 | int[] arr2 = {2,4,6,8,10}; 38 | 39 | arr1 = mergeArrays(arr1, arr2); 40 | 41 | for (int el : arr1) { 42 | System.out.print(el); 43 | } 44 | 45 | } 46 | } -------------------------------------------------------------------------------- /Arrays/Merge.js: -------------------------------------------------------------------------------- 1 | 2 | function merge(arr1, arr2) { 3 | 4 | let i=0, j=0; 5 | 6 | while (i arr2[j]) { 8 | let temp = arr1[i]; 9 | arr1[i] = arr2[j]; 10 | arr2[j] = temp; 11 | arr2.sort((a,b)=>a-b); 12 | } 13 | i+=1; 14 | } 15 | 16 | arr2.forEach(el => { 17 | arr1.push(el); 18 | }) 19 | 20 | } 21 | 22 | arr = [1,3,5,7,9] 23 | arr2 = [2,4,6,8,10] 24 | 25 | merge(arr, arr2) 26 | 27 | console.log(arr) -------------------------------------------------------------------------------- /Arrays/Merge.py: -------------------------------------------------------------------------------- 1 | """ 2 | QUESTION STATEMENT : MERGE TWO SORTED ARRAYS WITHOUT USING ANY EXTRA SPACE 3 | 4 | example : 5 | 6 | arr1 = {1,3,5,7,9} size = n 7 | arr2 = {2,4,6,8,10} size = m 8 | 9 | arr1 after merging = {1,2,3,4,5,6,7,8,9,10} 10 | 11 | """ 12 | 13 | def mergeArrays(arr : list, arr2 : list) : 14 | 15 | i = 0;j = 0; 16 | 17 | while i < len(arr) : # O(n) 18 | if arr[i] > arr2[j] : 19 | arr[i], arr2[j] = arr2[j], arr[i] # swapping the elements 20 | 21 | arr2.sort() # O(mlog2m) 22 | 23 | i+=1 24 | 25 | # total complexity = (n*m)log2m 26 | 27 | for el in arr2 : 28 | arr.append(el) 29 | 30 | 31 | if __name__ == '__main__' : 32 | arr = [1,3,5,7,9] 33 | arr2 = [2,4,6,8,10] 34 | 35 | mergeArrays(arr, arr2) 36 | 37 | print(arr) 38 | 39 | 40 | -------------------------------------------------------------------------------- /Arrays/MonotonicArray.py: -------------------------------------------------------------------------------- 1 | # Problem Statement : Check whether the given array is a Monotonic array 2 | 3 | def isIncreasing(arr : list) -> bool : 4 | for i in range(len(arr) - 1) : 5 | if arr[i] > arr[i+1] : 6 | return False 7 | 8 | return True 9 | 10 | def isDecreasing(arr : list) -> bool : 11 | for i in range(len(arr) - 1) : 12 | if arr[i] < arr[i+1] : 13 | return False 14 | return True 15 | 16 | def isMonotic(arr : list) -> bool : 17 | if isIncreasing(arr) or isDecreasing(arr) : 18 | return False 19 | else : 20 | return True 21 | 22 | 23 | if __name__ == '__main__' : 24 | print(isMonotic([-1,-5,-10,-1100, -1101, -900])) 25 | # output = 1 26 | -------------------------------------------------------------------------------- /Arrays/MoveElementToEnd.py: -------------------------------------------------------------------------------- 1 | # Moving elements to the end 2 | 3 | def moveToEnd(arr : list, sk : int) : 4 | left = 0;right = len(arr)-1 5 | 6 | while left < right : 7 | 8 | while arr[right] == sk : 9 | right -= 1 10 | 11 | if arr[left] == sk : 12 | arr[left], arr[right] = arr[right], arr[left] 13 | 14 | left += 1 15 | 16 | return arr 17 | 18 | if __name__ == '__main__' : 19 | print(moveToEnd([1,3,2,4,2,2,2], 2)) -------------------------------------------------------------------------------- /Arrays/NumberLineJumps.py: -------------------------------------------------------------------------------- 1 | """ 2 | You are choreographing a circus show with various animals. For one act, you are given two kangaroos on a number line ready to jump in the positive direction (i.e, toward positive infinity). 3 | 4 | The first kangaroo starts at location and moves at a rate of meters per jump. 5 | The second kangaroo starts at location and moves at a rate of meters per jump. 6 | You have to figure out a way to get both kangaroos at the same location at the same time as part of the show. If it is possible, return YES, otherwise return NO. 7 | 8 | For example, kangaroo starts at with a jump distance and kangaroo starts at with a jump distance of . After one jump, they are both at , (, ), so our answer is YES. 9 | 10 | Function Description 11 | 12 | Complete the function kangaroo in the editor below. It should return YES if they reach the same position at the same time, or NO if they don't. 13 | 14 | kangaroo has the following parameter(s): 15 | 16 | x1, v1: integers, starting position and jump distance for kangaroo 1 17 | x2, v2: integers, starting position and jump distance for kangaroo 2 18 | Input Format 19 | 20 | A single line of four space-separated integers denoting the respective values of , , , and . 21 | 22 | Constraints 23 | 24 | Output Format 25 | 26 | Print YES if they can land on the same location at the same time; otherwise, print NO. 27 | 28 | Note: The two kangaroos must land at the same location after making the same number of jumps. 29 | 30 | Sample Input 0 31 | 32 | 0 3 4 2 33 | Sample Output 0 34 | 35 | YES 36 | Explanation 0 37 | 38 | The two kangaroos jump through the following sequence of locations: 39 | 40 | image 41 | 42 | From the image, it is clear that the kangaroos meet at the same location (number on the number line) after same number of jumps ( jumps), and we print YES. 43 | 44 | Sample Input 1 45 | 46 | 0 2 5 3 47 | Sample Output 1 48 | 49 | NO 50 | Explanation 1 51 | 52 | The second kangaroo has a starting location that is ahead (further to the right) of the first kangaroo's starting location (i.e., ). Because the second kangaroo moves at a faster rate (meaning ) and is already ahead of the first kangaroo, the first kangaroo will never be able to catch up. Thus, we print NO.""" 53 | 54 | def kangaroo(x1, v1, x2, v2) : 55 | return "YES" if (x2-x1)*(v2-v1) < 0 and (x2-x1)%(v2-v1) == 0 else "NO" 56 | 57 | if __name__ == '__main__' : 58 | print(kangaroo(1,2,2,1)) -------------------------------------------------------------------------------- /Arrays/Numbers.py: -------------------------------------------------------------------------------- 1 | # program to find the number of digits in a given number 2 | import math 3 | 4 | def calDigits(num : int) : 5 | return math.log10(num) 6 | 7 | if __name__ == '__main__' : 8 | print(math.ceil(calDigits(12345))) -------------------------------------------------------------------------------- /Arrays/OddOneOut.py: -------------------------------------------------------------------------------- 1 | # Odd one out from hackerearth solution 2 | 3 | def oddOneOut(arr : list) : 4 | n = len(arr) 5 | arr.sort() 6 | summation = sum(arr) 7 | 8 | actual_sum = int((n+1)/2 * (2*arr[0] + (n*2))) 9 | print(actual_sum) 10 | return actual_sum - summation 11 | 12 | 13 | if __name__ == '__main__' : 14 | arr = list(map(int, input("Enter the elements into the array : ").split())) 15 | print(oddOneOut(arr)) -------------------------------------------------------------------------------- /Arrays/Orange.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Orange.class -------------------------------------------------------------------------------- /Arrays/PerfectString.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import Counter 3 | 4 | def perfectString(string) : 5 | 6 | counter = Counter(string) 7 | string_len = len(string) 8 | each_char_length = string_len//len(counter) 9 | 10 | res = 0 11 | 12 | for el in counter.keys() : 13 | if not counter[el] == each_char_length : 14 | res += abs(counter[el] // each_char_length) 15 | 16 | 17 | return res 18 | 19 | 20 | if __name__ == '__main__' : 21 | print(perfectString("xyyzxyxxy")) 22 | -------------------------------------------------------------------------------- /Arrays/PermutationPalindrome.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write an efficient function that checks whether any permutation of an input string is a palindrome or not. 3 | """ 4 | 5 | def check_permutation_palindrome(string : str) -> bool : 6 | 7 | has_seen = set() 8 | 9 | for char in string : 10 | if char in has_seen : has_seen.remove(char) 11 | else : has_seen.add(char) 12 | 13 | return len(has_seen) <= 1 14 | 15 | 16 | if __name__ == "__main__": 17 | print(check_permutation_palindrome('civil')) -------------------------------------------------------------------------------- /Arrays/PickingNumbers.py: -------------------------------------------------------------------------------- 1 | 2 | # hackerrank problem of problem solving 3 | # problem statement : Picking Numbers 4 | 5 | 6 | def pickingNumbers(arr) : 7 | left = 0 8 | max_sum = 0;max_left = 0;max_right=0 9 | 10 | for i in range(1, len(arr)) : 11 | if abs(arr[i] - arr[i-1]) > 1 : 12 | number = i - left 13 | if number > max_sum : 14 | max_sum = number 15 | max_left = left 16 | max_right = i-1 17 | left = i 18 | 19 | return max_sum+1 20 | 21 | 22 | if __name__ == "__main__" : 23 | print(pickingNumbers([1, 2, 2, 3, 1, 2])) 24 | 25 | -------------------------------------------------------------------------------- /Arrays/Reverse of Lists.py: -------------------------------------------------------------------------------- 1 | ## If You Don't Know What A list is then: List is colllection of data that can be of any Type. 2 | ## first We Create A fucntion 3 | def reverse_l(li): 4 | length= len(li) 5 | first=list(n.split()) 6 | for a in range(len(first)): ## This Range Is Converting the String input into int 7 | li[a]=int(first[a]) 8 | for i in range(length//2): 9 | li[i],li[(length-i)-1]=li[(length-i)-1],li[i] 10 | n=input("Enter Numbers given by space: ") ## here i Specify to Give Space otherwise 12345 will be considerd as one string not numbers and then cannot be splitted 11 | reverse_l(li) ## Program Can Be Modified With More Flexibilty 12 | print(li) 13 | -------------------------------------------------------------------------------- /Arrays/Sample.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Sample.class -------------------------------------------------------------------------------- /Arrays/Sample.java: -------------------------------------------------------------------------------- 1 | 2 | abstract class Fruit { 3 | protected String name, taste, size; 4 | 5 | public Fruit (String name, String taste, String size) { 6 | this.name = name; 7 | this.taste = taste; 8 | this.size = size; 9 | } 10 | 11 | abstract public void eat (); 12 | } 13 | 14 | class Apple extends Fruit { 15 | public Apple() { 16 | super("Apple", "taste like apple", "medium size"); 17 | } 18 | 19 | public void eat() { 20 | System.out.println("I am eating " + this.name + " tastes like : " + this.taste + " whose size is : " + this.size); 21 | } 22 | 23 | } 24 | 25 | class Orange extends Fruit { 26 | public Orange() { 27 | super("Orange", "taste like orange", "lasrge size"); 28 | } 29 | 30 | public void eat() { 31 | System.out.println("I am eating " + this.name + " tastes like : " + this.taste + " whose size is : " + this.size); 32 | } 33 | 34 | } 35 | 36 | class Sample { 37 | public static void main(String[] args) { 38 | Apple apple = new Apple(); 39 | Orange orange = new Orange(); 40 | apple.eat(); 41 | orange.eat(); 42 | } 43 | } -------------------------------------------------------------------------------- /Arrays/SmallestDifference.py: -------------------------------------------------------------------------------- 1 | # Smallest Difference Problem : Two arrays are given and you have to find the 2 | # pair (i , j) such abs(i-j) is the smallest where i belongs to the first array and j belong to the second array respectively 3 | 4 | def smallestDifference(arr1 : list, arr2 : list) : 5 | arr1.sort();arr2.sort() 6 | i = 0;j = 0 7 | 8 | smallest = float("inf"); 9 | smallestPair = list() 10 | 11 | while i < len(arr1) and j < len(arr2) : 12 | fnum = arr1[i];snum = arr2[j] 13 | 14 | if fnum < snum : 15 | current = snum - fnum 16 | i += 1 17 | elif snum < fnum : 18 | current = fnum - snum 19 | j += 1 20 | else : 21 | return [fnum, snum] 22 | 23 | # updating the smallest difference pair if found a new one 24 | if current < smallest : 25 | smallest = current 26 | smallestPair = [fnum, snum] 27 | 28 | return smallestPair 29 | 30 | if __name__ == '__main__' : 31 | print(smallestDifference([12,3,45,6], [2,4,4,5])) 32 | -------------------------------------------------------------------------------- /Arrays/Solution.py: -------------------------------------------------------------------------------- 1 | 2 | # program to find the number which occurs for the maximum number of times 3 | # in an array 4 | 5 | def maxTimes(arr : list) : 6 | result = dict() 7 | 8 | for el in arr : 9 | if el in result : 10 | result[el] += 1 11 | else : 12 | result[el] = 1 13 | 14 | count = max([x for x in result.values()]) 15 | 16 | if count == 1 : 17 | return -1 18 | else : 19 | return result[count] 20 | 21 | 22 | if __name__ == '__main__' : 23 | print(maxTimes([1,2,3,4,5])) -------------------------------------------------------------------------------- /Arrays/Stack.py: -------------------------------------------------------------------------------- 1 | # Stack using arrays 2 | 3 | class Stack(object) : 4 | 5 | def __init__(self) : 6 | self.arr = list() 7 | 8 | def push(self, sk) : 9 | self.arr.append(sk) 10 | 11 | def pop(self, index = None) : 12 | if index is not None : 13 | try : 14 | return self.arr.pop(index) 15 | except : 16 | pass 17 | else : 18 | try : 19 | return self.arr.pop() 20 | except IndexError as e : 21 | return e 22 | 23 | def peek(self) : 24 | return self.arr[len(self.arr) - 1] 25 | 26 | def isEmpty(self) : 27 | return self.arr is None 28 | 29 | def __repr__(self): 30 | return self.arr 31 | 32 | def __iter__(self) : 33 | self.index = 0 34 | return self 35 | 36 | def __next__(self) : 37 | if self.index < len(self.arr) : 38 | return self.arr[self.index] 39 | self.index += 1 40 | 41 | if __name__ == '__main__' : 42 | stack = Stack() 43 | stack.push(1) 44 | stack.push(2) 45 | print(stack.pop()) 46 | # for el in stack : 47 | # print(el) 48 | -------------------------------------------------------------------------------- /Arrays/Sum.py: -------------------------------------------------------------------------------- 1 | 2 | from abc import ABC, abstractclassmethod, abstractmethod 3 | 4 | class AbstractClass(ABC) : 5 | @abstractmethod 6 | def myabstractmethod(self) : 7 | pass 8 | 9 | class MyClass : 10 | 11 | def __iter__(self) : 12 | self.num = 0 13 | return self 14 | 15 | def __next__(self) : 16 | if self.num < 10 : 17 | self.num += 1 18 | else : 19 | raise StopIteration 20 | 21 | return self.num 22 | 23 | import os 24 | 25 | if __name__ == '__main__' : 26 | # ob = MyClass() 27 | # for el in ob : 28 | # print(el) 29 | os.chdir("../") 30 | print(os.listdir()) 31 | 32 | -------------------------------------------------------------------------------- /Arrays/Task.py: -------------------------------------------------------------------------------- 1 | # Monotonic array optimised solution 2 | # Time complexity = O(n) | Space Complexity : O(1) 3 | 4 | 5 | # method to check if the direction breaks 6 | def directionChanged(direction, previous, current) : 7 | difference = current - previous 8 | 9 | if direction > 0 : 10 | return difference < 0 11 | 12 | return difference > 0 13 | 14 | 15 | # function to check if the array is monotic or not 16 | def isMonotonicArray(arr : list) -> bool : 17 | 18 | if len(arr) <= 2 : 19 | return True 20 | 21 | direction = arr[1] - arr[0] 22 | 23 | for i in range(2, len(arr)) : 24 | if direction == 0 : 25 | direction = arr[i] - arr[i-1] 26 | continue 27 | 28 | if directionChanged(direction, arr[i-1], arr[i]) : 29 | return True 30 | 31 | return False 32 | 33 | 34 | # driver code 35 | if __name__ == '__main__' : 36 | print(isMonotonicArray([1,2,3,4,5])) -------------------------------------------------------------------------------- /Arrays/Thanos.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import Counter 3 | 4 | def thanosProblem(arr) : 5 | 6 | counter = Counter(arr) 7 | 8 | max_val = -999999 9 | 10 | for key in counter.keys() : 11 | if max_val < counter[key] : 12 | max_key = key 13 | max_val = counter[key] 14 | 15 | del counter[max_key] 16 | 17 | return sum(counter) 18 | 19 | if __name__ == '__main__' : 20 | print(thanosProblem([3,3,2,2,2,2,1,3])) 21 | -------------------------------------------------------------------------------- /Arrays/ThreeNumbersSum.py: -------------------------------------------------------------------------------- 1 | # Three number sum program 2 | # We will be using the sliding window algorithm here as well which will give us the complexity of O(nlogn) 3 | 4 | def sum_of_three(arr, target) : 5 | result = list() 6 | arr.sort() 7 | 8 | for i in range(len(arr)-2) : 9 | left = i+1;right=len(arr)-1 10 | 11 | while left < right : 12 | current_sum = arr[i] + arr[left] + arr[right] 13 | if current_sum == target : 14 | result.append((arr[i], arr[left], arr[right])) 15 | left+=1 16 | right-=1 17 | elif current_sum < target : 18 | left += 1 19 | elif current_sum > target : 20 | right -= 1 21 | else : 22 | print("Dont with the loop") 23 | return result 24 | 25 | if __name__ == '__main__' : 26 | print(sum_of_three([3,5,-4,8,11,1,-1,6], 10)) 27 | # -4 -1 1 3 5 6 8 11 28 | -------------------------------------------------------------------------------- /Arrays/TimeConversion.py: -------------------------------------------------------------------------------- 1 | """ 2 | Time Conversion program (Hackerrank) 3 | Given a time in -hour AM/PM format, convert it to military (24-hour) time. 4 | 5 | Note: - 12:00:00AM on a 12-hour clock is 00:00:00 on a 24-hour clock. 6 | - 12:00:00PM on a 12-hour clock is 12:00:00 on a 24-hour clock. 7 | 8 | Example 9 | 10 | 11 | Input '12:01:00AM'. 12 | 13 | 14 | Return '00:01:00'. 15 | 16 | Function Description 17 | 18 | Complete the timeConversion function in the editor below. It should return a new string representing the input time in 24 hour format. 19 | 20 | timeConversion has the following parameter(s): 21 | 22 | string s: a time in hour format 23 | Returns 24 | 25 | string: the time in hour format 26 | Input Format 27 | 28 | A single string that represents a time in -hour clock format (i.e.: or ). 29 | 30 | Constraints 31 | 32 | All input times are valid 33 | Sample Input 0 34 | 35 | 07:05:45PM 36 | Sample Output 0 37 | 38 | 19:05:45 39 | 40 | 41 | Hints : You will have to learn about split(), join(), substring(), 42 | 43 | """ 44 | 45 | def timeConversion(string : str) : 46 | # getting each part of the string 47 | new_str = string.split(":") 48 | hours = new_str[0] 49 | minutes = new_str[1] 50 | seconds = new_str[2][:2] 51 | am_pm = new_str[2][2:] 52 | 53 | # variable holding the result of the array 54 | result = "" 55 | 56 | # checking if the time is PM 57 | if am_pm == 'PM' : 58 | if int(hours) < 12 : 59 | hours = str(int(hours) + 12) 60 | 61 | # checking if the time is AM 62 | if am_pm == 'AM' : 63 | if int(hours) == 12 : 64 | hours = "00" 65 | 66 | # returning the output in the correct format 67 | return ":".join([str(hours), str(minutes), str(seconds)]) 68 | 69 | 70 | if __name__ == '__main__' : 71 | print(timeConversion("12:40:22AM")) -------------------------------------------------------------------------------- /Arrays/TopScores.py: -------------------------------------------------------------------------------- 1 | # Top Scores program 2 | """ 3 | You created a game that is more popular than angry birds. 4 | Each round, players receive a score between 0 and 100, which you can use to rank them from highest to lowest. 5 | So far you are using an algorithm that sorts in O(nlogn) time, but players are complaining that their ranking are not updated fast enough. 6 | you need a faster sorting algorithm. 7 | """ 8 | 9 | 10 | def sort_score(unsorted_scores : list, highest_possible_score : int) -> list : 11 | hashtable = [0]*highest_possible_score 12 | output = list() 13 | 14 | for score in unsorted_scores : hashtable[score] += 1 15 | 16 | for i in range(len(hashtable)-1, -1, -1) : 17 | times = hashtable[i] 18 | score = i 19 | 20 | for _ in range(times) : 21 | output.append(score) 22 | 23 | return output 24 | 25 | 26 | if __name__ == "__main__": 27 | unsorted_scores = [37, 89, 41, 65, 91, 53] 28 | HIGHEST_SCORE_POSSIBLE = 100 29 | 30 | print(sort_score(unsorted_scores, HIGHEST_SCORE_POSSIBLE)) 31 | 32 | -------------------------------------------------------------------------------- /Arrays/Triplet.py: -------------------------------------------------------------------------------- 1 | # Three number sum program 2 | # We will be using the sliding window algorithm here as well which will give us the complexity of O(nlogn) 3 | 4 | def sum_of_three(arr) : 5 | result = 0 6 | arr.sort() 7 | 8 | for i in range(len(arr)-2) : 9 | left = i+1;right=len(arr)-1 10 | 11 | while left < right : 12 | x=arr[i];y=arr[left];z=arr[right] 13 | if y-x == z-y : 14 | result+=1 15 | left+=1 16 | right-=1 17 | elif y-x < z-y : 18 | left += 1 19 | elif y-x > z-y : 20 | right -= 1 21 | else : 22 | print("Done with the loop") 23 | return result+1 24 | 25 | if __name__ == '__main__' : 26 | print(sum_of_three([2,5,6,8,10])) 27 | -------------------------------------------------------------------------------- /Arrays/TwoNumbersSum.py: -------------------------------------------------------------------------------- 1 | # program for TWO Number Sum 2 | 3 | # naive approach using two for loops 4 | def twoNumberSum(arr : list, target : int) -> list : 5 | result = list() 6 | for i in range(len(arr)) : 7 | for j in range(i+1, len(arr)) : 8 | if arr[i]+arr[j] == target : 9 | result.append((arr[i],arr[j])) 10 | return result 11 | 12 | # this approach uses the concept of hash table for this problem 13 | def two_number_sum(arr : list, target : int) -> list : 14 | nums = list();result = list() 15 | for el in arr : 16 | if target-el in nums : 17 | result.append((el, target-el)) 18 | else : 19 | nums.append(el) 20 | return result 21 | 22 | # this approach is called as sliding window algorithm and takes O(nlogn) time complexity 23 | def SumOfTwo(arr, target) : 24 | result = list() 25 | arr.sort() 26 | left = 0;right=len(arr)-1 27 | while(left < right) : 28 | if arr[left] + arr[right] == target : 29 | result.append((arr[left], arr[right])) 30 | left+=1;right-=1 31 | elif arr[left] + arr[right] < target : 32 | left+=1 33 | elif arr[left] + arr[right] > target : 34 | right-=1 35 | 36 | return result 37 | 38 | if __name__ == '__main__' : 39 | print(SumOfTwo([3,5,-4,8,11,1,-1,6], 10)) 40 | # -4 -1 1 3 5 6 8 11 -------------------------------------------------------------------------------- /Arrays/TwoSum(Returning index).py: -------------------------------------------------------------------------------- 1 | # Leetcode 2 sum problem 2 | # returning the index of the array 3 | 4 | def twoSum(nums : list, target : int) -> list : 5 | 6 | for i in range(len(nums) - 1) : 7 | for j in range(i+1, len(nums)) : 8 | current_sum = nums[i] + nums[j] 9 | if current_sum == target : 10 | return [i, j] 11 | 12 | return [-1, -1] 13 | 14 | if __name__ == '__main__' : 15 | print(twoSum([2,7,11,15], 9)) -------------------------------------------------------------------------------- /Arrays/UglyNumber.py: -------------------------------------------------------------------------------- 1 | # Leetcode ugly number III 2 | 3 | def nthUglyNumber(n : int, a : int, b : int, c : int) -> int : 4 | smallest_number = min(a,min(b,c)) 5 | 6 | i = smallest_number 7 | 8 | while i <= n : 9 | i+=smallest_number 10 | 11 | return i 12 | 13 | 14 | if __name__ == '__main__' : 15 | print(nthUglyNumber(1000000000,2,217983653,336916467)) -------------------------------------------------------------------------------- /Arrays/Unique.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/Unique.class -------------------------------------------------------------------------------- /Arrays/Unique.java: -------------------------------------------------------------------------------- 1 | /** 2 | 3 | PROBLEM STATEMENT 4 | ----------------- 5 | Implement an algorithm to determine if a string has all unique characters. 6 | 7 | example : 8 | 9 | string = "ankit" => yes 10 | string = "ankita" => no 11 | 12 | Level : medium why ? 13 | timecomplexity = O(n) 14 | 15 | 16 | using a hashtable 17 | 18 | ASCII of A = 65 - 65 is = 0 19 | B = 66 - 65 = 1 20 | c = 2 21 | ... z = 25 22 | 23 | int[] arr = [0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] space complexity = O(26) is constanct so it becomes O(1) 24 | 25 | for each_character in the string : 26 | char ch = each_character.toUpperCase() 27 | 28 | if arr[ascii(character) - 65] == 0 : 29 | arr[ascii(character) - 65] = 1 30 | else : 31 | return False 32 | 33 | */ 34 | 35 | public class Unique { 36 | public static void main(String[] args) { 37 | String str = "priyaa"; 38 | 39 | int[] arr = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; 40 | 41 | boolean flag = true; 42 | 43 | str = str.toUpperCase(); 44 | 45 | for(int i=0;i int : 5 | stack = list();count=0 6 | 7 | for char in string : 8 | if char == 'a' : 9 | if stack and stack[len(stack)-1] == 'b': 10 | count+=1 11 | stack.pop() 12 | else : 13 | stack.append(char) 14 | 15 | return count 16 | 17 | if __name__ == "__main__": 18 | string = "bbaaaaabb" 19 | print(balance_string(string)) 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /Arrays/candy.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def solve_candy(arr : list, k : int) -> int : 4 | 5 | arr.sort() 6 | 7 | mid_element = arr[len(arr)//2-1] if len(arr) %2 == 0 else arr[len(arr)//2] 8 | mid_pos = (len(arr) // 2 - 1) if len(arr) %2 == 0 else len(arr) // 2 9 | 10 | count = 0 11 | 12 | for _ in arr[mid_pos:] : 13 | count+=1 14 | 15 | if count >= k : 16 | return mid_element 17 | 18 | return -1 19 | 20 | 21 | if __name__ == "__main__": 22 | print(solve_candy([26,20,23], 2)) -------------------------------------------------------------------------------- /Arrays/defuse.py: -------------------------------------------------------------------------------- 1 | # defuse the bomb problem leetcode biweekly challenge 2 | 3 | def defuse_bomb(arr : list, k : int) -> None : 4 | res = list() 5 | if k == 0 : 6 | for i in range(len(arr)) : 7 | arr[i] = 0 8 | return arr 9 | 10 | elif k > 0 : 11 | for i in range(len(arr)) : 12 | cum = 0 13 | j = 1;pos=i+1 14 | while j <= k : 15 | if pos == len(arr) : pos=0 16 | cum += arr[pos] 17 | pos+=1 18 | j+=1 19 | res.append(cum) 20 | return res 21 | else : 22 | for i in range(len(arr)) : 23 | cum = 0 24 | j=1;pos=i-1; 25 | while j<=abs(k) : 26 | if pos == -1 : pos = len(arr)-1 27 | cum += arr[pos] 28 | pos-=1 29 | j+=1 30 | 31 | res.append(cum) 32 | 33 | return res 34 | 35 | if __name__ == "__main__": 36 | arr = [2,4,9,3];k=-2 37 | arr = defuse_bomb(arr, k) 38 | print(arr) 39 | -------------------------------------------------------------------------------- /Arrays/equivalent.py: -------------------------------------------------------------------------------- 1 | # program to check if two strings are equivalent 2 | 3 | def check_equivalent(string1 : str, string2 : str) -> bool : 4 | string1 = "".join(string1);string2="".join(string2) 5 | print(string1,string2) 6 | if len(string1) != len(string2) : return False 7 | 8 | 9 | if __name__ == "__main__": 10 | print(check_equivalent(['ab', 'c'], ['a', 'bc'])) 11 | 12 | 13 | -------------------------------------------------------------------------------- /Arrays/fairarray.py: -------------------------------------------------------------------------------- 1 | 2 | # fair array leetcode weekly challenge solution 3 | 4 | def clac_odd_even (arr : list) : 5 | odd = 0;even = 0 6 | 7 | for i in range(len(arr)) : 8 | if i%2 == 0 : 9 | even += arr[i] 10 | else : 11 | odd += arr[i] 12 | 13 | return (odd, even) 14 | 15 | 16 | def fair_array(arr : list) -> int : 17 | count = 0 18 | 19 | for i in range(len(arr)) : 20 | odd, even = clac_odd_even(arr) 21 | 22 | if i%2 == 0 : 23 | if even - arr[i] == odd : 24 | count+=1 25 | 26 | else : 27 | if even == odd-arr[i] : 28 | count+=1 29 | 30 | return count 31 | 32 | 33 | if __name__ == "__main__": 34 | print(fair_array([6,1,7,4,1])) -------------------------------------------------------------------------------- /Arrays/pattern.py: -------------------------------------------------------------------------------- 1 | # program to pring a triangular pattern in python 2 | 3 | def print_pattern(row : int) : 4 | count = 1 5 | for i in range(1, row+1) : 6 | for j in range(1, i+1) : 7 | print(count, end = " ") 8 | count+=1 9 | 10 | print() 11 | 12 | 13 | def pascal_triangle(row : int) : 14 | 15 | pass 16 | 17 | 18 | if __name__ == "__main__": 19 | print_pattern(5) -------------------------------------------------------------------------------- /Arrays/prefix.py: -------------------------------------------------------------------------------- 1 | def findPrefix(s, strings) : 2 | result = list() 3 | 4 | for string in strings : 5 | if s in string.lower() : 6 | result.append(string) 7 | 8 | return result 9 | 10 | if __name__ == "__main__": 11 | print(findPrefix('de', ['Dog', 'Dear', 'Deer'])) -------------------------------------------------------------------------------- /Arrays/removedup.py: -------------------------------------------------------------------------------- 1 | 2 | def remove_duplicates(arr : list) : 3 | has_seen = set() 4 | output = list() 5 | 6 | for el in arr : 7 | if el not in has_seen : 8 | output.append(el) 9 | has_seen.add(el) 10 | 11 | return output 12 | 13 | class IteratorClass (object) : 14 | 15 | def __init__(self) : 16 | self.num = 0 17 | 18 | def __iter__(self) : 19 | self.index = 0 20 | return self 21 | 22 | def __next__(self) : 23 | if self.index <= 10 : 24 | self.index+=1 25 | self.num += 10 26 | return self.num 27 | else : 28 | raise StopIteration 29 | 30 | 31 | 32 | if __name__ == "__main__": 33 | arr = [1,2,3,4,5,1,2,4] 34 | arr = remove_duplicates(arr) 35 | print(arr) 36 | 37 | ob = IteratorClass() 38 | for i in ob : 39 | print(i) 40 | 41 | -------------------------------------------------------------------------------- /Arrays/reverse.py: -------------------------------------------------------------------------------- 1 | # leetcode problem solution of reverse string 2 | 3 | def strip_string(string : str) -> str : 4 | res = " " 5 | i=0 6 | while i < len(string) : 7 | if string[i].isalpha() : 8 | res+=string[i] 9 | elif string[i] == ' ' : 10 | res += " " 11 | j = i 12 | while string[j] == ' ' : j+=1 13 | i = j-1 14 | 15 | i+=1 16 | 17 | return res 18 | 19 | 20 | 21 | def reverse_string(string : str) -> str : 22 | string = strip_string(string) 23 | string = string.split(" ") 24 | string.reverse() 25 | string = " ".join(string) 26 | 27 | return string 28 | 29 | 30 | def reverse_from_end(string : str) -> str : 31 | res = " " 32 | i = len(string) - 1 33 | 34 | while i >= 0 : 35 | 36 | if string[i].isalpha() : 37 | res += string[i] 38 | elif string[i] == " " : 39 | res += " " 40 | j = i 41 | while j>=0 and string[j] == ' ' : j-=1 42 | i = j+1 43 | 44 | i-=1 45 | 46 | return res 47 | 48 | 49 | if __name__ == '__main__' : 50 | print(reverse_string("a good example")) -------------------------------------------------------------------------------- /Arrays/reversestring.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write a function that takes a list of characters and reverses the letters in place 3 | """ 4 | 5 | def reverseCharacters(arr) : 6 | left = 0;right=len(arr)-1 7 | 8 | while left<=right : 9 | arr[left], arr[right] = arr[right], arr[left] 10 | left += 1 11 | right -= 1 12 | 13 | 14 | if __name__ == "__main__": 15 | chars = ['a','b','c','d', 'e'] 16 | reverseCharacters(chars) 17 | print(chars) 18 | -------------------------------------------------------------------------------- /Arrays/reversewords.py: -------------------------------------------------------------------------------- 1 | # program to reverse words (in-place algorithm) 2 | 3 | # function to reverse the words 4 | def reverse_words(string) : 5 | 6 | string.reverse() 7 | 8 | start_pos = 0 9 | 10 | for i in range(len(string)) : 11 | if string[i] == ' ' : 12 | reverse_chars(string, start_pos, i-1) 13 | start_pos=i+1 14 | 15 | reverse_chars(string, start_pos, len(string)-1) 16 | 17 | 18 | # helper function to reverse the characters of a string from a given index to a given index 19 | def reverse_chars(string, start, end) : 20 | while start <= end : 21 | string[start], string[end] = string[end], string[start] 22 | 23 | start+=1 24 | end-=1 25 | 26 | 27 | # driver code 28 | if __name__ == "__main__": 29 | string = ['c','a','k','e',' ','p','o', 'u', 'n', 'd', ' ', 's', 't', 'e', 'a', 'l'] 30 | reverse_words(string) 31 | print("".join(string)) -------------------------------------------------------------------------------- /Arrays/smallestString.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Arrays/smallestString.py -------------------------------------------------------------------------------- /Arrays/wordcloud.py: -------------------------------------------------------------------------------- 1 | # Word cloud data 2 | 3 | 4 | # function to split the string into words 5 | def split_string(string : str) -> list : 6 | 7 | result = list();pos=0 8 | 9 | for index, value in enumerate(string) : 10 | if not value.isalpha() : 11 | result.append(string[pos:index]) 12 | pos = index+1 13 | 14 | result.append(string[pos:]) 15 | return result 16 | 17 | 18 | # function to count the words in dictionary 19 | def word_cloud(string : str) -> dict : 20 | count_dict = dict() 21 | 22 | splitted_string = split_string(string) 23 | 24 | for el in splitted_string : 25 | if el in count_dict : 26 | count_dict[el] += 1 27 | else : 28 | count_dict[el] = 1 29 | 30 | return count_dict 31 | 32 | 33 | 34 | # driver code 35 | if __name__ == "__main__": 36 | print(split_string("ankit kumar")) 37 | print(word_cloud('ankit kumar singh ankit')) 38 | -------------------------------------------------------------------------------- /Arrays/zeromatrix.py: -------------------------------------------------------------------------------- 1 | """ 2 | Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are set to 0 3 | """ 4 | 5 | def printMatrix(arr) : 6 | for rows in arr : 7 | for el in rows : 8 | print(el, end = " : ") 9 | 10 | print() 11 | 12 | return 13 | 14 | def zeroMatrix(arr) : 15 | i = 0 16 | while i < len(arr) : 17 | j = 0 18 | try : 19 | while j < len(arr[i]) : 20 | if arr[i][j] == 0 : 21 | for k in range(len(arr[i])) : 22 | arr[i][k] = 0 23 | 24 | for k in range(len(arr)) : 25 | arr[k][i] = 0 26 | 27 | i+=1 28 | j = i+1 29 | 30 | j+=1 31 | except : 32 | pass 33 | 34 | i+=1 35 | 36 | if __name__ == '__main__' : 37 | arr = [ 38 | [1,0,3], 39 | [4,5,6], 40 | [7,8,9] 41 | ] 42 | #zeroMatrix(arr) 43 | printMatrix(arr) -------------------------------------------------------------------------------- /CodeChef/Atm.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction. 3 | 4 | Input 5 | Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw. 6 | 7 | Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance. 8 | 9 | Output 10 | Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance. 11 | 12 | Example - Successful Transaction 13 | Input: 14 | 30 120.00 15 | 16 | Output: 17 | 89.50 18 | Example - Incorrect Withdrawal Amount (not multiple of 5) 19 | Input: 20 | 42 120.00 21 | 22 | Output: 23 | 120.00 24 | Example - Insufficient Funds 25 | Input: 26 | 300 120.00 27 | 28 | Output: 29 | 120.00 30 | """ 31 | 32 | def withdrawMoney() : 33 | wamount, totalamount = list(map(float, input().split())) 34 | 35 | dispense = wamount + 0.5 36 | 37 | if wamount%5 == 0 and dispense <= totalamount : 38 | return float("{:.3f}".format(totalamount - dispense)) 39 | else : 40 | return float("{:.3f}".format(totalamount)) 41 | 42 | if __name__ == "__main__" : 43 | print(withdrawMoney()) -------------------------------------------------------------------------------- /CodeChef/Enormous.py: -------------------------------------------------------------------------------- 1 | """The purpose of this problem is to verify whether the method you are using to read input data is sufficiently fast to handle problems branded with the enormous Input/Output warning. You are expected to be able to process at least 2.5MB of input data per second at runtime. 2 | 3 | Input 4 | The input begins with two positive integers n k (n, k<=107). The next n lines of input contain one positive integer ti, not greater than 109, each. 5 | 6 | Output 7 | Write a single integer to output, denoting how many integers ti are divisible by k. 8 | 9 | Example 10 | Input: 11 | 7 3 12 | 1 13 | 51 14 | 966369 15 | 7 16 | 9 17 | 999996 18 | 11 19 | 20 | Output: 21 | 4 22 | """ 23 | 24 | if __name__ == "__main__": 25 | n, k = list(map(int, input().split())) 26 | 27 | count = 0 28 | 29 | for _ in range(n) : 30 | sk = int(input()) 31 | 32 | if sk%k == 0 : 33 | count+=1 34 | 35 | print(count) -------------------------------------------------------------------------------- /Data Structures/Arrays/BillDivision.py: -------------------------------------------------------------------------------- 1 | """ 2 | Problem Statement : Bill Division (Source : Hackerrank) 3 | Two friends Anna and Brian, are deciding how to split the bill at a dinner. Each will only pay for the items they consume. Brian gets the check and calculates Anna's portion. You must determine if his calculation is correct. 4 | 5 | For example, assume the bill has the following prices: . Anna declines to eat item which costs . If Brian calculates the bill correctly, Anna will pay . If he includes the cost of , he will calculate . In the second case, he should refund to Anna. 6 | 7 | Function Description 8 | 9 | Complete the bonAppetit function in the editor below. It should print Bon Appetit if the bill is fairly split. Otherwise, it should print the integer amount of money that Brian owes Anna. 10 | 11 | bonAppetit has the following parameter(s): 12 | 13 | bill: an array of integers representing the cost of each item ordered 14 | k: an integer representing the zero-based index of the item Anna doesn't eat 15 | b: the amount of money that Anna contributed to the bill 16 | Input Format 17 | 18 | The first line contains two space-separated integers and , the number of items ordered and the -based index of the item that Anna did not eat. 19 | The second line contains space-separated integers where . 20 | The third line contains an integer, , the amount of money that Brian charged Anna for her share of the bill. 21 | 22 | Constraints 23 | 24 | The amount of money due Anna will always be an integer 25 | Output Format 26 | 27 | If Brian did not overcharge Anna, print Bon Appetit on a new line; otherwise, print the difference (i.e., ) that Brian must refund to Anna. This will always be an integer. 28 | 29 | Sample Input 0 30 | 31 | 4 1 32 | 3 10 2 9 33 | 12 34 | 35 | Sample Output 0 36 | 37 | 5 38 | """ 39 | 40 | # function for the required problem 41 | def bonAppetite(bill : list, k : int, b : int) : 42 | fair_share = 0 43 | 44 | # getting the bill shared by both of them 45 | for i in range(0, len(bill)) : 46 | if i != k : 47 | fair_share += bill[i] 48 | 49 | # checking if both of them paid the same amount 50 | if fair_share//2 == b : 51 | return "Bon Appetit" 52 | 53 | # if anyone of them doesnt pay the same amount 54 | return fair_share//2 - b 55 | 56 | 57 | # main section of the program 58 | if __name__ == '__main__' : 59 | print(bonAppetite([3,10,2,9], 1, 7)) -------------------------------------------------------------------------------- /Data Structures/Arrays/ClassObjects.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class MyClass : 4 | 5 | # class variable 6 | username = "default username" 7 | 8 | def __init__(self, name, email) : 9 | # instance variable 10 | print("MyClass __init__ called") 11 | self.name = name 12 | self.email = email 13 | 14 | def __str__(self) : 15 | return self.username 16 | 17 | class SecondClass : 18 | def __init__(self, name, email) : 19 | print("Second class __init__ called") 20 | self.namelength = len(name) 21 | self.nameemail = len(email) 22 | 23 | 24 | # constructor calls in multiple inheritance in python 25 | class DerivedClass(MyClass, SecondClass) : 26 | 27 | def __init__(self, name, email, password) : 28 | super().__init__(name, email) # calls only the first class passed to it 29 | SecondClass.__init__(self, name, email) # used to call the second class 30 | print("Derived class constructor") 31 | self.__password = password 32 | 33 | def __str__(self) : 34 | return self.name + " " + self.email + " " + self.__password + " " +str(self.namelength )+ " " + str(self.nameemail) 35 | 36 | 37 | if __name__ == '__main__' : 38 | ob = DerivedClass('ankit', 'ankitemail', 'mypassword') 39 | print(ob) 40 | 41 | 42 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Duplicate.py: -------------------------------------------------------------------------------- 1 | # Find the duplicate in an array of N+1 integers. 2 | # Leetcode problem : 287 3 | 4 | # Takes O(n) time complexity and O(n) space complexity 5 | def duplicate(arr) : 6 | seen = list() 7 | 8 | for el in arr : 9 | if el in seen : 10 | return el 11 | else : 12 | seen.append(el) 13 | 14 | return -1 15 | 16 | 17 | # Takes O(n) time complexity and O(1) space complexity 18 | def duplicateNumber(arr) : 19 | slow, fast = arr[0], arr[0] 20 | 21 | slow = arr[slow] 22 | fast = arr[arr[fast]] 23 | 24 | while slow != fast : 25 | slow = arr[slow] 26 | fast = arr[arr[fast]] 27 | 28 | fast = arr[0] 29 | 30 | while slow != fast : 31 | slow = arr[slow] 32 | fast = arr[fast] 33 | 34 | return slow 35 | 36 | 37 | if __name__ == '__main__' : 38 | print(duplicateNumber([1,2,3,4,2])) 39 | print(duplicate([1,2,3,5])) 40 | 41 | -------------------------------------------------------------------------------- /Data Structures/Arrays/HourGlass.py: -------------------------------------------------------------------------------- 1 | """ 2 | Hackerrank Hourglass Solution 3 | """ 4 | 5 | #!/bin/python3 6 | 7 | import math 8 | import os 9 | import random 10 | import re 11 | import sys 12 | 13 | # Complete the hourglassSum function below. 14 | def hourglassSum(arr): 15 | 16 | largest = -float("inf");pos=-1 17 | for i in range(1, len(arr) -1) : 18 | for j in range(1, len(arr[i])-1) : 19 | sum = arr[i][j] + arr[i-1][j] + arr[i-1][j-1] + arr[i-1][j+1] + arr[i+1][j]+arr[i+1][j-1]+arr[i+1][j+1] 20 | if sum > largest : 21 | largest = sum 22 | pos = (i, j) 23 | 24 | return(largest) 25 | 26 | 27 | if __name__ == '__main__': 28 | fptr = open(os.environ['OUTPUT_PATH'], 'w') 29 | 30 | arr = [] 31 | 32 | for _ in range(6): 33 | arr.append(list(map(int, input().rstrip().split()))) 34 | 35 | result = hourglassSum(arr) 36 | 37 | fptr.write(str(result) + '\n') 38 | 39 | fptr.close() 40 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Intersection.py: -------------------------------------------------------------------------------- 1 | 2 | # python program to find the intersection between two arrays 3 | 4 | def intersection_arrays(arr1 : list, arr2: list) : 5 | i=0;j=0; 6 | 7 | result = set() 8 | 9 | while i arr2[j] : 14 | j+=1 15 | 16 | else : 17 | result.add(arr1[i]) 18 | i+=1;j+=1 19 | 20 | return result 21 | 22 | 23 | if __name__ == "__main__": 24 | print(intersection_arrays([1,2,3,4,5], [4,5,6,7,8,9])) 25 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Iterator.py: -------------------------------------------------------------------------------- 1 | 2 | # program to demostrate how iterator in python works 3 | 4 | 5 | class MyIterator : 6 | 7 | def __iter__(self) : 8 | self.num = 0 9 | return self 10 | 11 | 12 | def __next__(self) : 13 | self.num += 1 14 | if self.num <= 10 : 15 | return self.num 16 | 17 | else : 18 | raise StopIteration 19 | 20 | 21 | 22 | 23 | 24 | if __name__ == '__main__' : 25 | ob = MyIterator() 26 | 27 | for i in ob : 28 | print(i) 29 | 30 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Merge.py: -------------------------------------------------------------------------------- 1 | # program to merge to arrays a and b which are in ascending order and the result should be in descending order 2 | 3 | 4 | def merge(arr : list, arr2 : list) : 5 | i, j = 0, 0 6 | result = list() 7 | 8 | while i < len(arr) and j < len(arr2) : 9 | if arr[i] <= arr2[j] : 10 | result.append(arr[i]) 11 | i += 1 12 | 13 | elif arr[i] >= arr2[j] : 14 | result.append(arr2[j]) 15 | j += 1 16 | 17 | 18 | if i == len(arr) : 19 | result.append(arr2[j]) 20 | j += 1 21 | else : 22 | result.append(arr[i]) 23 | i += 1 24 | 25 | return result 26 | 27 | 28 | if __name__ == '__main__' : 29 | print(merge([1,3,5,7,9],[2,4,6,8])) -------------------------------------------------------------------------------- /Data Structures/Arrays/MinMax.py: -------------------------------------------------------------------------------- 1 | 2 | def min_mix (arr) : 3 | min = arr[0];max=arr[0] 4 | 5 | for el in arr : 6 | if el < min : 7 | min = el 8 | if el > max : 9 | max = el 10 | 11 | return (min, max) 12 | 13 | 14 | 15 | if __name__ == '__main__' : 16 | print(min_mix([1,2,3,4,5])) -------------------------------------------------------------------------------- /Data Structures/Arrays/Missing.py: -------------------------------------------------------------------------------- 1 | # Find the Missing and Repeating Number 2 | 3 | def missingNumber(arr) : 4 | 5 | visited = [0 for _ in range(len(arr)+1)] 6 | 7 | repeated_element = -1 8 | 9 | for el in arr : 10 | if visited[el] == 0 : 11 | visited[el] = el 12 | else : 13 | repeated_element = el 14 | 15 | print(visited) 16 | return [repeated_element, abs(sum(visited) - sum([i for i in range(1,len(arr)+1)]))] 17 | 18 | 19 | if __name__ == '__main__' : 20 | print(missingNumber([1,2,3,4,1,5,7])) -------------------------------------------------------------------------------- /Data Structures/Arrays/Move.py: -------------------------------------------------------------------------------- 1 | # python program to move a given element to the end of the array 2 | 3 | def move_to_end(arr : list, target : int) : 4 | left = 0;right=len(arr)-1 5 | 6 | while left < right : 7 | 8 | while arr[right] == target : right-=1 9 | 10 | if arr[left] == target : 11 | arr[left], arr[right] = arr[right], arr[left] 12 | left+=1 13 | right-=1 14 | 15 | left+=1 16 | 17 | 18 | if __name__ == '__main__' : 19 | arr = [2,1,2,2,2,3,4,2] 20 | 21 | move_to_end(arr, 2) 22 | 23 | print(arr) 24 | -------------------------------------------------------------------------------- /Data Structures/Arrays/MoveNegative.py: -------------------------------------------------------------------------------- 1 | 2 | # python program to move all the negative elements to one side of the array 3 | 4 | def move_to_right(arr: list) : 5 | left = 0;right = len(arr) - 1 6 | 7 | while left <= right : 8 | if arr[left] < 0 : 9 | arr[left], arr[right] = arr[right], arr[left] 10 | right-=1 11 | else : 12 | left+=1 13 | 14 | 15 | if __name__ == "__main__": 16 | arr = [1,2,-1,3,4,-5,6,-7,23,-56] 17 | move_to_right(arr) 18 | print(arr) -------------------------------------------------------------------------------- /Data Structures/Arrays/Palindrome.py: -------------------------------------------------------------------------------- 1 | # program to check if the given number is palindrome or not 2 | 3 | def ispalindrome(num : int) -> bool : 4 | new_num = 0;temp = num 5 | 6 | while temp != 0 : 7 | new_num = new_num*10 + temp%10 8 | temp //= 10 9 | 10 | return new_num == num 11 | 12 | 13 | if __name__ == '__main__' : 14 | print(ispalindrome(1111)) 15 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Reverse.py: -------------------------------------------------------------------------------- 1 | # Program to reverse an array 2 | 3 | def reverseArray(arr : list) : 4 | 5 | for i in range(len(arr) // 2) : 6 | arr[i], arr[len(arr)-1-i] = arr[len(arr)-1-i], arr[i] 7 | 8 | 9 | if __name__ == "__main__": 10 | arr = [1,2,3,4,5,6,7] 11 | reverseArray(arr) 12 | print(arr) 13 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Solution.py: -------------------------------------------------------------------------------- 1 | # Problem statement : Moving all the instances of a given element to the end of the array 2 | 3 | def moveToEnd(arr : list, num : int) : 4 | 5 | left = 0;right = len(arr) - 1 6 | 7 | while(left < right) : 8 | while arr[right] == num : 9 | right -= 1 10 | 11 | if arr[left] == num : 12 | arr[left], arr[right] = arr[right], arr[left] 13 | 14 | left+=1 15 | 16 | return arr 17 | 18 | 19 | if __name__ == '__main__' : 20 | print(moveToEnd([1,2,2,2,3,4,5,2,2,4], 2)) -------------------------------------------------------------------------------- /Data Structures/Arrays/SortZeroOne.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sort an array of 0s, 1s and 2s 3 | Easy Accuracy: 48.12% Submissions: 100k+ Points: 2 4 | Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order. 5 | 6 | Input: 7 | The first line contains an integer 'T' denoting the total number of test cases. Then T testcases follow. Each testcases contains two lines of input. The first line denotes the size of the array N. The second lines contains the elements of the array A separated by spaces. 8 | 9 | Output: 10 | For each testcase, print the sorted array. 11 | 12 | Constraints: 13 | 1 <= T <= 500 14 | 1 <= N <= 106 15 | 0 <= Ai <= 2 16 | 17 | Example: 18 | Input : 19 | 2 20 | 5 21 | 0 2 1 2 0 22 | 3 23 | 0 1 0 24 | 25 | Output: 26 | 0 0 1 2 2 27 | 0 0 1 28 | 29 | Explanation: 30 | Testcase 1: After segragating the 0s, 1s and 2s, we have 0 0 1 2 2 which shown in the output. 31 | """ 32 | 33 | def sortOneTwo(arr : list) : 34 | left = 0;mid=0;right=len(arr)-1 35 | 36 | while(mid <= right) : 37 | if arr[mid] == 0 : 38 | arr[mid], arr[left] = arr[left], arr[mid] 39 | left+=1;mid+=1 40 | elif arr[mid] == 1 : 41 | mid+=1 42 | else : 43 | arr[mid], arr[right] = arr[right], arr[mid] 44 | right-=1 45 | 46 | 47 | # main function to run the code 48 | if __name__ == "__main__": 49 | t = int(input()) 50 | 51 | for _ in range(t) : 52 | n = int(input()) 53 | arr = list(map(int, input().split())) 54 | sortOneTwo(arr) 55 | for el in arr : 56 | print(el, end = " ") 57 | 58 | print() -------------------------------------------------------------------------------- /Data Structures/Arrays/Sorted.py: -------------------------------------------------------------------------------- 1 | 2 | def sorted_elements(arr : list) : 3 | result = list() 4 | 5 | for el in arr : 6 | if el not in result : 7 | result.append(el) 8 | 9 | result.sort() 10 | return result 11 | 12 | 13 | if __name__ == '__main__' : 14 | result = sorted_elements([7,6,7,3,28,7]) 15 | 16 | for el in result : 17 | print(el, end = " ") -------------------------------------------------------------------------------- /Data Structures/Arrays/SortingColors.py: -------------------------------------------------------------------------------- 1 | """ 2 | 75. Sort Colors 3 | Medium 4 | 5 | 4110 6 | 7 | 240 8 | 9 | Add to List 10 | 11 | Share 12 | Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue. 13 | 14 | Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. 15 | 16 | Follow up: 17 | 18 | Could you solve this problem without using the library's sort function? 19 | Could you come up with a one-pass algorithm using only O(1) constant space? 20 | 21 | 22 | Example 1: 23 | 24 | Input: nums = [2,0,2,1,1,0] 25 | Output: [0,0,1,1,2,2] 26 | Example 2: 27 | 28 | Input: nums = [2,0,1] 29 | Output: [0,1,2] 30 | Example 3: 31 | 32 | Input: nums = [0] 33 | Output: [0] 34 | Example 4: 35 | 36 | Input: nums = [1] 37 | Output: [1] 38 | 39 | 40 | Constraints: 41 | 42 | n == nums.length 43 | 1 <= n <= 300 44 | nums[i] is 0, 1, or 2. 45 | """ 46 | 47 | def sortArray(arr) : 48 | 49 | left = 0;mid = 0 50 | right = len(arr) - 1 51 | 52 | while mid <= right : 53 | el = arr[mid] 54 | 55 | if el == 0 : 56 | arr[left], arr[mid] = arr[mid], arr[left] 57 | left+=1 58 | mid+=1 59 | 60 | elif el == 1 : 61 | mid+=1 62 | 63 | elif el == 2 : 64 | arr[mid], arr[right] = arr[right], arr[mid] 65 | right -= 1 66 | 67 | 68 | if __name__ == '__main__' : 69 | # an example array 70 | arr = [1,2,0,0,1,2,0,0,1,2,2,0,0] 71 | 72 | # sorting the array 73 | sortArray(arr) 74 | print(arr) 75 | -------------------------------------------------------------------------------- /Data Structures/Arrays/SortingZero.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def sortingZero(arr: list) : 4 | left = 0 ;mid = 0; right = len(arr) - 1 5 | 6 | while mid < right: 7 | if arr[mid] == 0 : 8 | arr[left], arr[mid] = arr[mid], arr[left] 9 | left+=1;mid+=1 10 | elif arr[mid] == 1: 11 | mid+=1 12 | else : 13 | arr[mid], arr[right] = arr[right], arr[mid] 14 | right-=1 15 | else: 16 | pass 17 | 18 | 19 | if __name__ == "__main__": 20 | arr = [1,0,2,1,1,0,0,1,2,2,0] 21 | sortingZero(arr) 22 | print(arr) 23 | -------------------------------------------------------------------------------- /Data Structures/Arrays/Spiral.py: -------------------------------------------------------------------------------- 1 | 2 | def spiralTraversal(arr) : 3 | result = list() 4 | rowStart, rowEnd = 0, len(arr) - 1 5 | colStart, colEnd = 0, len(arr[0]) - 1 6 | 7 | while rowStart <= rowEnd and colStart <= colEnd : 8 | 9 | for col in range(colStart, colEnd+1) : 10 | result.append(arr[rowStart][col]) 11 | 12 | for col in range(rowEnd, colEnd+1) : 13 | result.append(arr[col][colEnd]) 14 | 15 | for col in range(colEnd, rowStart) : 16 | result.append(arr[rowEnd][col]) 17 | 18 | for col in range(rowEnd, rowStart+1) : 19 | result.append(arr[col][colStart]) 20 | 21 | rowStart += 1 22 | rowEnd -= 1 23 | colStart += 1 24 | colEnd -= 1 25 | 26 | return result 27 | 28 | 29 | if __name__ == '__main__' : 30 | spiralTraversal([[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]) 31 | -------------------------------------------------------------------------------- /Data Structures/Arrays/StringCompression.py: -------------------------------------------------------------------------------- 1 | 2 | # program : string compression 3 | """ 4 | Implement a method to perform basic string compression using the counts of characters. 5 | 6 | """ 7 | 8 | def compressString(string : str) -> dict : 9 | i = 0 10 | result = "" 11 | while i < len(string) : 12 | count = 1 13 | try : 14 | while string[i+1] == string[i] : 15 | i+=1 16 | count+=1 17 | except : 18 | pass 19 | 20 | result += "{}{}".format(string[i], count) 21 | i+=1 22 | 23 | return result 24 | 25 | if __name__ == '__main__' : 26 | string = input("Enter a string : ") 27 | 28 | print(compressString(string)) 29 | 30 | -------------------------------------------------------------------------------- /Data Structures/Arrays/StringMethods.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | # function to determine if a string has all unique characters. 4 | def isUnique(string) : 5 | 6 | # using brute force 7 | # for i in range(len(string)-1) : 8 | # for j in range(i+1, len(string)) : 9 | # if string[i] == string[j] : 10 | # return False 11 | 12 | # using sorting (optimised solution) 13 | # string = list(string) 14 | # string.sort() 15 | 16 | # for i in range(len(string)-1) : 17 | # if string[i] == string[i+1] : 18 | # return False 19 | 20 | # using hashtables 21 | string = string.upper() 22 | 23 | table = [0 for x in range(26)] 24 | 25 | for el in string : 26 | if table[ord(el) - 65] == 1 : 27 | return False 28 | else : 29 | table[ord(el) - 65] = 1 30 | 31 | return True 32 | 33 | 34 | if __name__ == '__main__' : 35 | print(isUnique("abcdefghijklmnopqrstuvwxyza")) -------------------------------------------------------------------------------- /Data Structures/Arrays/Symmetric.py: -------------------------------------------------------------------------------- 1 | # program to check if the given matrix is symmetric 2 | # a matrix is said to be symmetric if A = A` 3 | 4 | import math 5 | 6 | def isSymmetric(arr) -> bool : 7 | 8 | for i in range(len(arr)) : 9 | for j in range(len(arr[i])) : 10 | if arr[i][j] != arr[len(arr[i])-i-1][j] : 11 | return False 12 | return True 13 | 14 | 15 | if __name__ == '__main__' : 16 | print(isSymmetric([[8],[8],[8]])) 17 | 18 | 19 | """ 20 | [ 00, 01, 02, 03 ] 21 | [ 10, 11, 12, 13 ] 22 | [ 20, 21, 22, 23 ] 23 | [ 30, 31, 32, 33 ] 24 | 25 | """ -------------------------------------------------------------------------------- /Data Structures/Arrays/ThreeNumber.py: -------------------------------------------------------------------------------- 1 | # Three number sum 2 | 3 | def threeSumProblem(arr: list, target: int) : 4 | arr.sort() 5 | result = list() 6 | 7 | for i in range(0, len(arr) - 2) : 8 | left = i+1;right=len(arr)-1 9 | 10 | while left < right : 11 | curren_sum = arr[i] + arr[left] + arr[right] 12 | 13 | if curren_sum == target : 14 | result.append([arr[i], arr[left], arr[right]]) 15 | left+=1 16 | right-=1 17 | elif curren_sum < target : 18 | left+=1 19 | else : 20 | right -= 1 21 | 22 | return result 23 | 24 | 25 | 26 | if __name__ == '__main__' : 27 | print(threeSumProblem([12,3,1,2,-6,5,-8,6], 0)) -------------------------------------------------------------------------------- /Data Structures/Arrays/TwoSum.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Program to solve the problem of two sum from leetcode 4 | """ 5 | 6 | def twoSum(arr : list, target : int) : 7 | arr.sort() 8 | result = list() 9 | left = 0;right=len(arr) - 1 10 | 11 | while left < right : 12 | current_sum = arr[left] + arr[right] 13 | if current_sum < target : 14 | left+=1 15 | elif current_sum > target : 16 | right-=1 17 | 18 | else : 19 | result.extend([arr[left], arr[right]]) 20 | break 21 | 22 | return result 23 | 24 | 25 | 26 | if __name__ == '__main__' : 27 | print(twoSum([-4,-1,1,3,5,6,8,11], 13)) -------------------------------------------------------------------------------- /Data Structures/Arrays/Union.py: -------------------------------------------------------------------------------- 1 | 2 | # python program to find the union of two sorted arrays 3 | 4 | def union_of_arrays(arr1: list, arr2: list) : 5 | i=0;j=0 6 | result = set() 7 | while i= arr2[j] : 12 | result.add(arr2[j]) 13 | j+=1 14 | 15 | if i == len(arr1) : 16 | while j < len(arr2) : 17 | result.add(arr2[j]) 18 | j+=1 19 | else: 20 | while i < len(arr1) : 21 | result.add(arr1[i]) 22 | i+=1 23 | 24 | return result 25 | 26 | 27 | 28 | if __name__ == "__main__": 29 | print(union_of_arrays([1,2,3,4,5], [5,6,7,8])) 30 | -------------------------------------------------------------------------------- /Data Structures/Arrays/countpairs.py: -------------------------------------------------------------------------------- 1 | # given an array with n integers and an integer k, find the numbers of pairs of elements in the array whose sum is equal to k 2 | 3 | def find_pairs(arr : list, target : int) : 4 | arr.sort() 5 | left = 0;right = len(arr) - 1 6 | result = list() 7 | 8 | while left < right : 9 | current_sum = arr[left] + arr[right] 10 | 11 | if current_sum == target : 12 | result.append((left, right)) 13 | left+=1 14 | elif current_sum < target : 15 | left+=1 16 | else : 17 | right-=1 18 | 19 | return result 20 | 21 | 22 | if __name__ == '__main__' : 23 | arr = [1,5,7,1] 24 | res = find_pairs(arr, 6) 25 | print(len(res)) -------------------------------------------------------------------------------- /Data Structures/Arrays/findmissing.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python program to find the smallest positive number missing from the array 3 | """ 4 | 5 | def find_missing(arr : list) : 6 | 7 | has_seen = list() 8 | 9 | for el in arr : 10 | if el >= 0 : 11 | has_seen.append(el) 12 | 13 | 14 | for i in range(len(has_seen)-1) : 15 | if has_seen[i+1]-has_seen[i] != 1 : 16 | return has_seen[i+1] - has_seen[i] 17 | 18 | return has_seen[len(has_seen)-1] + 1 19 | 20 | 21 | 22 | 23 | if __name__ == "__main__": 24 | print(find_missing([1,2,3,4,5])) 25 | -------------------------------------------------------------------------------- /Data Structures/Arrays/jumps.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Minimum number of jumps 4 | ----------------------- 5 | Given an array of integers where each element represents the max number of steps that can be made forward from that element. 6 | Write a function to return the minimum number of jumps to reach the end of the array (starting from the first element). if an 7 | element is 0, then cannot move through that element. 8 | 9 | """ 10 | 11 | def jump(arr : list) : 12 | 13 | i = 0;step_count = 0 14 | 15 | if len(arr) <= 1 : 16 | return 0 17 | 18 | while i < len(arr) : 19 | 20 | if i >= len(arr) - 1 : 21 | return step_count 22 | else : 23 | if arr[i] != 0 : 24 | step_count += 1 25 | 26 | if arr[i] == 0 : 27 | i += 1 28 | else : 29 | i += arr[i] 30 | 31 | return step_count 32 | 33 | 34 | if __name__ == '__main__' : 35 | print(jump([1,3,5,8,9,2,6,7,6,8,9])) 36 | 37 | 38 | -------------------------------------------------------------------------------- /Data Structures/Arrays/kadane.py: -------------------------------------------------------------------------------- 1 | # kadanes' algorithms 2 | 3 | def max_contiguos_sum(arr : list) : 4 | sum_so_far = -9999;current_sum = 0 5 | 6 | for el in arr : 7 | current_sum+=el 8 | 9 | if current_sum > sum_so_far : 10 | sum_so_far = current_sum 11 | 12 | if current_sum < 0 : 13 | current_sum = 0 14 | 15 | return sum_so_far 16 | 17 | 18 | if __name__ == "__main__": 19 | print(max_contiguos_sum([-1,-2,-3,-4])) 20 | -------------------------------------------------------------------------------- /Data Structures/Arrays/kadanes.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Kadane's algorithm 4 | to find the sub array with maximum sum 5 | 6 | """ 7 | 8 | 9 | def kadane_algorithm(arr : list) : 10 | sum_so_far = -9999; current_sum = 0 11 | 12 | for i in range(len(arr)) : 13 | current_sum += arr[i] 14 | 15 | if current_sum > sum_so_far : 16 | sum_so_far = current_sum 17 | 18 | if current_sum < 0 : 19 | current_sum = 0 20 | 21 | return sum_so_far 22 | 23 | if __name__ == "__main__": 24 | print(kadane_algorithm([-1,-2,-3,-4])) 25 | -------------------------------------------------------------------------------- /Data Structures/Arrays/kmaxmin.py: -------------------------------------------------------------------------------- 1 | # find the kth min and max element of an array given that all the elements of the array are distinct 2 | # expected complexity : O(n) 3 | 4 | def kth_min_max(arr: list, k: int) : 5 | arr.sort() 6 | print(arr) 7 | return (arr[k-1], arr[len(arr)-k]) 8 | 9 | 10 | if __name__ == "__main__": 11 | print(kth_min_max([7,10,4,20,15], 4)) 12 | 13 | -------------------------------------------------------------------------------- /Data Structures/Arrays/lonely.py: -------------------------------------------------------------------------------- 1 | # lonely solution from geeksforgeeks 2 | 3 | from collections import Counter 4 | 5 | def get_lonely(arr : list, k : int) : 6 | 7 | counter = Counter(arr) 8 | 9 | 10 | for key, value in counter.items() : 11 | if value != k : 12 | return key 13 | 14 | return -1 15 | 16 | 17 | if __name__ == '__main__' : 18 | print(get_lonely([1 ,8 ,7 ,2 ,1, 7 ,1 ,8 ,7,8], 3)) 19 | -------------------------------------------------------------------------------- /Data Structures/Arrays/mergetwo.py: -------------------------------------------------------------------------------- 1 | 2 | # merge without extra space 3 | 4 | def merge_two(arr1 : list, arr2 : list) : 5 | 6 | i = 0;j = 0 7 | 8 | while i < len(arr1) and j < len(arr2) : 9 | if arr1[i] >= arr2[j] : 10 | arr1[i], arr2[j] = arr2[j], arr1[i] 11 | arr2.sort() 12 | 13 | i+=1 14 | 15 | 16 | for el in arr2 : 17 | arr1.append(el) 18 | 19 | 20 | if __name__ == '__main__' : 21 | arr1 = [1,3,5,7,9] 22 | arr2 = [2,4,6,8,10] 23 | 24 | merge_two(arr1, arr2) 25 | 26 | print(arr1) 27 | 28 | 29 | -------------------------------------------------------------------------------- /Data Structures/Arrays/monotonic.py: -------------------------------------------------------------------------------- 1 | 2 | # python program to check whether a given array is monotonic of not 3 | 4 | def changeDirection(direction, previous_num, current_num): 5 | difference = current_num - previous_num 6 | if direction > 0 : 7 | return difference < 0 8 | return difference > 0 9 | 10 | # actual function thats going to check 11 | def is_monotic(arr) : 12 | 13 | if len(arr) <= 2 : 14 | return True 15 | 16 | 17 | direction = arr[1] - arr[0] 18 | 19 | for i in range(2, len(arr)) : 20 | if direction == 0 : 21 | direction = arr[i] - arr[i-1] 22 | continue 23 | 24 | if changeDirection(direction, arr[i-1], arr[i]) : 25 | return True 26 | 27 | return False 28 | 29 | 30 | 31 | if __name__ == '__main__' : 32 | print(is_monotic([-1,-5,-10,-1100,-1100, -1101, -1102, -9001, 0, 23])) 33 | print(is_monotic([1,2,3,4,5])) -------------------------------------------------------------------------------- /Data Structures/Arrays/oneaway.py: -------------------------------------------------------------------------------- 1 | 2 | # problem name : one away 3 | """ 4 | There are three types of edits that can be performed on trsings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away 5 | """ 6 | 7 | def oneAway(string, string2) : 8 | 9 | if len(string) - len(string2) >= 2 : 10 | return False 11 | 12 | count = 0 13 | for el in string : 14 | if el not in string2 : 15 | count+=1 16 | 17 | if count > 1 : 18 | return False 19 | 20 | return True 21 | 22 | 23 | if __name__ == '__main__' : 24 | print(oneAway('pales', 'pale')) 25 | -------------------------------------------------------------------------------- /Data Structures/Arrays/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | """ 2 | Geeks for geeks array problem : Write a program to remove duplicates from a sorted array 3 | """ 4 | 5 | 6 | def remove_duplicates(arr: list) : 7 | res = set() 8 | 9 | for el in arr : 10 | res.add(el) 11 | 12 | return list(res) 13 | 14 | 15 | def find_duplicates(arr : list) : 16 | result = list() 17 | 18 | for el in arr : 19 | if el not in result : 20 | result.append(el) # append, insert and extend 21 | 22 | return result 23 | 24 | 25 | if __name__ == '__main__' : 26 | print(find_duplicates([1,1,2,2,3,3,4,5])) -------------------------------------------------------------------------------- /Data Structures/Arrays/reversearray.py: -------------------------------------------------------------------------------- 1 | 2 | def reverse_array(arr: list) : 3 | left = 0;right = len(arr) - 1 4 | 5 | while left<=right : 6 | arr[left], arr[right] = arr[right], arr[left] 7 | left+=1 8 | right-=1 9 | 10 | 11 | if __name__ == '__main__' : 12 | arr = [1,2,3,4,5] 13 | reverse_array(arr) 14 | print(arr) -------------------------------------------------------------------------------- /Data Structures/Arrays/reverseingroups.py: -------------------------------------------------------------------------------- 1 | """ 2 | Python program to reverse array in groups 3 | 4 | """ 5 | import math 6 | 7 | # function to reverse the array in groups 8 | def reverse_in_groups(arr : list, start : int, end : int) : 9 | 10 | while start < end : 11 | arr[start], arr[end] = arr[end], arr[start] 12 | start+=1;end-=1 13 | 14 | 15 | 16 | # main driver of the program for this problem statement 17 | if __name__ == '__main__' : 18 | k = int(input("Enter the value of number of groups : ")) 19 | 20 | arr = [1,2,3,4,5,6,7] 21 | 22 | start = 0 23 | end = k-1 24 | 25 | if len(arr) % k == 0 : 26 | print("inside here") 27 | for _ in range(len(arr) // k) : 28 | reverse_in_groups(arr, start, end) 29 | start = start+k 30 | end = end+k 31 | 32 | else : 33 | print("entered here") 34 | for _ in range(len(arr) // k) : 35 | reverse_in_groups(arr, start, end) 36 | start = start+k 37 | end = end+k 38 | 39 | reverse_in_groups(arr, start, len(arr)-1) 40 | 41 | print(arr) 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /Data Structures/Arrays/rotate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Cyclically rotate an array by one 3 | --------------------------------- 4 | Given an array, cyclically rotate an array by one 5 | """ 6 | 7 | def rotate_by_one(arr : list) : 8 | 9 | i = len(arr) - 1 10 | temp = arr[i] 11 | while i>0 : 12 | arr[i] = arr[i-1] 13 | i-=1 14 | 15 | arr[i] = temp 16 | 17 | 18 | if __name__ == "__main__": 19 | arr = [9,8,7,6,4,2,1,3] 20 | rotate_by_one(arr) 21 | print(arr) 22 | 23 | -------------------------------------------------------------------------------- /Data Structures/Arrays/smallest.py: -------------------------------------------------------------------------------- 1 | 2 | # python program to find the smallest difference among two ararys 3 | 4 | def smallest_difference(arr1 : list, arr2: list) : 5 | arr1.sort() 6 | arr2.sort() 7 | 8 | i = 0;j = 0; 9 | smallest_diff = float("inf") 10 | result = [arr1[0], arr2[0]] 11 | while i < len(arr1) and j < len(arr2) : 12 | difference = arr1[i] - arr2[j] 13 | if arr1[i] < arr2[j] : 14 | i+=1 15 | elif arr1[i] > arr2[j] : 16 | j+=1 17 | else : 18 | return [arr1[i], arr2[j]] 19 | 20 | if difference < smallest_diff : 21 | result = [arr1[i-1], arr2[j-1]] 22 | 23 | return result 24 | 25 | 26 | if __name__ == '__main__' : 27 | print(smallest_difference([-1,5,10,20,28,3], [26,134,135,15,17])) -------------------------------------------------------------------------------- /Data Structures/Arrays/smallestDiv.py: -------------------------------------------------------------------------------- 1 | 2 | def compute_lcm(x, y): 3 | 4 | # choose the greater number 5 | if x > y: 6 | greater = x 7 | else: 8 | greater = y 9 | 10 | while(True): 11 | if((greater % x == 0) and (greater % y == 0)): 12 | lcm = greater 13 | break 14 | greater += 1 15 | 16 | return lcm 17 | 18 | def smallestDivNumber(num) : 19 | lcm = compute_lcm(1,2) 20 | 21 | for i in range(3, num+1) : 22 | lcm = compute_lcm(lcm, i) 23 | 24 | return lcm 25 | 26 | 27 | 28 | if __name__ == '__main__' : 29 | print(smallestDivNumber(3)) -------------------------------------------------------------------------------- /Data Structures/Arrays/word.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import Counter 3 | 4 | def word_frequecy(words : str) : 5 | 6 | counter = dict() 7 | 8 | for word in words : 9 | if word in counter.keys() : 10 | counter[word] += 1 11 | else : 12 | counter[word] = 1 13 | 14 | for key, value in counter.items() : 15 | if value > 1 : 16 | print("{} {}".format(key, value)) 17 | else : 18 | print(key) 19 | 20 | 21 | if __name__ == '__main__' : 22 | word_frequecy(["code", "while", "code"]) -------------------------------------------------------------------------------- /Data Structures/Java/Factorial.java: -------------------------------------------------------------------------------- 1 | package factorial; 2 | 3 | public class Factorial { 4 | 5 | public long calculateFactorial(long num) { 6 | if (num <= 1) 7 | return num; 8 | 9 | return num*calculateFactorial(num-1); 10 | } 11 | 12 | } 13 | 14 | -------------------------------------------------------------------------------- /Data Structures/Java/HelloWorld.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | public class HelloWorld { 4 | public static void main(String[] args) { 5 | System.out.println("hello world"); 6 | } 7 | } -------------------------------------------------------------------------------- /Data Structures/Java/Sample.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Data Structures/Java/Sample.class -------------------------------------------------------------------------------- /Data Structures/Java/Sample.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * POINTS TO BE NOTED 4 | * 1. There can't be more than one public class in a file 5 | * 2. If there is a public class in the file then the file name must match the class name 6 | * 3. Static members are only accessible by static methods 7 | * 8 | * CONTROL FLOW 9 | * 1. if statements 10 | * 2. if - else or if else if ladder 11 | * 3. switch 12 | * 13 | * 14 | * 1. Program to find the min and max in a given array, using a single loop (15mins) 15 | * 2. Program to nth smallest number in an array (1hr) 16 | * 17 | */ 18 | 19 | 20 | 21 | 22 | 23 | import java.util.Scanner; 24 | import java.util.Arrays; 25 | import factorial.Factorial; 26 | 27 | public class Sample { 28 | 29 | static Scanner sc = new Scanner(System.in); 30 | 31 | public static void main(String[] args) { 32 | Factorial ob = new Factorial(); 33 | System.out.println("Factorial of 5 = " + ob.calculateFactorial(5)); 34 | } 35 | 36 | } 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /Data Structures/Java/factorial/Factorial.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Data Structures/Java/factorial/Factorial.class -------------------------------------------------------------------------------- /Data Structures/Java/world/HelloWorld.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Data Structures/Java/world/HelloWorld.class -------------------------------------------------------------------------------- /Data Structures/Queue/Printermanagement: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node { 6 | int data; 7 | Node* next = NULL; 8 | }; 9 | 10 | struct Queue { 11 | Node *front= NULL, *rear = NULL; 12 | void enQueue(int x) 13 | { 14 | 15 | Node* temp = new Node; 16 | temp->data = x; 17 | if (rear == NULL) { 18 | front = rear = temp; 19 | return; 20 | } 21 | rear->next = temp; 22 | rear = temp; 23 | } 24 | 25 | void deQueue() 26 | { 27 | if (front == NULL) 28 | return; 29 | 30 | Node* temp = front; 31 | front = front->next; 32 | if (front == NULL) 33 | rear = NULL; 34 | 35 | free(temp); 36 | } 37 | }; 38 | 39 | void display(Node * p) 40 | { 41 | 42 | while(p!=NULL) 43 | { 44 | printf("Printing the document of person with user id = %d\n",p->data); 45 | p=p->next; 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | 52 | Queue q; 53 | int x; 54 | int choice; 55 | do{ 56 | printf("enter your id (integer)\n"); 57 | scanf("%d",&x); 58 | q.enQueue(x); 59 | printf("\nDo you want to use the printer?1: YES \n"); 60 | scanf("%d",&choice); 61 | }while(1==choice); 62 | 63 | display((q.front)); 64 | } 65 | -------------------------------------------------------------------------------- /Data Structures/Queues/CreateQueue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Data Structures/Queues/CreateQueue.class -------------------------------------------------------------------------------- /Data Structures/Queues/Queue.java: -------------------------------------------------------------------------------- 1 | class CreateQueue { 2 | 3 | private int[] arr; 4 | private int front, rear; 5 | 6 | public CreateQueue() 7 | { 8 | this.arr = new int[5]; 9 | this.front = this.rear = -1; 10 | } 11 | 12 | public void insert(int sk) 13 | { 14 | if(this.front == -1 && this.rear == -1) 15 | { 16 | this.front = this.rear = 0; 17 | } 18 | 19 | // overflow condition for the queue 20 | if(this.rear == this.arr.length) 21 | { 22 | System.out.println("Queue overflow"); 23 | return; 24 | } 25 | 26 | // when the queue is empty or has space in it 27 | this.arr[rear++] = sk; 28 | 29 | } 30 | 31 | public void traverse() 32 | { 33 | if(this.front==-1) { 34 | System.out.println("Queue underflow"); 35 | return; 36 | } 37 | for(int i = this.front;i int : 4 | fact = 1 5 | for i in range(2, num+1) : 6 | fact*=i 7 | 8 | return fact 9 | 10 | 11 | if __name__ == "__main__": 12 | mylist = [1,2,3,4,5] 13 | for el in mylist : 14 | print("Factorial of {} = {}".format(el, factorial(el)), end="\r\n") 15 | 16 | for el, index in enumerate(mylist) : 17 | print(el, index) -------------------------------------------------------------------------------- /Data Structures/Trees/tree.py: -------------------------------------------------------------------------------- 1 | # python program to implement tree 2 | 3 | class Node : 4 | def __init__(self, sk) : 5 | self.val = sk 6 | self.right = None 7 | self.left = None 8 | 9 | 10 | # class for creating and traversing a tree 11 | class Tree : 12 | 13 | # constructor for the class 14 | def __init__(self) : 15 | self.root = None 16 | 17 | 18 | # method to insert a node into the binary tree 19 | def insert(self, sk) : 20 | if self.root is None : 21 | self.root = Node(sk) 22 | return 23 | 24 | queue = list() 25 | queue.append(self.root) 26 | 27 | while queue : 28 | temp = queue.pop(0) 29 | 30 | if temp.left is None : 31 | temp.left = Node(sk) 32 | break 33 | else : 34 | queue.append(temp.left) 35 | 36 | if temp.right is None : 37 | temp.right = Node(sk) 38 | break 39 | else : 40 | queue.append(temp.right) 41 | 42 | # method to get the root of the tree 43 | def get_root(self) : 44 | return self.root 45 | 46 | 47 | # method to traverse the entire tree (in order traversal) 48 | def traverse(self, root) : 49 | if not root : 50 | return 51 | 52 | self.traverse(root.left) 53 | print(root.val, end = " ") 54 | self.traverse(root.right) 55 | 56 | 57 | # method to search a node in the tree 58 | def search(self, root, sk) : 59 | pass 60 | 61 | # method to delete a node from the tree 62 | """ 63 | Algorithm : 64 | 1. Starting at root, find the deepest and the rightmost node in the binary tree and node which we want to delete 65 | 2. Replace the deepest rightmost node's data with the node to be deleted 66 | 3. Then delete the deepest rightmost node 67 | """ 68 | def delete(self) : 69 | pass 70 | 71 | 72 | if __name__ == "__main__": 73 | tree = Tree() 74 | tree.insert(1) 75 | tree.insert(2) 76 | tree.insert(3) 77 | tree.traverse(tree.get_root()) 78 | search = tree.search(tree.get_root(),3) 79 | 80 | from array import * 81 | myarray = array('i', [1,2,3]) 82 | print(myarray) -------------------------------------------------------------------------------- /Doubly Linked List: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class DLLNode{ 4 | public: 5 | int data; 6 | class DLLNode *next; 7 | class DLLNode *prev; 8 | }; 9 | void DLLInsert(DLLNode **head,int data,int position){ 10 | int k = 1; 11 | class DLLNode *temp,*newNode; 12 | newNode = (class DLLNode*)malloc(sizeof(class DLLNode)); 13 | 14 | if(!newNode) cout <<"Memory Error"; 15 | newNode->data = data; 16 | if(position ==1){ 17 | newNode->next = *head; 18 | newNode->prev = NULL; 19 | if(*head) 20 | (*head )->prev = newNode; 21 | } 22 | temp = *head; 23 | { 24 | while((knext!=NULL) 25 | temp = temp->next; 26 | k++; 27 | } 28 | if(k!=position) cout <<"Desired position"; 29 | newNode->next = temp->next; 30 | newNode->prev = temp; 31 | if(temp->next) 32 | temp->next->prev = newNode; 33 | temp->next = newNode; 34 | return; 35 | } 36 | int main(){ 37 | DLLNode *head; 38 | DLLInsert( &head,55,1); 39 | //DLLInsert(&head,55,2); 40 | //DLLInsert(&head,55,3); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /HackerRank/Average.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG (POPULATION) FROM CITY WHERE DISTRICT = 'California'; -------------------------------------------------------------------------------- /HackerRank/Average_Population.sql: -------------------------------------------------------------------------------- 1 | Select floor(avg(population)) from city; -------------------------------------------------------------------------------- /HackerRank/Binary_Tree_Node.sql: -------------------------------------------------------------------------------- 1 | SELECT N, 2 | CASE 3 | WHEN P IS NULL THEN "Root" 4 | WHEN N IN ( 5 | SELECT P 6 | FROM BST 7 | ) THEN "Inner" 8 | ELSE "Leaf" 9 | END 10 | FROM BST 11 | order by n; -------------------------------------------------------------------------------- /HackerRank/Count_Function.sql: -------------------------------------------------------------------------------- 1 | Select count (district) from city where population > 100000; -------------------------------------------------------------------------------- /HackerRank/Employee_Names.sql: -------------------------------------------------------------------------------- 1 | Select name from Employee order by name asc; -------------------------------------------------------------------------------- /HackerRank/Employee_Salary.sql: -------------------------------------------------------------------------------- 1 | Select name from Employee where salary > 2000 and months < 10 order by employee_id asc; -------------------------------------------------------------------------------- /HackerRank/Higher_Than_75marks.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM STUDENTS WHERE MARKS > 75 ORDER BY RIGHT(NAME, 3), ID ASC; 2 | 3 | -------------------------------------------------------------------------------- /HackerRank/Japan_Population.sql: -------------------------------------------------------------------------------- 1 | select sum(population) from city where countrycode = 'JPN'; -------------------------------------------------------------------------------- /HackerRank/Japanese_City_Attribute.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY 2 | WHERE COUNTRYCODE = 'JPN'; 3 | -------------------------------------------------------------------------------- /HackerRank/Japanese_City_Names.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM CITY 2 | WHERE COUNTRYCODE = 'JPN'; 3 | -------------------------------------------------------------------------------- /HackerRank/New_Companies.sql: -------------------------------------------------------------------------------- 1 | select company.company_code, 2 | company.founder, 3 | count(distinct lead_manager.lead_manager_code), 4 | count(distinct senior_manager.senior_manager_code), 5 | count(distinct manager.manager_code), 6 | count(distinct employee.employee_code) 7 | From Company 8 | INNER JOIN lead_manager ON company.company_code = lead_manager.company_code 9 | INNER JOIN senior_manager ON lead_manager.lead_manager_code = senior_manager.lead_manager_code 10 | INNER JOIN manager ON senior_manager.senior_manager_code = manager.senior_manager_code 11 | INNER JOIN employee ON manager.manager_code = employee.manager_code 12 | group by company.company_code, 13 | company.founder 14 | order by company.company_code; -------------------------------------------------------------------------------- /HackerRank/Occupations.sql: -------------------------------------------------------------------------------- 1 | SELECT Doctor , Professor , Singer , Actor FROM ( SELECT * FROM( SELECT occupation,name, ROW_NUMBER()OVER(PARTITION By occupation order by name asc) rownumber FROM OCCUPATIONS ) PIVOT( MIN(name) FOR occupation IN ( 'Doctor' Doctor, 'Professor' Professor, 'Singer' Singer, 'Actor' Actor) ) ORDER BY rownumber ); -------------------------------------------------------------------------------- /HackerRank/Population_Density_Difference.sql: -------------------------------------------------------------------------------- 1 | select (max(population)-min(population)) FROM CITY; -------------------------------------------------------------------------------- /HackerRank/Select_All.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY; -------------------------------------------------------------------------------- /HackerRank/Select_ByID.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY 2 | WHERE ID = 1661; -------------------------------------------------------------------------------- /HackerRank/Select_Query(I).sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY 2 | WHERE COUNTRYCODE = 'USA' 3 | AND POPULATION>100000; -------------------------------------------------------------------------------- /HackerRank/Select_Query(II).sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM CITY 2 | WHERE COUNTRYCODE = 'USA' 3 | AND POPULATION >120000; 4 | -------------------------------------------------------------------------------- /HackerRank/Sum_Function.sql: -------------------------------------------------------------------------------- 1 | select sum(population) from city where District = 'California'; -------------------------------------------------------------------------------- /HackerRank/ThePads.sql: -------------------------------------------------------------------------------- 1 | select CONCAT(NAME, CONCAT('(',left(occupation,1),')')) as Name from occupations order by name; 2 | 3 | SELECT concat("There are a total of ", COUNT(OCCUPATION),' ',lower(occupation),'s.') from occupations group by occupation order by count(occupation), occupation -------------------------------------------------------------------------------- /HackerRank/The_Blunder.sql: -------------------------------------------------------------------------------- 1 | Select ceil(avg(salary) - AVG(REPLACE(Salary,'0',''))) from employees; -------------------------------------------------------------------------------- /HackerRank/Top_Earners.sql: -------------------------------------------------------------------------------- 1 | select max(months*salary),count(months*salary) from Employee where (months*salary) = (select max(months*salary) from Employee); -------------------------------------------------------------------------------- /HackerRank/Triangle_Type.sql: -------------------------------------------------------------------------------- 1 | select case when a+b>c and b+c>a and c+a>b then case when a=b and b=c then 'Equilateral' when a=b or b=c or a=c then 'Isosceles' else 'Scalene' end else 'Not A Triangle' end from triangles; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_1.sql: -------------------------------------------------------------------------------- 1 | SELECT CITY,STATE FROM STATION; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_10.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION WHERE RIGHT(CITY,1) NOT IN('A','E','I','O','U'); -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_11.sql: -------------------------------------------------------------------------------- 1 | select distinct city from station where not regexp_like(lower(city), '^[aeiou].*[aeiou]$'); -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_12.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT City 2 | FROM Station 3 | WHERE REGEXP_LIKE(City, '^[^AEIOU].*[^aeiou]$'); -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_13.sql: -------------------------------------------------------------------------------- 1 | select round(sum(lat_n) , 4) from station where lat_n > 38.7880 and lat_n < 137.2345 ; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_14.sql: -------------------------------------------------------------------------------- 1 | Select round(max(lat_n) , 4) from station where lat_n < 137.2345; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_15.sql: -------------------------------------------------------------------------------- 1 | Select round(long_W, 4) from station where lat_n = (select max(lat_n) from station where lat_n<137.2345); -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_16.sql: -------------------------------------------------------------------------------- 1 | select round(min(lat_n), 4) from station where lat_n > 38.7780; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_17.sql: -------------------------------------------------------------------------------- 1 | Select round (long_w , 4) from station where lat_n = (Select min(lat_n) from station where lat_n > 38.7780); 2 | -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_18.sql: -------------------------------------------------------------------------------- 1 | Select abs (round ((min(lat_n)-max(lat_n)) + (min(long_w)-max(long_w)) , 4)) from station; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_19.sql: -------------------------------------------------------------------------------- 1 | select round( 2 | sqrt ( 3 | power ((max(long_w) - min(long_w)), 2) + power((max(lat_n) - min(lat_n)), 2) 4 | ), 5 | 4 6 | ) 7 | from station; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_2.sql: -------------------------------------------------------------------------------- 1 | /* 2 | Enter your query here. 3 | */ 4 | Select round(sum(lat_n) , 2) , round(sum(long_w) , 2) from station; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_20.sql: -------------------------------------------------------------------------------- 1 | select round(s.lat_n,4) from station s where (select round(count(s.id)/2)-1 from station) = (select count(s1.id) from station s1 where s1.lat_n > s.lat_n); -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_3.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION WHERE MOD(ID,2)=0; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_4.sql: -------------------------------------------------------------------------------- 1 | select count (city) - count(distinct city) from station; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_5.sql: -------------------------------------------------------------------------------- 1 | SELECT TOP 1 CITY, 2 | LEN(CITY) 3 | FROM STATION 4 | ORDER BY LEN(CITY), CITY ASC; 5 | 6 | SELECT TOP 1 CITY, 7 | LEN(CITY) 8 | FROM STATION 9 | ORDER BY LEN(CITY) DESC; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_6.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION 2 | WHERE CITY LIKE 'a%'; 3 | 4 | SELECT DISTINCT CITY FROM STATION 5 | WHERE CITY LIKE 'e%'; 6 | 7 | SELECT DISTINCT CITY FROM STATION 8 | WHERE CITY LIKE 'i%'; 9 | 10 | SELECT DISTINCT CITY FROM STATION 11 | WHERE CITY LIKE 'o%'; 12 | 13 | SELECT DISTINCT CITY FROM STATION 14 | WHERE CITY LIKE 'u%'; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_7.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION 2 | WHERE CITY LIKE '%a'; 3 | 4 | SELECT DISTINCT CITY FROM STATION 5 | WHERE CITY LIKE '%e'; 6 | 7 | SELECT DISTINCT CITY FROM STATION 8 | WHERE CITY LIKE '%i'; 9 | 10 | SELECT DISTINCT CITY FROM STATION 11 | WHERE CITY LIKE '%o'; 12 | 13 | SELECT DISTINCT CITY FROM STATION 14 | WHERE CITY LIKE '%u'; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_8.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION 2 | WHERE CITY LIKE 'a%e'; 3 | 4 | SELECT DISTINCT CITY FROM STATION 5 | WHERE CITY LIKE 'a%i'; 6 | 7 | SELECT DISTINCT CITY FROM STATION 8 | WHERE CITY LIKE 'a%o'; 9 | 10 | SELECT DISTINCT CITY FROM STATION 11 | WHERE CITY LIKE 'a%a'; 12 | 13 | SELECT DISTINCT CITY FROM STATION 14 | WHERE CITY LIKE 'a%u'; 15 | 16 | SELECT DISTINCT CITY FROM STATION 17 | WHERE CITY LIKE 'e%a'; 18 | 19 | SELECT DISTINCT CITY FROM STATION 20 | WHERE CITY LIKE 'e%e'; 21 | 22 | SELECT DISTINCT CITY FROM STATION 23 | WHERE CITY LIKE 'e%i'; 24 | 25 | SELECT DISTINCT CITY FROM STATION 26 | WHERE CITY LIKE 'e%o'; 27 | 28 | SELECT DISTINCT CITY FROM STATION 29 | WHERE CITY LIKE 'e%u'; 30 | 31 | SELECT DISTINCT CITY FROM STATION 32 | WHERE CITY LIKE 'i%e'; 33 | 34 | SELECT DISTINCT CITY FROM STATION 35 | WHERE CITY LIKE 'i%i'; 36 | 37 | SELECT DISTINCT CITY FROM STATION 38 | WHERE CITY LIKE 'i%o'; 39 | 40 | SELECT DISTINCT CITY FROM STATION 41 | WHERE CITY LIKE 'i%a'; 42 | 43 | SELECT DISTINCT CITY FROM STATION 44 | WHERE CITY LIKE 'i%u'; 45 | 46 | SELECT DISTINCT CITY FROM STATION 47 | WHERE CITY LIKE 'o%e'; 48 | 49 | SELECT DISTINCT CITY FROM STATION 50 | WHERE CITY LIKE 'o%i'; 51 | 52 | SELECT DISTINCT CITY FROM STATION 53 | WHERE CITY LIKE 'o%o'; 54 | 55 | SELECT DISTINCT CITY FROM STATION 56 | WHERE CITY LIKE 'o%a'; 57 | 58 | SELECT DISTINCT CITY FROM STATION 59 | WHERE CITY LIKE 'o%u'; 60 | 61 | SELECT DISTINCT CITY FROM STATION 62 | WHERE CITY LIKE 'u%e'; 63 | 64 | SELECT DISTINCT CITY FROM STATION 65 | WHERE CITY LIKE 'u%i'; 66 | 67 | SELECT DISTINCT CITY FROM STATION 68 | WHERE CITY LIKE 'u%o'; 69 | 70 | SELECT DISTINCT CITY FROM STATION 71 | WHERE CITY LIKE 'u%a'; 72 | 73 | SELECT DISTINCT CITY FROM STATION 74 | WHERE CITY LIKE 'u%u'; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_9.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION 2 | WHERE CITY REGEXP '^[^aeiou]'; -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2020 Ankit Kumar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /LeetCode/multiply_strings.py: -------------------------------------------------------------------------------- 1 | # LeetCode Problem link - https://leetcode.com/problems/multiply-strings/submissions/ 2 | 3 | class Solution: 4 | def multiply(self, num1: str, num2: str) -> str: 5 | return ""+str(int(num1)*int(num2)) -------------------------------------------------------------------------------- /LinkedList/Circular.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/Circular.class -------------------------------------------------------------------------------- /LinkedList/Circular.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | int data; 3 | Node next; 4 | 5 | public Node () {} 6 | 7 | public Node (int sk) { 8 | this.data = sk; 9 | this.next = null; 10 | } 11 | } 12 | 13 | class CircularLinkedList { 14 | 15 | private Node head; 16 | 17 | public CircularLinkedList() { 18 | this.head = null; 19 | } 20 | 21 | public void append(int data) { 22 | Node newNode = new Node(data); 23 | if (this.head == null) { 24 | this.head = newNode; 25 | newNode.next = this.head; 26 | }else{ 27 | Node ptr = this.head; 28 | while(ptr.next != this.head) ptr=ptr.next; 29 | ptr.next = newNode; 30 | newNode.next = this.head; 31 | } 32 | } 33 | 34 | public void traverse() { 35 | if (this.head == null) { 36 | System.out.println("The linked list is empty"); 37 | return; 38 | } 39 | 40 | Node ptr = this.head; 41 | while(ptr.next != this.head) { 42 | System.out.print(ptr.data + " : "); 43 | ptr = ptr.next; 44 | } 45 | System.out.print(ptr.data); 46 | } 47 | 48 | } 49 | 50 | public class Circular { 51 | public static void main(String[] args) { 52 | CircularLinkedList ob = new CircularLinkedList(); 53 | ob.append(1); 54 | ob.append(2); 55 | ob.append(3); 56 | ob.traverse(); 57 | } 58 | } -------------------------------------------------------------------------------- /LinkedList/Circular.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | 4 | Implementing circular linked list 5 | 6 | """ 7 | 8 | # class to create a node of the linked list 9 | class LinkedlistNode : 10 | def __init__(self, data) : 11 | self.data = data 12 | self.next_node = None 13 | 14 | 15 | # circular linked list class (main class) 16 | class CircularList : 17 | 18 | # constructor of the class 19 | def __init__(self) : 20 | self.head = None 21 | 22 | 23 | # method to append a node at the end of the circular linked list 24 | def append(self, data) : 25 | 26 | ptr = LinkedlistNode(data) 27 | 28 | if self.head is None : 29 | self.head = ptr 30 | ptr.next_node = self.head 31 | 32 | else : 33 | 34 | qptr = self.head 35 | while qptr.next_node != self.head : qptr = qptr.next_node 36 | 37 | qptr.next_node = ptr 38 | ptr.next_node = self.head 39 | 40 | 41 | # method to traverse the circular linked list 42 | def traverse(self) : 43 | if self.head is None : 44 | print('The linked list is empty') 45 | return 46 | 47 | else : 48 | ptr = self.head 49 | while ptr.next_node != self.head : 50 | print(ptr.data, end = " : ") 51 | ptr = ptr.next_node 52 | print(ptr.data) 53 | 54 | 55 | # method to search for a element in the linked list 56 | def search(self, sk) : 57 | if self.head is None : 58 | return False 59 | 60 | if self.head.data == sk : 61 | return True 62 | 63 | ptr = self.head.next_node 64 | 65 | while ptr != self.head : 66 | if ptr.data == sk : 67 | return True 68 | 69 | ptr = ptr.next_node 70 | 71 | return False 72 | 73 | 74 | # method to delete the given node from the linked list 75 | def delete(self, sk) : 76 | if self.head is None : 77 | print('Linked list empty') 78 | return 79 | 80 | if self.head.data == sk : 81 | 82 | # if the given node is the first node to be deleted 83 | qptr = self.head 84 | ptr = self.head 85 | 86 | while ptr.next_node != self.head : ptr = ptr.next_node 87 | 88 | self.head = qptr.next_node 89 | ptr.next_node = self.head 90 | del qptr 91 | 92 | else : 93 | 94 | # deleting any other node from apart from the first node 95 | ptr = self.head 96 | qptr = self.head.next_node 97 | 98 | while qptr.next_node != self.head : 99 | if qptr.data == sk : 100 | ptr.next_node = qptr.next_node 101 | del qptr 102 | return 103 | 104 | ptr = qptr 105 | qptr = qptr.next_node 106 | 107 | if qptr.data == sk : 108 | ptr.next_node = self.head 109 | del qptr 110 | 111 | 112 | if __name__ == '__main__' : 113 | linkedList = CircularList() 114 | 115 | linkedList.append(1) 116 | linkedList.append(2) 117 | linkedList.append(3) 118 | 119 | linkedList.traverse() 120 | 121 | -------------------------------------------------------------------------------- /LinkedList/CircularLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/CircularLinkedList.class -------------------------------------------------------------------------------- /LinkedList/Decorators.py: -------------------------------------------------------------------------------- 1 | 2 | def decoratorFunction(view_function) : 3 | print("inside decorator") 4 | def wrapper_function(username) : 5 | import re 6 | regex = re.compile('^([a-zA-Z0-9])+$') 7 | if re.match(regex, username) : 8 | view_function(username) 9 | else : 10 | print("Username entered is not valid") 11 | 12 | return wrapper_function 13 | 14 | 15 | @decoratorFunction 16 | def printFunction(username) : 17 | print("Hello world from{}".format(username)) 18 | 19 | printFunction("ankit#") -------------------------------------------------------------------------------- /LinkedList/Doubly Linked List: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class DLLNode{ 4 | public: 5 | int data; 6 | class DLLNode *next; 7 | class DLLNode *prev; 8 | }; 9 | void DLLInsert(DLLNode **head,int data,int position){ 10 | int k = 1; 11 | class DLLNode *temp,*newNode; 12 | newNode = (class DLLNode*)malloc(sizeof(class DLLNode)); 13 | 14 | if(!newNode) cout <<"Memory Error"; 15 | newNode->data = data; 16 | if(position ==1){ 17 | newNode->next = *head; 18 | newNode->prev = NULL; 19 | if(*head) 20 | (*head )->prev = newNode; 21 | } 22 | temp = *head; 23 | { 24 | while((knext!=NULL) 25 | temp = temp->next; 26 | k++; 27 | } 28 | if(k!=position) cout <<"Desired position"; 29 | newNode->next = temp->next; 30 | newNode->prev = temp; 31 | if(temp->next) 32 | temp->next->prev = newNode; 33 | temp->next = newNode; 34 | return; 35 | } 36 | int main(){ 37 | DLLNode *head; 38 | DLLInsert( &head,55,1); 39 | //DLLInsert(&head,55,2); 40 | //DLLInsert(&head,55,3); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /LinkedList/Doubly-Linked-List.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | PYTHON PROGRAM TO IMPLEMENT DOUBLY LINKED LIST 4 | 5 | """ 6 | 7 | class Node : 8 | data = None 9 | next_node = None 10 | prev_node = None 11 | 12 | 13 | class DoublyLinkedList : 14 | 15 | def __init__(self) : 16 | self.head = None 17 | 18 | 19 | 20 | # function to add a node into the doubly linked list 21 | def insertNode(self, sk) : 22 | ptr = Node() 23 | ptr.data = sk 24 | ptr.next_node = None 25 | 26 | if self.head is None : 27 | ptr.prev_node = None 28 | self.head = ptr 29 | 30 | else : 31 | qptr = self.head 32 | while qptr.next_node is not None : qptr=qptr.next_node 33 | 34 | qptr.next_node = ptr 35 | ptr.prev_node = qptr 36 | 37 | 38 | 39 | # function to traverse the entire doubly linked list 40 | def traverse(self) : 41 | if self.head is None : 42 | print("list is empty") 43 | return 44 | 45 | ptr = self.head 46 | while ptr is not None : 47 | print(ptr.data, end=" ") 48 | ptr = ptr.next_node 49 | 50 | 51 | 52 | # function to search for a node element in the doubly linked list 53 | def searchNode(self, sk): 54 | if self.head is None : 55 | print("List is empty") 56 | return 57 | 58 | ptr = self.head 59 | while ptr!=None : 60 | if ptr.data == sk : 61 | print("Node was found") 62 | return 63 | 64 | print("Node was not found") 65 | 66 | 67 | # function to delete a node from the list 68 | def deleteNode(self, sk) : 69 | if self.head is None : 70 | print("List is empty") 71 | return 72 | 73 | if self.head.data == sk : 74 | ptr = self.head 75 | self.head.next_node = ptr.next_node 76 | del ptr 77 | print("node deleted") 78 | return 79 | 80 | ptr = self.head 81 | while ptr.next_node is not None : 82 | pass 83 | 84 | 85 | 86 | 87 | 88 | if __name__ == '__main__' : 89 | mylist = DoublyLinkedList() 90 | mylist.insertNode(1) 91 | mylist.insertNode(2) 92 | mylist.insertNode(3) 93 | 94 | mylist.traverse() 95 | 96 | -------------------------------------------------------------------------------- /LinkedList/LabProgram.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/LabProgram.class -------------------------------------------------------------------------------- /LinkedList/LabProgram.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a program to accept name and age of a person from the command prompt(passed as arguments when you execute the class) and ensure that the age entered is >=18 and < 60. 3 | Display proper error messages. 4 | The program must exit gracefully after displaying the error message in case the arguments passed are not proper. (Hint : Create a user defined exception class for handling errors.) 5 | */ 6 | 7 | 8 | import java.lang.Exception; 9 | 10 | class UserException extends Exception { 11 | public String toString() { 12 | return "User Expcetion : Username or age you entered are invalid"; 13 | } 14 | } 15 | 16 | class LabProgram { 17 | public static void main(String[] args) { 18 | 19 | try { 20 | 21 | String username = args[0]; 22 | int age = Integer.parseInt(args[1]); 23 | 24 | if (age >=18 && age < 60 ) { 25 | System.out.println("Your name : "+username+ " and age : "+age+ " is valid"); 26 | }else{ 27 | throw new UserException(); 28 | } 29 | 30 | }catch(UserException exception) { 31 | 32 | System.out.print(exception.toString()); 33 | 34 | }catch(Exception exception) { 35 | 36 | System.out.print(exception.toString()); 37 | 38 | } 39 | 40 | } 41 | } -------------------------------------------------------------------------------- /LinkedList/LinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/LinkedList.class -------------------------------------------------------------------------------- /LinkedList/LinkedList.py: -------------------------------------------------------------------------------- 1 | 2 | # structure to create a node for the linked list 3 | 4 | class Node : 5 | data = None 6 | next_node = None 7 | 8 | 9 | 10 | class LinkedList : 11 | 12 | # cosntructor of the program 13 | def __init__(self) : 14 | self.head = None 15 | 16 | 17 | # method to append a new node at the end of the list 18 | def append(self, sk) : 19 | ptr = Node() 20 | ptr.data = sk 21 | ptr.next_node = None 22 | 23 | if self.head is None : 24 | self.head = ptr 25 | 26 | else : 27 | qptr = self.head 28 | while qptr.next_node is not None : qptr = qptr.next_node 29 | qptr.next_node = ptr 30 | 31 | # printing the class values 32 | def __str__(self) : 33 | self.traverse() 34 | return "" 35 | 36 | # iterative method to traverse the linked list 37 | def traverse(self) : 38 | ptr = self.head 39 | if self.head is None : 40 | print("List is empty") 41 | else : 42 | ptr = self.head 43 | while ptr is not None : 44 | print(ptr.data, end = " : ") 45 | ptr = ptr.next_node 46 | 47 | 48 | # recursive method to traverse the linked list 49 | def recursive_traversal(self, head) : 50 | if head is None : 51 | return print("list printed successfully. no data left to display.") 52 | 53 | print(head.data, end = " ") 54 | return self.recursive_traversal(head.next_node) 55 | 56 | # method to return the main node 57 | def returnhead(self) : return self.head 58 | 59 | # method to count the number of nodes in the linked list 60 | def return_number_of_nodes(self) -> int: 61 | total_nodes = 0 62 | ptr = self.head 63 | 64 | while ptr is not None : 65 | total_nodes += 1 66 | ptr = ptr.next_node 67 | 68 | return total_nodes 69 | 70 | 71 | # method to get the sum of all the nodes in the linked list 72 | def sum(self, head) : 73 | if head is None : return 0 74 | return head.data + self.sum(head.next_node) 75 | 76 | 77 | # method to find the maximum element in the linked list 78 | def max(self) -> int : 79 | if self.head is None : 80 | return 0 81 | 82 | largest = self.head.data 83 | 84 | ptr = self.head.next_node 85 | 86 | while ptr is not None : 87 | largest = max(largest, ptr.data) 88 | ptr = ptr.next_node 89 | 90 | return largest 91 | 92 | 93 | # method to find the element in the linked list 94 | def search(self, sk) : 95 | if self.head is None : 96 | print("Linked list is empty") 97 | return 98 | 99 | ptr = self.head 100 | flag, element = False, -1 101 | while ptr.next_node is not None : 102 | if ptr.data == sk : 103 | flag = True 104 | element = ptr.data 105 | break 106 | 107 | if flag : 108 | return element 109 | else : 110 | print('Element was not found in the array') 111 | return 112 | 113 | 114 | # method to check if the linked list is sorted or not 115 | def is_ascending(self) : 116 | if self.head is None : 117 | print("Linked list is empty") 118 | return False 119 | 120 | ptr = self.head 121 | 122 | while ptr.next_node is not None : 123 | if ptr.data > ptr.next_node.data : 124 | return False 125 | 126 | ptr = ptr.next_node 127 | 128 | return True 129 | 130 | 131 | # method to make the list cyclic 132 | def make_cyclic(self) : 133 | ptr = self.head 134 | 135 | qptr = ptr.next_node.next_node 136 | 137 | qptr.next_node = ptr 138 | 139 | 140 | 141 | # method to check if the linked list contains a loop 142 | def is_cyclic(self) : 143 | ptr , qptr = self.head, self.head.next_node 144 | 145 | while ptr is not None and qptr is not None : 146 | if ptr == qptr : 147 | return True 148 | ptr = ptr.next_node 149 | qptr = qptr.next_node.next_node 150 | 151 | return False 152 | 153 | 154 | # method to delete duplicates from the linked list 155 | def delete_duplicates(self) : 156 | has_seen = set() 157 | 158 | prev, ptr = None, self.head 159 | 160 | while ptr is not None : 161 | if ptr.data in has_seen : 162 | qptr = ptr 163 | ptr = ptr.next_node 164 | prev.next_node = ptr 165 | del qptr 166 | else : 167 | has_seen.add(ptr.data) 168 | prev = ptr 169 | ptr = ptr.next_node 170 | 171 | 172 | # method to find the middle element of the linked list 173 | def middle_element(self) : 174 | if self.head is None : 175 | print('List is empty') 176 | return 177 | 178 | 179 | ptr = self.head 180 | qptr = self.head 181 | 182 | while qptr is not None : 183 | qptr = qptr.next_node 184 | if qptr : 185 | qptr = qptr.next_node 186 | ptr = ptr.next_node 187 | 188 | return ptr.data 189 | 190 | 191 | # method to find the middle element of the linked list using a stack 192 | def middle_element_stack(self) : 193 | ptr = self.head 194 | result = list() 195 | while ptr is not None : 196 | result.append(ptr.data) 197 | ptr = ptr.next_node 198 | 199 | return result[len(result)//2] 200 | 201 | 202 | # method to find the intersection of the two linked list 203 | def intersection(self, head : Node) : 204 | ptr = self.head 205 | qptr = head 206 | 207 | r1 = set();r2 = set() 208 | 209 | while ptr is not None : 210 | r1.add(ptr) 211 | ptr = ptr.next_node 212 | 213 | while qptr is not None : 214 | if qptr in r1 : 215 | return (True, qptr.data) 216 | 217 | return False 218 | 219 | 220 | if __name__ == '__main__' : 221 | 222 | linkedlist = LinkedList() 223 | newlist = LinkedList() 224 | 225 | linkedlist.append(1) 226 | linkedlist.append(1) 227 | linkedlist.append(4) 228 | linkedlist.append(3) 229 | linkedlist.append(5) 230 | linkedlist.append(5) 231 | linkedlist.append(1) 232 | linkedlist.append(7) 233 | linkedlist.append(8) 234 | 235 | linkedlist.delete_duplicates() 236 | 237 | print("intersection = ", linkedlist.intersection(newlist.returnhead())) 238 | 239 | print("Middle node = ", linkedlist.middle_element_stack()) 240 | print("Middle node = ", linkedlist.middle_element()) 241 | 242 | linkedlist.recursive_traversal(linkedlist.returnhead()) 243 | 244 | print("total number of nodes = {}".format(linkedlist.return_number_of_nodes())) 245 | print("Sum of all the nodes = {}".format(linkedlist.sum(linkedlist.returnhead()))) 246 | print("Largest element in the array = {}".format(linkedlist.max())) 247 | print(linkedlist.is_ascending()) 248 | print(linkedlist) 249 | linkedlist.make_cyclic() 250 | print("Cyclic : ", linkedlist.is_cyclic()) 251 | 252 | -------------------------------------------------------------------------------- /LinkedList/List.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/List.class -------------------------------------------------------------------------------- /LinkedList/List.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | // Data structure to create node of the linked list 4 | class Node { 5 | int data; 6 | Node next; 7 | } 8 | 9 | 10 | class LinkedList { 11 | 12 | private Node head; 13 | 14 | // constructor of the linked list class 15 | public LinkedList() { 16 | this.head = null; 17 | } 18 | 19 | // method to append a node at the end of the linked list 20 | public void append(int sk) { 21 | 22 | Node ptr = new Node(); 23 | ptr.data = sk; 24 | ptr.next = null; 25 | 26 | if (this.head == null) this.head=ptr; 27 | else { 28 | Node qptr = this.head; 29 | while (qptr.next != null) qptr=qptr.next; 30 | qptr.next = ptr; 31 | } 32 | 33 | } 34 | 35 | 36 | // iterative method to traverse all the nodes of the linked list 37 | public void traverse() { 38 | 39 | Node ptr = this.head; 40 | if (ptr == null) { 41 | System.out.println("Linked list is empty"); 42 | return; 43 | } 44 | while(ptr!=null) { 45 | System.out.println(ptr.data + " : "); 46 | ptr = ptr.next; 47 | } 48 | 49 | } 50 | 51 | // method to return the head node of the linked list 52 | public Node getHead() { return this.head; } 53 | 54 | // recursive method to traverse all the nodes of the linked list 55 | public void recursiveTraversal(Node head) { 56 | 57 | if (head == null) { 58 | System.out.println("Printed all nodes"); 59 | return; 60 | } 61 | 62 | System.out.print(head.data); 63 | this.recursiveTraversal(head.next); 64 | 65 | } 66 | 67 | // method to count the number of nodes in the linked list 68 | public long countNodes() { 69 | Node ptr = this.head; 70 | long count = 0; 71 | while(ptr!=null) { 72 | count++; 73 | ptr=ptr.next; 74 | } 75 | return count; 76 | } 77 | 78 | // method to calculate the sum of all the nodes in the linked list 79 | public long sum(Node head) { 80 | if (head == null) return 0; 81 | return head.data + sum(head.next); 82 | } 83 | 84 | // method to get maximum 85 | public int getmax(int m, int n) { 86 | return m > n ? m : n; 87 | } 88 | 89 | // method to get the maximum element from the linked list 90 | public int max() { 91 | 92 | if(this.head == null) return 0; 93 | 94 | int largest = this.head.data; 95 | Node ptr = this.head; 96 | 97 | while(ptr!=null) { 98 | largest = this.getmax(largest, ptr.data);ptr=ptr.next; 99 | } 100 | 101 | return largest; 102 | 103 | } 104 | 105 | public int search(int sk) { 106 | Node ptr = this.head; 107 | while(ptr!=null) { 108 | if(ptr.data == sk) { 109 | return ptr.data; 110 | } 111 | ptr = ptr.next; 112 | } 113 | return -1; 114 | } 115 | 116 | public boolean isAscending() { 117 | Node ptr = this.head; 118 | while(ptr.next!=null) { 119 | if(ptr.data > ptr.next.data) { 120 | return false; 121 | } 122 | ptr = ptr.next; 123 | } 124 | return true; 125 | } 126 | 127 | public void delete_duplicates() { 128 | HashSet hashSet = new HashSet<>(); 129 | if (hashSet.contains(1)) { 130 | 131 | }else{ 132 | 133 | } 134 | } 135 | 136 | } 137 | 138 | 139 | class List { 140 | public static void main(String[] args) { 141 | LinkedList ob = new LinkedList(); 142 | ob.append(1); 143 | ob.append(2); 144 | ob.append(3); 145 | ob.recursiveTraversal(ob.getHead()); 146 | System.out.println("Total number of nodes = "+ob.countNodes()); 147 | System.out.println("Sum of nodes of the list = "+ob.sum(ob.getHead())); 148 | System.out.println("Maximum element in the linked list = " + ob.max()); 149 | } 150 | } -------------------------------------------------------------------------------- /LinkedList/List.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | PROGRAM TO CREATE A LINKED LIST IN PYTHON 4 | """ 5 | 6 | # class used to create a single node or point to node 7 | class Node : 8 | data = None 9 | next_node = None 10 | 11 | 12 | # class to create a linked list 13 | class LinkedList : 14 | 15 | def __init__(self) : 16 | self.head = None 17 | 18 | 19 | # function to insert a node at the end of the linked list 20 | def insertData(self, num) : 21 | ptr = Node() 22 | ptr.data = num 23 | ptr.next_node = None 24 | 25 | if self.head == None : 26 | self.head = ptr 27 | else : 28 | qptr = self.head 29 | while qptr.next_node != None : 30 | qptr = qptr.next_node 31 | 32 | qptr.next_node = ptr 33 | 34 | 35 | 36 | # function to traverse the entire linked list (iterative method) 37 | def traverse(self) : 38 | if self.head == None : 39 | print("No data in the list") 40 | else : 41 | ptr = self.head 42 | while ptr != None : 43 | print(ptr.data, end = " -> ") 44 | ptr = ptr.next_node 45 | 46 | 47 | 48 | # function to get the head pointer 49 | def gethead(self) : 50 | return self.head 51 | 52 | 53 | # function to traverse a linked list recursively 54 | def recursiveTraverse(self, main_node) : 55 | if main_node == None : 56 | print("list ended") 57 | return 58 | 59 | print(main_node.data) 60 | self.recursiveTraverse(main_node.next_node) 61 | 62 | 63 | 64 | # function to delete a node from the linked list using the data 65 | def remove(self, sk) : 66 | if self.head == None : 67 | print("The lis is empty") 68 | return 69 | 70 | if self.head.data == sk : 71 | ptr = self.head 72 | self.head = ptr.next_node 73 | del ptr 74 | print("Element deleted") 75 | return 76 | 77 | qptr = self.head 78 | 79 | while qptr.next_node != None : 80 | 81 | if qptr.next_node.data == sk : 82 | ptr = qptr.next_node 83 | qptr.next_node = ptr.next_node 84 | del ptr 85 | print("Element deleted ") 86 | return 87 | 88 | 89 | qptr = qptr.next_node 90 | 91 | print("Element was not found") 92 | 93 | 94 | # searching an element in the linked list 95 | def searchNode(self, sk) : 96 | ptr = self.head 97 | if ptr is None : 98 | print("List is empty");return 99 | 100 | while ptr is not None : 101 | if ptr.data == sk : 102 | print("Element was found in the list") 103 | return 104 | ptr = ptr.next_node 105 | 106 | print("Element was not found in the list") 107 | 108 | 109 | 110 | # deleting the first node from the list 111 | def deleteFirst(self) : 112 | if self.head is None : 113 | print("list is empty") 114 | return 115 | 116 | ptr = self.head 117 | self.head = ptr.next_node 118 | num = ptr.data 119 | del ptr 120 | print("Deleted the first node") 121 | return num 122 | 123 | 124 | 125 | # function to delete duplicate nodes from the linked list in O(n) 126 | def delDuplicate(self) : 127 | dup = set() 128 | if self.head is None : 129 | print("List is empty") 130 | return 131 | 132 | ptr = self.head;prev=self.head 133 | 134 | dup.add(ptr.data) 135 | ptr = ptr.next_node 136 | 137 | while ptr is not None : 138 | if ptr.data in dup : 139 | prev.next_node = ptr.next_node 140 | del ptr 141 | ptr = prev.next_node 142 | else : 143 | dup.add(ptr.data) 144 | prev = ptr 145 | ptr = ptr.next_node 146 | 147 | 148 | # function to convert a singly linked list to a circular linked list 149 | def convertCircular(self) : 150 | 151 | if self.head is None : 152 | print("List is empty") 153 | return 154 | 155 | ptr = self.head 156 | 157 | while ptr.next_node is not None : 158 | ptr = ptr.next_node 159 | 160 | ptr.next_node = self.head 161 | 162 | 163 | 164 | if __name__ == '__main__' : 165 | 166 | mylist = LinkedList() 167 | mylist.insertData(5) 168 | mylist.insertData(4) 169 | mylist.insertData(3) 170 | mylist.insertData(2) 171 | mylist.insertData(5) 172 | 173 | mylist.traverse() 174 | 175 | print() 176 | mylist.delDuplicate() 177 | 178 | mylist.traverse() 179 | 180 | 181 | -------------------------------------------------------------------------------- /LinkedList/Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/Node.class -------------------------------------------------------------------------------- /LinkedList/Operator.py: -------------------------------------------------------------------------------- 1 | # operator overloading in python 2 | from abc import ABC, abstractmethod 3 | 4 | class OperatorOverloading(ABC) : 5 | 6 | @abstractmethod 7 | def __add__(self) : pass 8 | 9 | 10 | class Overloaded(OperatorOverloading) : 11 | 12 | def __init__(self, num) : 13 | self.num = num 14 | 15 | def __add__(self) : 16 | pass 17 | pass 18 | 19 | class Overloading : 20 | 21 | def __init__(self, num) : 22 | self.num = num 23 | 24 | 25 | # relational operator overloading 26 | def __le__(self, other) : 27 | return self.num <= other.num 28 | 29 | def __lt__(self, other) : 30 | return self.num < other.num 31 | 32 | def __ge__(self, other) : 33 | return self.num >= other.num 34 | 35 | def __gt__(self, other) : 36 | return self.num > other.num 37 | 38 | 39 | # basic multiplication methods 40 | def __floordiv__(self, other) : 41 | return self.num // other.num 42 | 43 | def __truediv__(self, other) : 44 | return self.num / other.div 45 | 46 | def __mul__(self, other) : 47 | return self.num + other.num 48 | 49 | def __add__(self, other) : 50 | return self.num + other.num 51 | 52 | def __sub__(self, other) : 53 | return self.num + other.num 54 | 55 | 56 | if __name__ == '__main__' : 57 | from collections import Counter 58 | 59 | print(Counter(['a', 'b', 'c', 'd', 'a'])) -------------------------------------------------------------------------------- /LinkedList/UserException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/LinkedList/UserException.class -------------------------------------------------------------------------------- /Matrix/diagonal.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Diagonal matrix program 4 | """ 5 | 6 | # method to check if the given matrix is a diagonal matrix or not 7 | def is_diagonal_matrix(arr) : 8 | 9 | for i in range(len(arr)) : 10 | for j in range(len(arr[i])) : 11 | if i == j : 12 | if arr[i][j] == 0 : 13 | return False 14 | 15 | else : 16 | if arr[i][j] != 0 : 17 | return False 18 | else : 19 | print("Loop ends here ... ") 20 | 21 | 22 | return True 23 | 24 | 25 | def is_lower_triangle_matrix(arr) : 26 | 27 | for i in range(len(arr)) : 28 | for j in range(len(arr[i])) : 29 | if j > i : 30 | if arr[i][j] != 0 : 31 | return False 32 | 33 | else : 34 | if arr[i][j] == 0 : 35 | return False 36 | 37 | 38 | return True 39 | 40 | 41 | 42 | # driver code of the program 43 | if __name__ == '__main__' : 44 | 45 | arr = [ 46 | [2,0,0,0,0], 47 | [1,7,0,0,0], 48 | [2,3,4,0,0], 49 | [1,1,1,9,0], 50 | [1,2,2,2,6] 51 | ] 52 | 53 | print(is_diagonal_matrix(arr)) 54 | print(is_lower_triangle_matrix(arr)) 55 | -------------------------------------------------------------------------------- /Printermanagement: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | struct Node { 6 | int data; 7 | Node* next = NULL; 8 | }; 9 | 10 | struct Queue { 11 | Node *front= NULL, *rear = NULL; 12 | void enQueue(int x) 13 | { 14 | 15 | Node* temp = new Node; 16 | temp->data = x; 17 | if (rear == NULL) { 18 | front = rear = temp; 19 | return; 20 | } 21 | rear->next = temp; 22 | rear = temp; 23 | } 24 | 25 | void deQueue() 26 | { 27 | if (front == NULL) 28 | return; 29 | 30 | Node* temp = front; 31 | front = front->next; 32 | if (front == NULL) 33 | rear = NULL; 34 | 35 | free(temp); 36 | } 37 | }; 38 | 39 | void display(Node * p) 40 | { 41 | 42 | while(p!=NULL) 43 | { 44 | printf("Printing the document of person with user id = %d\n",p->data); 45 | p=p->next; 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | 52 | Queue q; 53 | int x; 54 | int choice; 55 | do{ 56 | printf("enter your id (integer)\n"); 57 | scanf("%d",&x); 58 | q.enQueue(x); 59 | printf("\nDo you want to use the printer?1: YES \n"); 60 | scanf("%d",&choice); 61 | }while(1==choice); 62 | 63 | display((q.front)); 64 | } 65 | -------------------------------------------------------------------------------- /Problems/Insertion.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Problems/Insertion.class -------------------------------------------------------------------------------- /Problems/Insertion.java: -------------------------------------------------------------------------------- 1 | public class Insertion { 2 | 3 | public static void insertionSort(int[] arr) { 4 | int j, temp; 5 | 6 | for(int i=1;i=0 && arr[j] > temp) { 10 | arr[j+1] = arr[j]; 11 | j--; 12 | } 13 | arr[j+1] = temp; 14 | } 15 | } 16 | 17 | public static void main(String[] args) { 18 | int[] arr = {-1, 1,2, 3,-5,89,12,6,7,8,-10}; 19 | insertionSort(arr); 20 | for(int x : arr) 21 | System.out.println(x + " : "); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Problems/Negative.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Problems/Negative.class -------------------------------------------------------------------------------- /Problems/Negative.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Move all the negative elements towards the left of the right 3 | * arr = [-1, 1,2, 3,-5,6,7,8-10] 4 | * 5 | * temp = -1 6 | * 7 | * output = [-1,-5,-10,1,2,3,6,7,8] 8 | */ 9 | 10 | public class Negative { 11 | 12 | public static void moveNegative(int[] arr) { 13 | int j, temp; 14 | 15 | for(int i=1;i=0 && temp < 0) { 19 | arr[j+1] = arr[j]; 20 | j--; 21 | } 22 | arr[j+1] = temp; 23 | } 24 | } 25 | 26 | public static void main(String[] args) { 27 | int[] arr = {89, 10,-1,-2,-5,11,67}; 28 | moveNegative(arr); 29 | for(int x : arr) 30 | System.out.println(x + " : "); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Problems/Prime.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Problems/Prime.class -------------------------------------------------------------------------------- /Problems/Prime.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class PrimeCheck { 4 | public static boolean isPrime(int num) { 5 | 6 | if(num < 2) 7 | return false; 8 | 9 | if (num==2) 10 | return true; 11 | 12 | for(int i = 2;i<=Math.sqrt(num);i++){ 13 | if(num%i==0) { 14 | return false; 15 | } 16 | } 17 | 18 | return true; 19 | } 20 | 21 | } 22 | 23 | public class Prime { 24 | public static void main(String[] args) { 25 | Scanner sc = new Scanner(System.in); 26 | int range = sc.nextInt(); 27 | sc.close(); 28 | 29 | for(int i=1;i<=range;i++){ 30 | if(PrimeCheck.isPrime(i)) { 31 | System.out.print(i+":"); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Problems/PrimeCheck.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Problems/PrimeCheck.class -------------------------------------------------------------------------------- /Problems/Prob1.py: -------------------------------------------------------------------------------- 1 | 2 | n = int(input()) 3 | c = int(input()) 4 | 5 | csum = 0;prod = 1 6 | 7 | if c == 1 : 8 | for i in range(1, n+1) : 9 | csum += i 10 | print(csum) 11 | elif c == 2 : 12 | for i in range(1, n+1) : 13 | prod *= i 14 | print(prod) 15 | else : 16 | print(-1) -------------------------------------------------------------------------------- /Problems/Prob2.py: -------------------------------------------------------------------------------- 1 | # expression = 3n + 2 2 | 3 | x = int(input()) 4 | 5 | count = 0;i=1 6 | 7 | while True : 8 | num = 3*i + 2 9 | i+=1 10 | 11 | if num%4 != 0 : 12 | print(num, end = " ") 13 | count += 1 14 | 15 | if count == x : 16 | break -------------------------------------------------------------------------------- /Problems/Selection.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Problems/Selection.class -------------------------------------------------------------------------------- /Problems/Selection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Write a function to sort the array using selection sort 3 | * ------------------------------------------------------- 4 | * [5,3,1,6,2] - ascending order (1) 5 | * 6 | * [1,3,3,5,6,2] (2) 7 | * 8 | * [1,2,5,6,3] (3) 9 | * 10 | * [1,2,3,5,6] 11 | * 12 | */ 13 | 14 | public class Selection { 15 | 16 | static void selectionSort(int[] arr) { 17 | 18 | for(int i=0;i int : 9 | temp = amount 10 | count = 0 11 | 12 | for i in range(2,5) : 13 | count += temp//i 14 | 15 | return count 16 | 17 | 18 | if __name__ == "__main__": 19 | print(count_bytelandian_amoun(12)) 20 | 21 | -------------------------------------------------------------------------------- /Problems/generate.py: -------------------------------------------------------------------------------- 1 | """ 2 | 3 | Generate all the strings of length n drawn from 0 ... k -1 4 | 5 | """ 6 | 7 | def get_substring(string, counter, result, level, k) : 8 | if level == k : 9 | print(result) 10 | 11 | else : 12 | 13 | for i in range(len(string)) : 14 | if counter[i] == 1 : 15 | result[level] = string[i] 16 | counter[i] = 0 17 | get_substring(string, counter, result, level+1, k) 18 | counter[i] = 1 19 | 20 | 21 | if __name__ == '__main__' : 22 | string = "abcdefgh" 23 | counter = [1 for _ in range(len(string))] 24 | result = [0 for _ in range(len(string))] 25 | get_substring(string, counter, result,0, 4) -------------------------------------------------------------------------------- /Problems/permutation.py: -------------------------------------------------------------------------------- 1 | # string permutation 2 | 3 | def string_permutation(string, counter, result, level) : 4 | if level == len(string) : 5 | print(result) 6 | 7 | else : 8 | 9 | for i in range(len(string)) : 10 | if counter[i] == 0 : 11 | continue 12 | else : 13 | result[level] = string[i] 14 | counter[i] = 0 15 | string_permutation(string, counter, result, level+1) 16 | counter[i] = 1 17 | 18 | 19 | if __name__ == "__main__": 20 | counter = [1,1,1] 21 | result = [0,0,0] 22 | string_permutation(['1', '2', '3'], counter, result, 0) -------------------------------------------------------------------------------- /Problems/prob3.py: -------------------------------------------------------------------------------- 1 | 2 | def reverse(n) : 3 | temp = 0 4 | while n!=0 : 5 | temp = temp*10 + n%10 6 | n //= 10 7 | 8 | return temp 9 | 10 | n=int(input()) 11 | result = reverse(n) 12 | print(result) 13 | 14 | -------------------------------------------------------------------------------- /Problems/prob4.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | decimal = 0 4 | i=0 5 | while n!=0 : 6 | remainder = n%10 7 | decimal += pow(2,i)*remainder 8 | i+=1 9 | n//=10 10 | 11 | print(decimal) -------------------------------------------------------------------------------- /Problems/prob5.py: -------------------------------------------------------------------------------- 1 | n = bin(input()) 2 | 3 | binary = str(bin(n))[2:] 4 | 5 | print(binary) -------------------------------------------------------------------------------- /Problems/prob6.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | for i in range(1, n+1) : 4 | for j in range(i) : 5 | print(1, end="") 6 | print() -------------------------------------------------------------------------------- /Problems/shifting.py: -------------------------------------------------------------------------------- 1 | """ 2 | arr = [1,10,3,4,5,2,2,5,6,7,8,9,2,2] 3 | target_element = 2 4 | output = find all the occurences of target_element and move it on the right/left side of the list or array 5 | 6 | """ 7 | 8 | # swapping method 9 | def shift_using_swapping(arr : list, target : int) : 10 | left = 0;right = len(arr) - 1 11 | 12 | while left <= right : 13 | 14 | while arr[right] == target : right-=1 15 | 16 | if arr[left] == target : 17 | # swapping 18 | arr[left], arr[right] = arr[right], arr[left] 19 | right-=1 20 | 21 | left += 1 22 | 23 | 24 | def shiting_using_iteration(arr : list, target : int) : 25 | 26 | for i in range(1, len(arr)) : 27 | temp = arr[i] 28 | j = i - 1 29 | while j>=0 and temp == target : 30 | arr[j+1] = arr[j] 31 | j-=1 32 | 33 | arr[j+1] = temp 34 | 35 | 36 | 37 | if __name__ == "__main__": 38 | arr = [1,10,3,4,5,2,2,5,6,7,8,9,2,2] 39 | 40 | shiting_using_iteration(arr, 2) 41 | 42 | print(arr) 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /Stack/Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Stack/Node.class -------------------------------------------------------------------------------- /Stack/Stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Stack/Stack.class -------------------------------------------------------------------------------- /Stack/Stack.java: -------------------------------------------------------------------------------- 1 | 2 | class StackClass { 3 | private int[] arr; 4 | private int top; 5 | 6 | public StackClass() { 7 | this.arr = new int[5]; 8 | this.top = -1; 9 | } 10 | 11 | 12 | public void push(int sk) { 13 | 14 | try{ 15 | 16 | if(this.top == this.arr.length-1) { 17 | System.out.println("Stack is overflow"); 18 | return; 19 | } 20 | 21 | this.top++; 22 | this.arr[top] = sk; 23 | 24 | System.out.println("Element inserted into the stack"); 25 | 26 | }catch(ArrayIndexOutOfBoundsException exception) { 27 | System.out.println(exception.toString()); 28 | }catch(Exception exception) { 29 | System.out.println(exception.toString()); 30 | } 31 | 32 | } 33 | 34 | 35 | public int pop() { 36 | if(top==-1) { 37 | System.out.println("Stack is empty/underflow"); 38 | return -1; 39 | } 40 | return this.arr[this.top--]; 41 | } 42 | 43 | public int peek() { 44 | return this.top; 45 | } 46 | 47 | public boolean isFull() { 48 | if(this.top == this.arr.length) { 49 | return true; 50 | } 51 | return false; 52 | } 53 | 54 | public boolean isEmpty() { 55 | return this.top == -1 ? true : false; 56 | } 57 | 58 | public void traverse() { 59 | if(this.isEmpty()) { 60 | System.out.println("Stack is empty"); 61 | return; 62 | } 63 | for(int i=0;i<=this.top;i++) 64 | System.out.print(this.arr[i] + " "); 65 | } 66 | 67 | } 68 | 69 | public class Stack { 70 | public static void main(String[] args) { 71 | StackClass ob = new StackClass(); 72 | 73 | ob.push(1); 74 | ob.push(2); 75 | ob.push(3); 76 | ob.push(4); 77 | ob.push(5); 78 | ob.push(6); 79 | 80 | ob.traverse(); 81 | } 82 | } -------------------------------------------------------------------------------- /Stack/Stack.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Stack is a data structure (linear) based on the principle of Last In First Out 4 | 5 | We will make stack using a linked list here 6 | 7 | """ 8 | 9 | class Stack : 10 | 11 | def __init__(self) : 12 | self.__array = list() -------------------------------------------------------------------------------- /Stack/StackClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Stack/StackClass.class -------------------------------------------------------------------------------- /Stack/StackList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/703f78819a41d4dd88caf71156a4a515651edc1b/Stack/StackList.class -------------------------------------------------------------------------------- /Stack/StackList.java: -------------------------------------------------------------------------------- 1 | 2 | class Node { 3 | int data; 4 | Node next; 5 | Node() { 6 | data = 0; 7 | next = null; 8 | } 9 | 10 | Node(int data) { 11 | this.data = data; 12 | this.next = null; 13 | } 14 | } 15 | 16 | class Stack { 17 | private Node top; 18 | 19 | public Stack() { 20 | this.top = null; 21 | } 22 | 23 | public void push(int data) { 24 | Node newNode = new Node(data); 25 | if(this.top == null) { 26 | this.top = newNode; 27 | }else{ 28 | newNode.next = this.top; 29 | this.top = newNode; 30 | } 31 | } 32 | 33 | public int pop() { 34 | if(this.top == null) { 35 | return -1; 36 | }else{ 37 | Node ptr = this.top; 38 | int data = ptr.data; 39 | this.top = ptr.next; 40 | ptr = null; 41 | return data; 42 | } 43 | } 44 | } 45 | 46 | 47 | public class StackList { 48 | public static void main(String[] args) { 49 | Stack stack = new Stack(); 50 | stack.push(1); 51 | stack.push(2); 52 | stack.push(3); 53 | System.out.print(stack.pop()+" "); 54 | System.out.print(stack.pop()+" "); 55 | System.out.print(stack.pop()+" "); 56 | System.out.print(stack.pop()+" "); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Stack/StackList.py: -------------------------------------------------------------------------------- 1 | """ 2 | Stack using linked list 3 | """ 4 | 5 | class Node : 6 | 7 | def __init__(self, data) : 8 | self.data = data 9 | self.next_node = None 10 | 11 | 12 | class Stack : 13 | 14 | def __init__(self) : 15 | self.top = None 16 | 17 | 18 | 19 | def push(self, data) : 20 | newNode = Node(data) 21 | 22 | if self.top is None : 23 | self.top = newNode 24 | else : 25 | newNode.next_node = self.top 26 | self.top = newNode 27 | 28 | 29 | def pop(self) -> int : 30 | if self.top is None : 31 | return "Stack is empty" 32 | 33 | ptr = self.top 34 | temp = ptr.data 35 | self.top = ptr.next_node 36 | del ptr 37 | return temp 38 | 39 | 40 | 41 | if __name__ == '__main__' : 42 | stack = Stack() 43 | 44 | stack.push(1) 45 | stack.push(2) 46 | stack.push(3) 47 | 48 | print(stack.pop()) 49 | print(stack.pop()) 50 | print(stack.pop()) 51 | print(stack.pop()) 52 | 53 | 54 | -------------------------------------------------------------------------------- /Stack/Words.py: -------------------------------------------------------------------------------- 1 | 2 | # function to get each word in words 3 | def conver_to_word(number) : 4 | num_dict = { 5 | 1 : "One", 6 | 2 : "Two", 7 | 3 : "Three", 8 | 4 : "Four", 9 | 5 : "Five", 10 | 6 : "Six", 11 | 7 : "Seven", 12 | 8 : "Eight", 13 | 9 : "Nine", 14 | 0 : "Zero" 15 | } 16 | 17 | return num_dict.get(number, "Invalid digit") 18 | 19 | 20 | if __name__ == '__main__' : 21 | number = int(input("Enter a number : ")) 22 | temp = number 23 | res = list() 24 | while temp!=0 : 25 | res.append(temp%10) 26 | temp //= 10 27 | 28 | res.reverse() 29 | 30 | for num in res : 31 | print(conver_to_word(num), end = " ") 32 | -------------------------------------------------------------------------------- /Stack/balance.py: -------------------------------------------------------------------------------- 1 | """ 2 | A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. 3 | 4 | Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). 5 | 6 | A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]. 7 | 8 | By this logic, we say a sequence of brackets is balanced if the following conditions are met: 9 | 10 | It contains no unmatched brackets. 11 | The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. 12 | Given strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO. 13 | 14 | Function Description 15 | 16 | Complete the function isBalanced in the editor below. It must return a string: YES if the sequence is balanced or NO if it is not. 17 | 18 | isBalanced has the following parameter(s): 19 | 20 | s: a string of brackets 21 | Input Format 22 | 23 | The first line contains a single integer , the number of strings. 24 | Each of the next lines contains a single string , a sequence of brackets. 25 | 26 | Constraints 27 | 28 | , where is the length of the sequence. 29 | All chracters in the sequences ∈ { {, }, (, ), [, ] }. 30 | Output Format 31 | 32 | For each string, return YES or NO. 33 | 34 | Sample Input 35 | 36 | 3 37 | {[()]} 38 | {[(])} 39 | {{[[(())]]}} 40 | Sample Output 41 | 42 | YES 43 | NO 44 | YES 45 | Explanation 46 | 47 | The string {[()]} meets both criteria for being a balanced string, so we print YES on a new line. 48 | The string {[(])} is not balanced because the brackets enclosed by the matched pair { and } are not balanced: [(]). 49 | The string {{[[(())]]}} meets both criteria for being a balanced string, so we print YES on a new line. 50 | """ 51 | 52 | def isbalanced(string : str) -> bool : 53 | stack = list() 54 | 55 | for el in string : 56 | 57 | if el == '(' or el == '[' or el == '{' : 58 | stack.append(el) 59 | 60 | elif el == ']' : 61 | try : 62 | temp = stack.pop() 63 | except : 64 | temp = 0 65 | if temp != '[' : 66 | return "NO" 67 | elif el == ')' : 68 | try : 69 | temp = stack.pop() 70 | except : 71 | temp = 0 72 | if temp != '(' : 73 | return "NO" 74 | elif el == '}' : 75 | try : 76 | temp = stack.pop() 77 | except : 78 | temp = 0 79 | if temp != '{' : 80 | return "NO" 81 | 82 | if len(stack) > 0 : 83 | return "NO" 84 | 85 | return "YES" 86 | 87 | 88 | if __name__ == '__main__' : 89 | string = "{[(])}"; 90 | print(isbalanced(string)) 91 | -------------------------------------------------------------------------------- /Stack/infix.py: -------------------------------------------------------------------------------- 1 | 2 | # python program to convert infix to postfix using stack 3 | 4 | 5 | # function to get the priority of the characters in the stack 6 | def priority(char) : 7 | if char == '/' or char == '*' or char == '^' : 8 | return 3 9 | elif char == '+' or char == '-' : 10 | return 2 11 | else : 12 | return 1 13 | 14 | 15 | # function get the last element in the stack 16 | def peek(arr) : 17 | return arr[len(arr)-1] 18 | 19 | 20 | # function to convert infix to postfix 21 | def infix_to_postfix(string : str) -> str : 22 | stack = list() 23 | 24 | for char in string : 25 | 26 | if char.isalpha() : 27 | print(char, end=" ") 28 | elif char == '(' : 29 | stack.append(char) 30 | elif char == ')' : 31 | temp = stack.pop() 32 | while stack and temp != '(' : 33 | print(temp, end=" ") 34 | temp = stack.pop() 35 | else : 36 | while stack and priority(peek(stack)) > priority(char) : 37 | print(stack.pop(), end = " ") 38 | 39 | stack.append(char) 40 | 41 | while stack : 42 | print(stack.pop(), end=" ") 43 | 44 | if __name__ == "__main__": 45 | infix_to_postfix("a+(b/d)*e/(f*h)") 46 | 47 | -------------------------------------------------------------------------------- /Stack/paranthesis.py: -------------------------------------------------------------------------------- 1 | # paranthesis matching using stack 2 | 3 | def is_valid(string : str) -> bool : 4 | stack = list() 5 | 6 | for el in string : 7 | if el == '(' : 8 | stack.append(el) 9 | elif el == ')' : 10 | stack.pop() 11 | 12 | if len(stack) > 0 : 13 | return False 14 | else : 15 | return True 16 | 17 | 18 | if __name__ == '__main__' : 19 | string = "(((a+b)*(c-d))" 20 | 21 | print(is_valid(string)) 22 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Algo-Expert | LeetCode | Hackerrank Solutions | Interview Cake 2 | 3 | [![All Contributors](https://img.shields.io/badge/all_contributors-10-orange.svg?style=flat-square)](#contributors-) 4 | 5 | [![GitHub forks](https://img.shields.io/github/forks/AnkitAvi11/Data-Structures-And-Algorithms.svg?style=social&label=Fork&maxAge=43200)](https://github.com/AnkitAvi11/Data-Structures-And-Algorithms/network/) 6 | [![GitHub stars](https://img.shields.io/github/stars/AnkitAvi11/Data-Structures-And-Algorithms.svg?style=social&label=Star&maxAge=43200)](https://github.com/AnkitAvi11/Data-Structures-And-Algorithms/stargazers/) 7 | 8 | 9 | --- 10 | 11 | This repository is mainly to maintain the solutions of *Algo-Expert Questions* alongwith *Leetcode* & *Hackerrank*. Algo-Expert offers with the following resources which are helpful for the students: 12 | 13 | 1. 100 Hand Picked Questions 14 | 2. 70+ Hours of Video Explanations 15 | 3. Data Structures Crash Course 16 | 4. Solution of the problems in 9 languages 17 | 5. Space-Time Complexity Analysis 18 | 19 | ## Contributors ✨ 20 | 21 | People who contributed in this project 22 | 23 | 24 | 25 | 26 | 27 | 28 | 30 | 32 | 34 | 36 | 38 | 39 |

Ankit Singh
29 |

Ayush Kumar
31 |

Saransh-ssh
33 |

Yuvraj Shad
35 |

Piyush
37 |
40 | 41 | 42 | 43 | 44 | 45 | 46 | ## LICENSE 47 | 48 | [MIT](LICENSE) --------------------------------------------------------------------------------