├── Arrays ├── smallestString.py ├── First.cpp ├── Bank.class ├── Last.class ├── Apple.class ├── Fruit.class ├── Merge.class ├── Orange.class ├── Sample.class ├── Unique.class ├── ICICIBank.class ├── KotMBank.class ├── GeneralBank.class ├── UserException.class ├── Numbers.py ├── BinarySearch.java ├── prefix.py ├── Abstract.py ├── UglyNumber.py ├── equivalent.py ├── pattern.py ├── OddOneOut.py ├── Thanos.py ├── amazon.py ├── reversestring.py ├── TwoSum(Returning index).py ├── MoveElementToEnd.py ├── PermutationPalindrome.py ├── candy.py ├── Merge.js ├── PerfectString.py ├── 2D Array_HackerRank.py ├── Solution.py ├── balance.py ├── PickingNumbers.py ├── Sum.py ├── Campus.py ├── Reverse of Lists.py ├── MonotonicArray.py ├── fairarray.py ├── Kadane's_algorithm.py ├── Last.java ├── Triplet.py ├── Meeting.py ├── Merge.py ├── removedup.py ├── reversewords.py ├── ThreeNumbersSum.py ├── wordcloud.py ├── Task.py ├── Inflight.py ├── zeromatrix.py ├── TopScores.py ├── Merge.java ├── defuse.py ├── SmallestDifference.py ├── Sample.java ├── Binary_Search ├── Stack.py ├── reverse.py ├── TwoNumbersSum.py ├── Bank.java ├── Maximum_profit.java ├── Unique.java ├── TimeConversion.py └── NumberLineJumps.py ├── HackerRank ├── Select_All.sql ├── Select_ByID.sql ├── Weather_Observation_1.sql ├── Average_Population.sql ├── Employee_Names.sql ├── Average.sql ├── Weather_Observation_3.sql ├── Count_Function.sql ├── Japan_Population.sql ├── Japanese_City_Attribute.sql ├── Japanese_City_Names.sql ├── Sum_Function.sql ├── Weather_Observation_4.sql ├── Population_Density_Difference.sql ├── The_Blunder.sql ├── Weather_Observation_14.sql ├── Weather_Observation_16.sql ├── Select_Query(I).sql ├── Weather_Observation_9.sql ├── Employee_Salary.sql ├── Select_Query(II).sql ├── Higher_Than_75marks.sql ├── Weather_Observation_10.sql ├── Weather_Observation_11.sql ├── Weather_Observation_12.sql ├── Weather_Observation_13.sql ├── Weather_Observation_18.sql ├── Weather_Observation_15.sql ├── Weather_Observation_2.sql ├── Top_Earners.sql ├── Weather_Observation_17.sql ├── Weather_Observation_20.sql ├── Triangle_Type.sql ├── Weather_Observation_19.sql ├── Weather_Observation_5.sql ├── Binary_Tree_Node.sql ├── ThePads.sql ├── Occupations.sql ├── Weather_Observation_6.sql ├── Weather_Observation_7.sql ├── New_Companies.sql └── Weather_Observation_8.sql ├── Problems ├── prob5.py ├── Test.class ├── Prime.class ├── Insertion.class ├── Negative.class ├── Selection.class ├── Shifting.class ├── PrimeCheck.class ├── prob6.py ├── prob4.py ├── prob3.py ├── Prob2.py ├── Prob1.py ├── codechef.py ├── Insertion.java ├── Test.java ├── permutation.py ├── generate.py ├── armstrong.py ├── Prime.java ├── Negative.java ├── Selection.java ├── shifting.py └── Shifting.java ├── Stack ├── Node.class ├── Stack.class ├── StackClass.class ├── StackList.class ├── Stack.py ├── paranthesis.py ├── Words.py ├── StackList.py ├── infix.py ├── StackList.java ├── Stack.java └── balance.py ├── LinkedList ├── List.class ├── Node.class ├── Circular.class ├── LabProgram.class ├── LinkedList.class ├── UserException.class ├── CircularLinkedList.class ├── Decorators.py ├── Doubly Linked List ├── LabProgram.java ├── Operator.py ├── Circular.java ├── Doubly-Linked-List.py ├── Circular.py ├── List.java ├── List.py └── LinkedList.py ├── Data Structures ├── Java │ ├── Sample.class │ ├── world │ │ └── HelloWorld.class │ ├── factorial │ │ └── Factorial.class │ ├── HelloWorld.java │ ├── Factorial.java │ └── Sample.java ├── Queues │ ├── CreateQueue.class │ ├── queue.py │ ├── QueueList.java │ ├── QueueList.py │ ├── Queue.java │ ├── circularqueue.py │ └── queuestack.py ├── Arrays │ ├── Reverse.py │ ├── MinMax.py │ ├── reversearray.py │ ├── Palindrome.py │ ├── kmaxmin.py │ ├── Sorted.py │ ├── lonely.py │ ├── kadane.py │ ├── rotate.py │ ├── MoveNegative.py │ ├── Missing.py │ ├── Solution.py │ ├── Iterator.py │ ├── word.py │ ├── kadanes.py │ ├── mergetwo.py │ ├── Move.py │ ├── SortingZero.py │ ├── findmissing.py │ ├── Intersection.py │ ├── Symmetric.py │ ├── remove_duplicates.py │ ├── smallestDiv.py │ ├── TwoSum.py │ ├── oneaway.py │ ├── StringCompression.py │ ├── countpairs.py │ ├── Merge.py │ ├── ThreeNumber.py │ ├── Union.py │ ├── smallest.py │ ├── Spiral.py │ ├── monotonic.py │ ├── Duplicate.py │ ├── HourGlass.py │ ├── StringMethods.py │ ├── jumps.py │ ├── reverseingroups.py │ ├── ClassObjects.py │ ├── SortZeroOne.py │ ├── SortingColors.py │ └── BillDivision.py ├── Trees │ ├── prog.py │ └── tree.py └── Queue │ └── Printermanagement ├── LeetCode └── multiply_strings.py ├── CodeChef ├── Enormous.py └── Atm.py ├── Doubly Linked List ├── LICENSE.md ├── Matrix └── diagonal.py ├── Printermanagement └── readme.md /Arrays/smallestString.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /HackerRank/Select_All.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY; -------------------------------------------------------------------------------- /HackerRank/Select_ByID.sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY 2 | WHERE ID = 1661; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_1.sql: -------------------------------------------------------------------------------- 1 | SELECT CITY,STATE FROM STATION; -------------------------------------------------------------------------------- /HackerRank/Average_Population.sql: -------------------------------------------------------------------------------- 1 | Select floor(avg(population)) from city; -------------------------------------------------------------------------------- /HackerRank/Employee_Names.sql: -------------------------------------------------------------------------------- 1 | Select name from Employee order by name asc; -------------------------------------------------------------------------------- /Arrays/First.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | -------------------------------------------------------------------------------- /HackerRank/Average.sql: -------------------------------------------------------------------------------- 1 | SELECT AVG (POPULATION) FROM CITY WHERE DISTRICT = 'California'; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_3.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION WHERE MOD(ID,2)=0; -------------------------------------------------------------------------------- /HackerRank/Count_Function.sql: -------------------------------------------------------------------------------- 1 | Select count (district) from city where population > 100000; -------------------------------------------------------------------------------- /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/Sum_Function.sql: -------------------------------------------------------------------------------- 1 | select sum(population) from city where District = 'California'; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_4.sql: -------------------------------------------------------------------------------- 1 | select count (city) - count(distinct city) from station; -------------------------------------------------------------------------------- /Problems/prob5.py: -------------------------------------------------------------------------------- 1 | n = bin(input()) 2 | 3 | binary = str(bin(n))[2:] 4 | 5 | print(binary) -------------------------------------------------------------------------------- /HackerRank/Population_Density_Difference.sql: -------------------------------------------------------------------------------- 1 | select (max(population)-min(population)) FROM CITY; -------------------------------------------------------------------------------- /HackerRank/The_Blunder.sql: -------------------------------------------------------------------------------- 1 | Select ceil(avg(salary) - AVG(REPLACE(Salary,'0',''))) from employees; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_14.sql: -------------------------------------------------------------------------------- 1 | Select round(max(lat_n) , 4) 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/Select_Query(I).sql: -------------------------------------------------------------------------------- 1 | SELECT * FROM CITY 2 | WHERE COUNTRYCODE = 'USA' 3 | AND POPULATION>100000; -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_9.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION 2 | WHERE CITY REGEXP '^[^aeiou]'; -------------------------------------------------------------------------------- /Arrays/Bank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Bank.class -------------------------------------------------------------------------------- /Arrays/Last.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Last.class -------------------------------------------------------------------------------- /HackerRank/Employee_Salary.sql: -------------------------------------------------------------------------------- 1 | Select name from Employee where salary > 2000 and months < 10 order by employee_id asc; -------------------------------------------------------------------------------- /HackerRank/Select_Query(II).sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM CITY 2 | WHERE COUNTRYCODE = 'USA' 3 | AND POPULATION >120000; 4 | -------------------------------------------------------------------------------- /Stack/Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Stack/Node.class -------------------------------------------------------------------------------- /Stack/Stack.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Stack/Stack.class -------------------------------------------------------------------------------- /Arrays/Apple.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Apple.class -------------------------------------------------------------------------------- /Arrays/Fruit.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Fruit.class -------------------------------------------------------------------------------- /Arrays/Merge.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Merge.class -------------------------------------------------------------------------------- /Arrays/Orange.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Orange.class -------------------------------------------------------------------------------- /Arrays/Sample.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Sample.class -------------------------------------------------------------------------------- /Arrays/Unique.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/Unique.class -------------------------------------------------------------------------------- /HackerRank/Higher_Than_75marks.sql: -------------------------------------------------------------------------------- 1 | SELECT NAME FROM STUDENTS WHERE MARKS > 75 ORDER BY RIGHT(NAME, 3), ID ASC; 2 | 3 | -------------------------------------------------------------------------------- /HackerRank/Weather_Observation_10.sql: -------------------------------------------------------------------------------- 1 | SELECT DISTINCT CITY FROM STATION WHERE RIGHT(CITY,1) NOT IN('A','E','I','O','U'); -------------------------------------------------------------------------------- /Problems/Test.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/Test.class -------------------------------------------------------------------------------- /Arrays/ICICIBank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/ICICIBank.class -------------------------------------------------------------------------------- /Arrays/KotMBank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/KotMBank.class -------------------------------------------------------------------------------- /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_18.sql: -------------------------------------------------------------------------------- 1 | Select abs (round ((min(lat_n)-max(lat_n)) + (min(long_w)-max(long_w)) , 4)) from station; -------------------------------------------------------------------------------- /LinkedList/List.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/List.class -------------------------------------------------------------------------------- /LinkedList/Node.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/Node.class -------------------------------------------------------------------------------- /Problems/Prime.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/Prime.class -------------------------------------------------------------------------------- /Stack/StackClass.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Stack/StackClass.class -------------------------------------------------------------------------------- /Stack/StackList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Stack/StackList.class -------------------------------------------------------------------------------- /Arrays/GeneralBank.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/GeneralBank.class -------------------------------------------------------------------------------- /Problems/Insertion.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/Insertion.class -------------------------------------------------------------------------------- /Problems/Negative.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/Negative.class -------------------------------------------------------------------------------- /Problems/Selection.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/Selection.class -------------------------------------------------------------------------------- /Problems/Shifting.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/Shifting.class -------------------------------------------------------------------------------- /Arrays/UserException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Arrays/UserException.class -------------------------------------------------------------------------------- /LinkedList/Circular.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/Circular.class -------------------------------------------------------------------------------- /LinkedList/LabProgram.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/LabProgram.class -------------------------------------------------------------------------------- /LinkedList/LinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/LinkedList.class -------------------------------------------------------------------------------- /Problems/PrimeCheck.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Problems/PrimeCheck.class -------------------------------------------------------------------------------- /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); -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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; -------------------------------------------------------------------------------- /LinkedList/UserException.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/UserException.class -------------------------------------------------------------------------------- /Data Structures/Java/Sample.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Data Structures/Java/Sample.class -------------------------------------------------------------------------------- /HackerRank/Top_Earners.sql: -------------------------------------------------------------------------------- 1 | select max(months*salary),count(months*salary) from Employee where (months*salary) = (select max(months*salary) from Employee); -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /LinkedList/CircularLinkedList.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/LinkedList/CircularLinkedList.class -------------------------------------------------------------------------------- /Data Structures/Queues/CreateQueue.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Data Structures/Queues/CreateQueue.class -------------------------------------------------------------------------------- /Data Structures/Java/world/HelloWorld.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Data Structures/Java/world/HelloWorld.class -------------------------------------------------------------------------------- /Data Structures/Java/factorial/Factorial.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AnkitKumarSingh11/Data-Structures-And-Algorithms/HEAD/Data Structures/Java/factorial/Factorial.class -------------------------------------------------------------------------------- /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); -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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_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; -------------------------------------------------------------------------------- /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))) -------------------------------------------------------------------------------- /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; -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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; -------------------------------------------------------------------------------- /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() -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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'])) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 ); -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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) -------------------------------------------------------------------------------- /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'; -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /Problems/codechef.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | Bytelandian gold problem solution in python 4 | 5 | """ 6 | 7 | 8 | def count_bytelandian_amoun(amount : int) -> 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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 = " ") -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/amazon.py: -------------------------------------------------------------------------------- 1 | 2 | # forming words of length 'k' 3 | def form_words(string, k) : 4 | i = 0 5 | result = list() 6 | 7 | while i < len(string) : 8 | try : 9 | result.append(string[i:i+k]) 10 | except : 11 | result.append(string[i:]) 12 | i+=k 13 | 14 | return result 15 | 16 | 17 | # driver code 18 | if __name__ == "__main__": 19 | print(form_words('the quick brown fox jumps over the lazy dog', 10)) -------------------------------------------------------------------------------- /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/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)) -------------------------------------------------------------------------------- /Data Structures/Trees/prog.py: -------------------------------------------------------------------------------- 1 | 2 | # method to calculate the factorial of a number 3 | def factorial(num : int) -> 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) -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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)) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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/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/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/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])) -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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#") -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /Arrays/balance.py: -------------------------------------------------------------------------------- 1 | 2 | # balance a string problem leetcode weekly challenge 3 | 4 | def balance_string(string : str) -> 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 | -------------------------------------------------------------------------------- /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/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/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/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/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/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/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/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/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/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/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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/Test.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | class Test { 5 | 6 | public static void main(String[] args) { 7 | Scanner sc = new Scanner(System.in); 8 | System.out.println("Enter two numbers : "); 9 | int m = sc.nextInt(); 10 | int n = sc.nextInt(); 11 | 12 | try { 13 | System.out.println("The quotient of "+m+" / "+" n = "+(m/n)); 14 | } 15 | catch(ArithmeticException exception) { 16 | System.out.println(exception.toString()); 17 | } 18 | finally{ 19 | System.out.println("Inside the finally block"); 20 | } 21 | 22 | sc.close(); 23 | } 24 | } -------------------------------------------------------------------------------- /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)) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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; -------------------------------------------------------------------------------- /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/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)) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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)) -------------------------------------------------------------------------------- /Problems/armstrong.py: -------------------------------------------------------------------------------- 1 | # leetcode amrstrong problem 2 | import math 3 | 4 | 5 | # method to check if the given number is armstrong or not 6 | def is_armstrong(num : int) : 7 | k = math.floor(math.log10(num)) + 1 8 | 9 | summation, temp = 0, num 10 | 11 | while temp != 0 : 12 | r = temp % 10 13 | summation += math.floor(math.pow(r, k)) 14 | temp //= 10 15 | 16 | # for debugging (remove if you want to) 17 | print(k, summation, num) 18 | 19 | # checking if the sum is equal to the number given 20 | if summation == num : 21 | return True 22 | 23 | # returns false if the number is not armstrong 24 | return False 25 | 26 | 27 | if __name__ == '__main__' : 28 | print(is_armstrong(153)) 29 | 30 | 31 | -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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)])) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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)) -------------------------------------------------------------------------------- /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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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")) -------------------------------------------------------------------------------- /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])) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /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/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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | -------------------------------------------------------------------------------- /Data Structures/Queues/queue.py: -------------------------------------------------------------------------------- 1 | # queue using arrays in python 2 | 3 | class Queue : 4 | 5 | def __init__(self) : 6 | self.arr = list() 7 | self.front = -1 8 | self.rear = -1 9 | 10 | 11 | def insert(self, sk) : 12 | if self.front == -1 and self.rear == -1 : 13 | self.front = 0 14 | self.rear = 0 15 | 16 | if self.arr : 17 | self.arr.append(sk) 18 | self.rear = len(self.arr) - 1 19 | 20 | 21 | def isEmpty(self) : 22 | return self.rear == -1 or self.front == -1 23 | 24 | def peek(self) : 25 | if self.rear == -1 : 26 | return -1 27 | 28 | return self.arr[self.rear] 29 | 30 | def delete(self) : 31 | if self.arr : 32 | return self.arr[self.front] 33 | return -1 34 | 35 | def traverse(self) : 36 | if self.arr : 37 | for el in self.arr : 38 | print(el, end=" ") 39 | return -1 40 | 41 | 42 | if __name__ == "__main__": 43 | queue = Queue() 44 | -------------------------------------------------------------------------------- /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=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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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")) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Problems/Shifting.java: -------------------------------------------------------------------------------- 1 | public class Shifting { 2 | 3 | // algorithm used : sliding window algorithm (using swapping) 4 | public static void shiftTarget(int[] arr, int target) { 5 | int left = 0, right = arr.length - 1; 6 | 7 | while(left <= right) { 8 | 9 | while(arr[right] == target) right-=1; 10 | 11 | if(arr[left] == target) { // if this true then we perform swapping 12 | int temp = arr[left]; 13 | arr[left] = arr[right]; 14 | arr[right] = temp; 15 | right-=1; 16 | } 17 | 18 | left+=1; 19 | 20 | } 21 | 22 | } 23 | 24 | // insertion sorting technique 25 | public static void shiftUsingInsertion(int[] arr, int target) { 26 | int temp, j, i = 0; 27 | 28 | while(i= 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/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 | } -------------------------------------------------------------------------------- /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()) -------------------------------------------------------------------------------- /Data Structures/Queues/QueueList.java: -------------------------------------------------------------------------------- 1 | 2 | class Node { 3 | protected int val; 4 | protected Node next; 5 | 6 | public Node () { 7 | this.val = 0; 8 | this.next = null; 9 | } 10 | 11 | public Node(int sk) { 12 | this.val = sk; 13 | this.next = null; 14 | } 15 | } 16 | 17 | class Queue{ 18 | private Node front, rear; 19 | 20 | public Queue() { 21 | this.front = null; 22 | this.rear = null; 23 | } 24 | 25 | public void insert(int sk) { 26 | Node newnode = new Node(sk); 27 | if (this.rear == null) { 28 | this.front = this.rear = newnode; 29 | } 30 | else{ 31 | this.rear.next = newnode; 32 | this.rear = newnode; 33 | } 34 | } 35 | 36 | public void traverse() { 37 | if(this.front == null) {System.out.println("Queue is empty");} 38 | Node ptr = this.front; 39 | while (ptr!=null) { 40 | System.out.print(ptr.val + " "); 41 | ptr = ptr.next; 42 | } 43 | } 44 | 45 | public int delete() { 46 | if(this.front == null) { 47 | System.out.println("Queue is empty"); 48 | return -1; 49 | } 50 | Node ptr = this.front; 51 | this.front = ptr.next; 52 | int temp = ptr.val; 53 | ptr = null; 54 | return temp; 55 | } 56 | } 57 | 58 | 59 | public class QueueList { 60 | public static void main(String[] args) { 61 | Queue queue = new Queue(); 62 | queue.insert(1); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /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/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 | -------------------------------------------------------------------------------- /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/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/Queues/QueueList.py: -------------------------------------------------------------------------------- 1 | 2 | # class node to create a node for the queue linked list 3 | class Node : 4 | 5 | def __init__(self, val) : 6 | self.val = val 7 | self.next = None 8 | 9 | 10 | class Queue : 11 | 12 | # contructor of the queue class 13 | def __init__(self) : 14 | self.front = None 15 | self.rear = None 16 | 17 | 18 | # method to insert an element into the queue 19 | def insert(self, val) : 20 | new_node = Node(val) 21 | 22 | # if the front and rear pointer are null by default 23 | if self.rear is None and self.front is None : 24 | self.rear = new_node 25 | self.front = new_node 26 | 27 | # when there is already one more nodes or elements in the queue 28 | else : 29 | self.rear.next = new_node 30 | self.rear = new_node 31 | 32 | 33 | def traverse(self) : 34 | ptr = self.front 35 | if ptr is None : 36 | print('Queue is empty') 37 | return 38 | else : 39 | while ptr is not None : 40 | print(ptr.val, end = " ") 41 | ptr = ptr.next 42 | 43 | 44 | def delete(self) : 45 | ptr = self.front 46 | if ptr is None : 47 | print("queue is empty") 48 | return 49 | else : 50 | print(ptr.val) 51 | self.front = ptr.next 52 | del ptr 53 | 54 | 55 | if __name__ == '__main__' : 56 | queue = Queue() 57 | queue.insert(1) 58 | queue.insert(2) 59 | queue.insert(3) 60 | queue.delete() 61 | queue.delete() 62 | queue.delete() 63 | queue.delete() 64 | queue.traverse() -------------------------------------------------------------------------------- /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 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) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/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/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 | --------------------------------------------------------------------------------