├── .gitattributes ├── .gitignore ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── LICENSE.md ├── Low-level-design ├── amazon │ └── pizza-system-design │ │ └── pizza │ │ ├── HawaiianPizza.java │ │ ├── Main.java │ │ ├── MargheritaPizza.java │ │ ├── Order.java │ │ ├── Pizza.java │ │ ├── PizzaFactory.java │ │ ├── Topping.java │ │ └── VeggiePizza.java └── pizza-system-design │ └── pizza │ ├── HawaiianPizza.java │ ├── Main.java │ ├── MargheritaPizza.java │ ├── Order.java │ ├── Pizza.java │ ├── PizzaFactory.java │ ├── Topping.java │ └── VeggiePizza.java ├── README.md ├── algorithms ├── Readme.md ├── advanced │ ├── comp-scheduling.py │ ├── genetic.py │ ├── inversions.py │ └── propose_reject.py ├── levenshtein_distance.c ├── moores-voting-alorithm.cpp ├── search │ ├── binary.c │ ├── binary.cpp │ ├── linear.c │ ├── linear.cpp │ └── readme.md └── sort │ ├── Readme.md │ ├── bubble.c │ ├── bubble.cpp │ ├── merge.cpp │ ├── selection.c │ └── selection.cpp ├── assessments ├── CCQT_exam │ └── CCQT_exam_Program.c ├── TCS2018 │ ├── slot1.c │ ├── slot2 │ │ ├── slot2.c │ │ └── solution2.c │ └── slot3.c ├── TCS_MOCK │ └── code.c ├── amazon │ └── readme.md ├── cisco_oa.py └── readme.md ├── binary_search ├── binary_search.js ├── intersection_two_arrays2.js ├── perfect_sqr.js ├── power_function.js └── smallest_letter_greater_than_target.js ├── cryptography └── caesar-cipher │ ├── README.md │ ├── caesar-cipher.c │ └── caesar-cipher.py ├── data_structures ├── Readme.md ├── graphs │ ├── adjacency_list.py │ ├── adjacency_list_weighted.py │ ├── adjacency_matrix.py │ ├── smallest_str_with_swap.js │ └── traversal.py ├── heap │ ├── GFG │ │ └── cost_of_ropes.py.py │ ├── image-1.png │ ├── image.png │ ├── max_heap.py │ ├── min_heap.py │ └── readme.md ├── linked_list.c ├── linked_list │ ├── linked.cpp │ ├── node.py │ ├── odd_even.py │ ├── reverse_k_goup.py │ └── traversal.py ├── linked_list_custom.cpp ├── queue │ └── queue.py └── trees │ ├── Binary Tree Traversal │ ├── README.md │ ├── binary_search_tree.cpp │ ├── inorder.JPG │ ├── input.JPG │ ├── postorder.JPG │ ├── preorder-inorder-postorder.c │ ├── preorder.JPG │ └── prompt.JPG │ ├── __pycache__ │ └── node.cpython-310.pyc │ ├── binary_search_tree.py │ ├── depth_of_tree.py │ ├── max_min.py │ ├── node.py │ ├── root_sum_parent.py │ └── traversal.py ├── dynamic_programming ├── Readme.md ├── fibonacci.py └── sum_n.py ├── foobar ├── Level-1 │ └── braille_translation.py ├── Level-2 │ ├── bunny_worker_location.py │ └── power_hungry.py ├── Level-3 │ ├── bomb_baby.py │ ├── fuel-injection-perf.py │ └── queue_to_do.py ├── Level-4 │ └── running_with_bunnies.py └── readme.md ├── general ├── Day1 │ ├── Day 1 Coding.pdf │ ├── program1 │ │ └── p1.c │ ├── program2 │ │ └── p2.c │ └── program3 │ │ └── p3.c ├── Day2 │ └── code.c ├── findout │ └── code.c ├── odd_powers.py └── readme.md ├── geometric_algo ├── circle.c └── triangle.c ├── hackerrank ├── Readme.md ├── arrayrotation.cpp ├── between_sets.cpp └── clock_format.cpp ├── leetcode ├── Readme.md ├── SQL-50 │ ├── sql-584.sql │ └── sql-595.sql ├── adjacent_duplicates.cpp ├── adjacent_duplicates.py ├── adjacent_k_duplicates.py ├── bit-manipulation │ ├── problem_1680.py │ ├── problem_190.py │ ├── problem_191.py │ ├── problem_2220.py │ ├── problem_268.py │ ├── problem_29.py │ ├── problem_338.py │ └── problem_476.py ├── proble_881.py ├── problem_1.py ├── problem_100.py ├── problem_1002.py ├── problem_101.py ├── problem_102.py ├── problem_1022.py ├── problem_103.py ├── problem_104.py ├── problem_1051.py ├── problem_107.py ├── problem_1072.py ├── problem_108.py ├── problem_11.py ├── problem_110.py ├── problem_111.py ├── problem_112.py ├── problem_1122.py ├── problem_116.py ├── problem_118.py ├── problem_119.py ├── problem_1190.py ├── problem_12.py ├── problem_1200.py ├── problem_121.py ├── problem_122.py ├── problem_125.py ├── problem_128.py ├── problem_129.py ├── problem_1290.py ├── problem_13.py ├── problem_1302.py ├── problem_1310.py ├── problem_1318.py ├── problem_133.py ├── problem_1331.py ├── problem_1337.py ├── problem_1346.py ├── problem_135.py ├── problem_136.py ├── problem_1365.py ├── problem_1367.py ├── problem_1380.py ├── problem_1381.py ├── problem_14.py ├── problem_1400.py ├── problem_1404.py ├── problem_1408.py ├── problem_141.py ├── problem_142.py ├── problem_143.py ├── problem_144.py ├── problem_1442.py ├── problem_1448.py ├── problem_145.py ├── problem_1455.py ├── problem_146.py ├── problem_1460.py ├── problem_1464.py ├── problem_1475.py ├── problem_1480.py ├── problem_15.py ├── problem_1508.py ├── problem_151.py ├── problem_1512.py ├── problem_1514.py ├── problem_1518.py ├── problem_1530.py ├── problem_154.py ├── problem_1598.py ├── problem_16.py ├── problem_160.py ├── problem_1605.py ├── problem_1636.py ├── problem_1652.py ├── problem_167.py ├── problem_1684.py ├── problem_169.py ├── problem_1700.py ├── problem_1710.py ├── problem_1780.py ├── problem_179.py ├── problem_1791.py ├── problem_1792.py ├── problem_18.py ├── problem_1800.py ├── problem_1805.py ├── problem_1823.py ├── problem_1859.cpp ├── problem_189.py ├── problem_1894.py ├── problem_19.py ├── problem_191.py ├── problem_1937.py ├── problem_1945.py ├── problem_1961.py ├── problem_1963.py ├── problem_1971.java ├── problem_1971.py ├── problem_1980.py ├── problem_199.py ├── problem_2.py ├── problem_20.py ├── problem_200.py ├── problem_2006.py ├── problem_2016.py ├── problem_202.py ├── problem_2022.py ├── problem_2028.py ├── problem_203.py ├── problem_2037.py ├── problem_205.py ├── problem_2053.py ├── problem_2058.py ├── problem_206.py ├── problem_2064.py ├── problem_207.py ├── problem_2073.py ├── problem_209.py ├── problem_21.py ├── problem_2109.py ├── problem_215.py ├── problem_2161.py ├── problem_217.py ├── problem_2181.py ├── problem_2182.py ├── problem_2185.py ├── problem_219.py ├── problem_2196.py ├── problem_2220.py ├── problem_223.py ├── problem_2236.py ├── problem_225.py ├── problem_2255.py ├── problem_226.py ├── problem_2265.py ├── problem_23.py ├── problem_230.py ├── problem_232.py ├── problem_2331.py ├── problem_234.py ├── problem_235.py ├── problem_236.py ├── problem_237.py ├── problem_2373.py ├── problem_238.py ├── problem_2395.py ├── problem_24.py ├── problem_2415.py ├── problem_2418.py ├── problem_2419.py ├── problem_242.py ├── problem_2461.py ├── problem_2486.py ├── problem_2487.py ├── problem_2490.py ├── problem_2491.py ├── problem_25.py ├── problem_2500.py ├── problem_2516.py ├── problem_2554.py ├── problem_2558.py ├── problem_2559.py ├── problem_257.py ├── problem_2570.py ├── problem_2577.py ├── problem_2579.py ├── problem_258.py ├── problem_2582.py ├── problem_26.py ├── problem_260.py ├── problem_263.py ├── problem_264.py ├── problem_2640.py ├── problem_2678.py ├── problem_2696.py ├── problem_27.py ├── problem_273.py ├── problem_274.py ├── problem_28.py ├── problem_2816.py ├── problem_290.py ├── problem_2924.py ├── problem_295.py ├── problem_2965.py ├── problem_2974.py ├── problem_3.py ├── problem_3016.py ├── problem_303.py ├── problem_304.py ├── problem_3042.py ├── problem_3043.py ├── problem_3075.py ├── problem_3110.py ├── problem_3114.py ├── problem_3120.py ├── problem_3121.py ├── problem_3136.py ├── problem_3151.py ├── problem_3217.py ├── problem_3243.py ├── problem_3254.py ├── problem_3264.py ├── problem_328.py ├── problem_33.py ├── problem_338.py ├── problem_34.py ├── problem_344.py ├── problem_347.py ├── problem_35.py ├── problem_380.py ├── problem_383.py ├── problem_386.py ├── problem_387.py ├── problem_39.py ├── problem_392.py ├── problem_4.py ├── problem_40.py ├── problem_404.py ├── problem_409.py ├── problem_41.py ├── problem_42.py ├── problem_424.py ├── problem_432.py ├── problem_438.py ├── problem_442.py ├── problem_443.py ├── problem_445.py ├── problem_448.py ├── problem_451.py ├── problem_49.py ├── problem_5.py ├── problem_50.py ├── problem_506.py ├── problem_509.py ├── problem_513.py ├── problem_515.py ├── problem_523.py ├── problem_525.py ├── problem_53.py ├── problem_535.py ├── problem_539.py ├── problem_54.py ├── problem_543.py ├── problem_547.py ├── problem_55.py ├── problem_567.py ├── problem_572.py ├── problem_58.py ├── problem_590.py ├── problem_6.py ├── problem_61.py ├── problem_622.py ├── problem_624.py ├── problem_633.py ├── problem_648.py ├── problem_650.py ├── problem_658.py ├── problem_659.py ├── problem_66.py ├── problem_67.py ├── problem_69.py ├── problem_7.py ├── problem_70.py ├── problem_700.py ├── problem_701.py ├── problem_703.py ├── problem_704.py ├── problem_706.py ├── problem_719.py ├── problem_725.py ├── problem_729.py ├── problem_731.py ├── problem_733.py ├── problem_746.py ├── problem_75.py ├── problem_76.py ├── problem_771.py ├── problem_78.py ├── problem_783.py ├── problem_786.py ├── problem_796.py ├── problem_8.py ├── problem_80.py ├── problem_826.py ├── problem_83.py ├── problem_840.py ├── problem_846.py ├── problem_860.py ├── problem_874.py ├── problem_875.py ├── problem_876.py ├── problem_877.py ├── problem_88.py ├── problem_884.py ├── problem_885.py ├── problem_9.py ├── problem_901.py ├── problem_912.py ├── problem_916.py ├── problem_933.py ├── problem_938.py ├── problem_94.py ├── problem_945.py ├── problem_962.js ├── problem_974.py ├── problem_98.py ├── problem_99.py └── problem_997.py ├── linked_list ├── cycle_in_linked_list.js ├── detect_cycle_2.js ├── linked_list.js ├── odd_even.js └── reverse_linked_list.js ├── number_theory ├── GCD_HCF │ ├── gcd.c │ ├── gcd3.c │ └── gcdn.c ├── LCM_HCF │ ├── hcf.c │ └── lcm.c ├── armstrong.c ├── conversions │ ├── bin_oct.c │ ├── hex_bin.c │ ├── hex_dec.c │ └── oct_bin.c ├── palindrome.c ├── perfect.c ├── pow.c ├── readme.md ├── series │ ├── factorial.c │ ├── fibo.c │ ├── series.c │ └── sumprime.c ├── sqrt.c ├── squrt.c └── swap.c ├── package.json ├── patterns └── pattern_1.c ├── sorting ├── BubbleSort │ └── bubble.c ├── InsertionSort │ └── insertion_sort.js ├── MergeSort │ └── merge_sort.js ├── QuickSort │ └── quick_sort.js ├── SelectionSort │ ├── selection_sort.js │ ├── selection_sort.py │ └── sort.c └── readme.md ├── stack ├── min_stack.js └── valid_parentheses.js └── string_manipulation ├── Readme.md ├── StringReverse.c ├── camel.c ├── camel_cmd.c ├── caseinverse.c ├── eliminatevowels.c ├── lower.c ├── string_length.c ├── string_palindrome.c └── upper.c /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | !**/*.c 3 | !**/*.cpp 4 | *.out 5 | **/*.class 6 | **/*.iml 7 | *.exe 8 | !.gitignore 9 | **.pyc 10 | leetcode/problem_30.py 11 | leetcode/problem_36.py 12 | leetcode/problem_992.py 13 | **/__pycache__/* 14 | **/*.pyc -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/HawaiianPizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class HawaiianPizza extends Pizza { 4 | public HawaiianPizza(String size) { 5 | super(size, 10.0); 6 | } 7 | 8 | @Override 9 | protected double calculateBasePrice() { 10 | double price = basePrice; 11 | price += new Topping("Cheese", 1.0).getPrice(); 12 | price += new Topping("Ham", 1.5).getPrice(); 13 | price += new Topping("Pineapple", 1.2).getPrice(); 14 | return price; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/MargheritaPizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class MargheritaPizza extends Pizza { 4 | public MargheritaPizza(String size) { 5 | super(size, 8.0); 6 | } 7 | 8 | @Override 9 | protected double calculateBasePrice() { 10 | double price = basePrice; 11 | price += new Topping("Cheese", 1.0).getPrice(); 12 | price += new Topping("Tomato", 0.5).getPrice(); 13 | return price; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/Order.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | class Order { 6 | private List pizzas = new ArrayList<>(); 7 | 8 | public void addPizza(Pizza pizza) { 9 | pizzas.add(pizza); 10 | } 11 | 12 | public double calculateTotal() { 13 | return pizzas.stream().mapToDouble(Pizza::calculatePrice).sum(); 14 | } 15 | } -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/Pizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | abstract class Pizza { 6 | protected String size; 7 | protected double basePrice; 8 | protected List toppings = new ArrayList<>(); 9 | 10 | public Pizza(String size, double basePrice) { 11 | this.size = size; 12 | this.basePrice = basePrice; 13 | } 14 | 15 | public void addTopping(Topping topping) { 16 | toppings.add(topping); 17 | } 18 | 19 | protected abstract double calculateBasePrice(); 20 | 21 | public double calculatePrice() { 22 | double totalPrice = calculateBasePrice(); 23 | for (Topping topping : toppings) { 24 | totalPrice += topping.getPrice(); 25 | } 26 | return totalPrice; 27 | } 28 | } -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/PizzaFactory.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class PizzaFactory { 4 | public static Pizza createPizza(String pizzaType, String size) { 5 | switch (pizzaType) { 6 | case "Margherita": 7 | return new MargheritaPizza(size); 8 | case "Veggie": 9 | return new VeggiePizza(size); 10 | case "Hawaiian": 11 | return new HawaiianPizza(size); 12 | default: 13 | throw new IllegalArgumentException("Unknown pizza type: " + pizzaType); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/Topping.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class Topping { 4 | private String name; 5 | private double price; 6 | 7 | public Topping(String name, double price) { 8 | this.name = name; 9 | this.price = price; 10 | } 11 | 12 | public double getPrice() { 13 | return price; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | } -------------------------------------------------------------------------------- /Low-level-design/amazon/pizza-system-design/pizza/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class VeggiePizza extends Pizza { 4 | public VeggiePizza(String size) { 5 | super(size, 9.0); 6 | } 7 | 8 | @Override 9 | protected double calculateBasePrice() { 10 | double price = basePrice; 11 | price += new Topping("Cheese", 1.0).getPrice(); 12 | price += new Topping("Bell Peppers", 0.8).getPrice(); 13 | price += new Topping("Olives", 0.6).getPrice(); 14 | return price; 15 | } 16 | } -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/HawaiianPizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class HawaiianPizza extends Pizza { 4 | public HawaiianPizza(String size) { 5 | super(size, 10.0); 6 | } 7 | 8 | @Override 9 | protected double calculateBasePrice() { 10 | double price = basePrice; 11 | price += new Topping("Cheese", 1.0).getPrice(); 12 | price += new Topping("Ham", 1.5).getPrice(); 13 | price += new Topping("Pineapple", 1.2).getPrice(); 14 | return price; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/MargheritaPizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class MargheritaPizza extends Pizza { 4 | public MargheritaPizza(String size) { 5 | super(size, 8.0); 6 | } 7 | 8 | @Override 9 | protected double calculateBasePrice() { 10 | double price = basePrice; 11 | price += new Topping("Cheese", 1.0).getPrice(); 12 | price += new Topping("Tomato", 0.5).getPrice(); 13 | return price; 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/Order.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | class Order { 6 | private List pizzas = new ArrayList<>(); 7 | 8 | public void addPizza(Pizza pizza) { 9 | pizzas.add(pizza); 10 | } 11 | 12 | public double calculateTotal() { 13 | return pizzas.stream().mapToDouble(Pizza::calculatePrice).sum(); 14 | } 15 | } -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/Pizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | import java.util.ArrayList; 3 | import java.util.List; 4 | 5 | abstract class Pizza { 6 | protected String size; 7 | protected double basePrice; 8 | protected List toppings = new ArrayList<>(); 9 | 10 | public Pizza(String size, double basePrice) { 11 | this.size = size; 12 | this.basePrice = basePrice; 13 | } 14 | 15 | public void addTopping(Topping topping) { 16 | toppings.add(topping); 17 | } 18 | 19 | protected abstract double calculateBasePrice(); 20 | 21 | public double calculatePrice() { 22 | double totalPrice = calculateBasePrice(); 23 | for (Topping topping : toppings) { 24 | totalPrice += topping.getPrice(); 25 | } 26 | return totalPrice; 27 | } 28 | } -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/PizzaFactory.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class PizzaFactory { 4 | public static Pizza createPizza(String pizzaType, String size) { 5 | switch (pizzaType) { 6 | case "Margherita": 7 | return new MargheritaPizza(size); 8 | case "Veggie": 9 | return new VeggiePizza(size); 10 | case "Hawaiian": 11 | return new HawaiianPizza(size); 12 | default: 13 | throw new IllegalArgumentException("Unknown pizza type: " + pizzaType); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/Topping.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class Topping { 4 | private String name; 5 | private double price; 6 | 7 | public Topping(String name, double price) { 8 | this.name = name; 9 | this.price = price; 10 | } 11 | 12 | public double getPrice() { 13 | return price; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | } -------------------------------------------------------------------------------- /Low-level-design/pizza-system-design/pizza/VeggiePizza.java: -------------------------------------------------------------------------------- 1 | package pizza; 2 | 3 | class VeggiePizza extends Pizza { 4 | public VeggiePizza(String size) { 5 | super(size, 9.0); 6 | } 7 | 8 | @Override 9 | protected double calculateBasePrice() { 10 | double price = basePrice; 11 | price += new Topping("Cheese", 1.0).getPrice(); 12 | price += new Topping("Bell Peppers", 0.8).getPrice(); 13 | price += new Topping("Olives", 0.6).getPrice(); 14 | return price; 15 | } 16 | } -------------------------------------------------------------------------------- /algorithms/moores-voting-alorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int majority_element(int arr[], int n) 5 | { 6 | int cnt = 1, index = 0; 7 | for(int i=1;i n/2) { 35 | cout<<"Majority Element is "< 2 | int main(int argc,char *argv[]){ 3 | if(argc==1) 4 | return 0; 5 | int n = atoi(argv[1]); 6 | int i=2; 7 | while(i 8 | 9 | int search(int x, int arr[], int size){ 10 | for(int i=0;i 2 | 3 | void swap(int *a,int *b){ 4 | int c = *a; 5 | *a = *b; 6 | *b = c; 7 | } 8 | 9 | int main(int argc,char *argv[]){ 10 | if(argc==1) 11 | return 0; 12 | int arr[argc-1]; 13 | int i =0; 14 | int n=argc-1,j=0; 15 | 16 | for(i=0;iarr[j+1]){ 23 | swap(&arr[j],&arr[j+1]); 24 | } 25 | } 26 | } 27 | 28 | for(i=0;i 2 | 3 | int main(int argc,char *argv[]){ 4 | // printf("%c",argv[1][1]); 5 | int n=sizeof(argv[1])/2; 6 | char arr[n]; 7 | // printf("%d",sizeof(argv[1])); 8 | int k=0; 9 | for(int i=0;i 7 | 8 | int main() 9 | { 10 | int n; 11 | int sum=0; 12 | scanf("%d",&n); 13 | label: 14 | if(n!=0){ 15 | int temp = n%10; 16 | n = n /10; 17 | sum += temp; 18 | } 19 | if(sum >= 10 && n==0){ 20 | n=sum; 21 | sum=0; 22 | goto label; 23 | } 24 | if(sum <10 && n!=0){ 25 | goto label; 26 | } 27 | if(sum<10 && n==0){ 28 | goto lab; 29 | } 30 | goto label; 31 | lab: 32 | printf("sum = %d",sum); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /assessments/TCS2018/slot1.c: -------------------------------------------------------------------------------- 1 | /* 2 | For the Sequence:- 3 | 1 1 2 3 4 9 8 27 4 | find the nth term 5 | */ 6 | #include 7 | 8 | int power(int n,int p){ 9 | int out=1; 10 | 11 | for(int i=1;i<=p;i++){ 12 | out=out*n; 13 | //printf("%d\n",x); 14 | } 15 | return out; 16 | } 17 | 18 | int main(int argc,char *argv){ 19 | 20 | int n; 21 | scanf("%d",&n); 22 | 23 | int out; 24 | int num; 25 | 26 | if(n%2==0){ 27 | num = 3; 28 | int p =(n-1)/2; 29 | out = power(num,p); 30 | 31 | }else{ 32 | num = 2; 33 | int p =n/2; 34 | out = power(num,p); 35 | } 36 | printf("%d\n",out); 37 | printf("4^3=%d\n",power(2,3) ); 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /assessments/TCS2018/slot2/slot2.c: -------------------------------------------------------------------------------- 1 | /* 2 | Find the Nth Term of the Sequence 3 | 0 0 2 1 4 2 6 3 4 | Using:- 5 | Tn = a + (n-1)d 6 | here a=0; 7 | */ 8 | #include 9 | 10 | int main(){ 11 | int n,d1=2,d2 =1; 12 | scanf("%d",&n); 13 | int tn=0; 14 | if (n%2==0) 15 | { n=n/2; //it Gives n = 1,2,3 for even numbers 2,4,5,7 16 | tn= (n-1)*d2; 17 | 18 | }else{ 19 | n=1+n/2; //it Gives n = 1,2,3,4 for odd numbers 1,3,5,7 20 | tn= (n-1)*d1; 21 | } 22 | 23 | printf("Nth term =%d\n",tn); 24 | 25 | 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /assessments/TCS2018/slot2/solution2.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int main() 5 | { 6 | int n; 7 | scanf("%d",&n); 8 | if(n<2){ 9 | int k=0; 10 | printf("%d",k); 11 | } 12 | else{ 13 | if(n%2==0){ 14 | int k=(n-2)/2; 15 | printf("%d",k); 16 | } 17 | else{ 18 | printf("%d",n-1); 19 | } 20 | 21 | } 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /assessments/TCS_MOCK/code.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 1000 3 | 4 | void fibonacci(int n); 5 | void prime(int n); 6 | 7 | int main(){ 8 | int n; 9 | printf("Enter The No of the Term to Find In the Series\n"); 10 | scanf("%d",&n); 11 | 12 | if(n%2==0){ 13 | prime(n/2); 14 | 15 | }else{ 16 | fibonacci(n/2+1); 17 | } 18 | 19 | return 0; 20 | } 21 | 22 | void fibonacci(int n){ 23 | int t1=1,t2=1,term=1; 24 | 25 | for(int i=2;i a - b); 8 | nums2.sort((a, b) => a - b); 9 | 10 | let r = []; 11 | let i = 0, j = 0; 12 | while (i < nums1.length && j < nums2.length) { 13 | if (nums1[i] === nums2[j]) { 14 | r.push(nums1[i]); 15 | i++; 16 | j++; 17 | } else if (nums1[i] < nums2[j]) { 18 | i++; 19 | } else if (nums1[i] > nums2[j]) { 20 | j++; 21 | } 22 | } 23 | 24 | return r; 25 | }; 26 | 27 | console.log(intersect([1, 2, 2, 1], [2, 2])); -------------------------------------------------------------------------------- /binary_search/perfect_sqr.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Valid Perfect Square 3 | * https://leetcode.com/explore/learn/card/binary-search/137/conclusion/978/ 4 | * @param {number} num 5 | * @return {boolean} returns true if the number is perfect square 6 | */ 7 | var isPerfectSquare = function (num) { 8 | let left = 0, right = num; 9 | 10 | while (left <= right) { 11 | let mid = left + Math.floor((right - left) / 2); 12 | let numSqr = mid * mid; 13 | if (numSqr === num) { 14 | return true; 15 | } else if (numSqr < num) { 16 | left = mid + 1; 17 | } else { 18 | right = mid - 1; 19 | } 20 | 21 | } 22 | return false; 23 | }; 24 | 25 | console.log(isPerfectSquare(16)) // TRUE 26 | console.log(isPerfectSquare(10)) // FALSE -------------------------------------------------------------------------------- /binary_search/power_function.js: -------------------------------------------------------------------------------- 1 | function power(num, pow) { 2 | num = pow < 0 ? 1 / num : num; 3 | let result = 1; 4 | for(let i=0;i< Math.abs(pow);i++) { 5 | result = result * num; 6 | } 7 | return result; 8 | } 9 | console.log(power(2,-2)); 10 | console.log(1/2 * 1/2); -------------------------------------------------------------------------------- /binary_search/smallest_letter_greater_than_target.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {character[]} letters 3 | * @param {character} target 4 | * @return {character} 5 | */ 6 | var nextGreatestLetter = function (letters, target) { 7 | let left = 0, right = letters.length - 1; 8 | while (left <= right) { 9 | let mid = left + Math.floor((right - left) / 2); 10 | 11 | if (letters[mid] <= target) { 12 | left = mid + 1; 13 | } else { 14 | right = mid - 1; 15 | } 16 | } 17 | return letters[left % letters.length]; 18 | }; 19 | 20 | console.log(nextGreatestLetter(["c", "f", "j"], "a")); 21 | console.log(nextGreatestLetter(['a', 'b'], "z")); 22 | console.log(nextGreatestLetter(["c", "f", "j"], "c")); -------------------------------------------------------------------------------- /cryptography/caesar-cipher/README.md: -------------------------------------------------------------------------------- 1 |

Caesar Cipher

2 | 3 | 4 | ```sh 5 | 6 | Input Order : 7 | 8 | String Length (Int) 9 | String (char*) 10 | Cipher Value (Int) 11 | 12 | Input : 13 | 14 | 11 15 | ammj-igb 16 | 2 17 | 18 | Output: 19 | 20 | cool-kid 21 | 22 | ``` 23 | -------------------------------------------------------------------------------- /cryptography/caesar-cipher/caesar-cipher.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | int n; 6 | printf("Enter Input String Length: "); 7 | scanf("%d",&n); 8 | char upper[26]; 9 | char lower[26]; 10 | for(int i=0,m=65,l=97; i<26; i++){ 11 | upper[i] = m++; 12 | lower[i] = l++; 13 | } 14 | char* s = (char *)malloc(10240000 * sizeof(char)); 15 | printf("Enter Input String: "); 16 | scanf("%s",s); 17 | int k; 18 | printf("Enter Key: "); 19 | scanf("%d",&k); 20 | for(int i=0; i<=n; i++){ 21 | if(s[i]>=65 && s[i]<=90){ 22 | int d = s[i] - 65; 23 | int rot = (d + k) % 26 ; 24 | s[i] = 65 + rot; 25 | 26 | } 27 | else if(s[i]>=97 && s[i]<=122){ 28 | int d = s[i] - 97; 29 | int rot = (d + k) % 26; 30 | s[i] = 97 + rot; 31 | } 32 | } 33 | printf("Output %s",s); 34 | return 0; 35 | } 36 | 37 | /* 38 | 39 | Input 40 | 41 | 11 42 | ammj-igb 43 | 2 44 | 45 | Output 46 | cool-kid 47 | 48 | */ 49 | -------------------------------------------------------------------------------- /cryptography/caesar-cipher/caesar-cipher.py: -------------------------------------------------------------------------------- 1 | def encrypt(string, shift): 2 | 3 | cipher = '' 4 | for char in string: 5 | if char == ' ': 6 | cipher = cipher + char 7 | elif char.isupper(): 8 | cipher = cipher + chr((ord(char) + shift - 65) % 26 + 65) 9 | else: 10 | cipher = cipher + chr((ord(char) + shift - 97) % 26 + 97) 11 | 12 | return cipher 13 | 14 | text = input("enter string: ") 15 | s = int(input("enter shift number: ")) 16 | print("original string: ", text) 17 | print("after encryption: ", encrypt(text, s)) 18 | -------------------------------------------------------------------------------- /data_structures/heap/GFG/cost_of_ropes.py.py: -------------------------------------------------------------------------------- 1 | ### Minimum Cost of Ropes: https://www.geeksforgeeks.org/problems/minimum-cost-of-ropes-1587115620/1 2 | 3 | class Solution: 4 | #Function to return the minimum cost of connecting the ropes. 5 | def minCost(self,arr,n) : 6 | cost = 0 7 | heapq.heapify(arr) 8 | while(len(arr) > 1): 9 | popped = (heapq.heappop(arr) + heapq.heappop(arr)) 10 | cost += popped 11 | heapq.heappush(arr, popped) 12 | return cost 13 | -------------------------------------------------------------------------------- /data_structures/heap/image-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/heap/image-1.png -------------------------------------------------------------------------------- /data_structures/heap/image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/heap/image.png -------------------------------------------------------------------------------- /data_structures/linked_list/node.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data, next = None): 3 | self.data = data 4 | self.next = next 5 | 6 | def hasNext(self): 7 | return self.next != None 8 | -------------------------------------------------------------------------------- /data_structures/trees/Binary Tree Traversal/inorder.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/trees/Binary Tree Traversal/inorder.JPG -------------------------------------------------------------------------------- /data_structures/trees/Binary Tree Traversal/input.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/trees/Binary Tree Traversal/input.JPG -------------------------------------------------------------------------------- /data_structures/trees/Binary Tree Traversal/postorder.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/trees/Binary Tree Traversal/postorder.JPG -------------------------------------------------------------------------------- /data_structures/trees/Binary Tree Traversal/preorder.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/trees/Binary Tree Traversal/preorder.JPG -------------------------------------------------------------------------------- /data_structures/trees/Binary Tree Traversal/prompt.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/trees/Binary Tree Traversal/prompt.JPG -------------------------------------------------------------------------------- /data_structures/trees/__pycache__/node.cpython-310.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/data_structures/trees/__pycache__/node.cpython-310.pyc -------------------------------------------------------------------------------- /data_structures/trees/node.py: -------------------------------------------------------------------------------- 1 | # Define a class Node with data, left, and right attributes. 2 | class Node: 3 | def __init__(self, data): 4 | self.data = data 5 | self.left = None 6 | self.right = None 7 | 8 | def hasChild(self): 9 | return self.left != None or self.right != None 10 | def hasLeftChild(self): 11 | return self.left != None 12 | 13 | def hasRightChild(self): 14 | return self.right != None 15 | 16 | -------------------------------------------------------------------------------- /data_structures/trees/root_sum_parent.py: -------------------------------------------------------------------------------- 1 | ### Problem from Geeks for Geeks 2 | ### https://www.geeksforgeeks.org/problems/children-sum-parent/1 3 | class Solution: 4 | #Function to check whether all nodes of a tree have the value 5 | #equal to the sum of their child nodes. 6 | def isSumProperty(self, root): 7 | 8 | if(root is None or (root.left is None and root.right is None)): 9 | return 1 10 | left_sum = 0 11 | right_sum = 0 12 | if(root.left): 13 | left_sum = root.left.data 14 | if(root.right): 15 | right_sum = root.right.data 16 | if((root.data == left_sum + right_sum) and self.isSumProperty(root.left) and self.isSumProperty(root.right)): 17 | return 1 18 | else: 19 | return 0 -------------------------------------------------------------------------------- /dynamic_programming/sum_n.py: -------------------------------------------------------------------------------- 1 | # Given n as input find the sum of all numbers from 1 to n 2 | 3 | ### Topic: Dynamic Programming 4 | # f(1) => 1 5 | # f(2) => 1 + 2 = 3 = f(1) + 2 6 | # f(3) => 1 + 2 + 3 = 6 = f(2) + 3 7 | # f(4) => 1 + 2 + 3 + 4 = 10 = f(3) + 4 8 | def sum_n(n): 9 | if(n == 1): 10 | return 1 11 | return sum_n(n-1) + n 12 | 13 | # The Issue with above approach is we are recalculating the sum of all numbers from 1 to n-1 multiple times. So we can use memoization to store the result of sum of all numbers from 1 to n-1 and use it to calculate sum of all numbers from 1 to n in O(n) time complexity. 14 | def sum_n(n): 15 | if(n == 1): 16 | return 1 17 | dp = [0]*(n+1) 18 | dp[1] = 1 19 | for i in range(2, n+1): 20 | dp[i] = dp[i-1] + i 21 | return dp[n] 22 | 23 | 24 | print(sum_n(4)) # 10 25 | 26 | -------------------------------------------------------------------------------- /foobar/Level-2/bunny_worker_location.py: -------------------------------------------------------------------------------- 1 | def solution(x, y): 2 | row = 1 3 | col = 0 4 | column_count = x + y + 1 5 | rows = [] 6 | row_inc = 1 7 | row_result = 0 8 | 9 | # Traverse first row until 10 | for i in range(1, column_count): 11 | row_result += row_inc 12 | row_inc+=1 13 | col += 1 14 | print("result={0} at ({1},{2})".format(row_result, row, col)) 15 | 16 | # Traverse up along the column until target row is reached 17 | while(row != y): 18 | col -= 1 19 | row += 1 20 | row_result -=1 21 | print("result={0} at ({1},{2})".format(row_result, row, col)) 22 | 23 | row_inc -=1 24 | 25 | # Traverse back along the row until target column is reached 26 | while(col != x): 27 | col -= 1 28 | row_result -= row_inc 29 | row_inc -=1 30 | if(row == y and col == x): 31 | break; 32 | 33 | return row_result; 34 | 35 | print(solution(6,4)) -------------------------------------------------------------------------------- /foobar/Level-2/power_hungry.py: -------------------------------------------------------------------------------- 1 | def solution(xs): 2 | negatives = [] 3 | # if odd number of negatives remove negative(max) 4 | for number in xs: 5 | if(number<0): 6 | negatives.append(number) 7 | if(len(negatives) %2 != 0 and len(xs) > 1): 8 | to_remove = max(negatives) 9 | xs.remove(to_remove) 10 | 11 | max_prod = xs[0] 12 | min_prod = xs[0] 13 | 14 | result = max_prod 15 | for i in range(1, len(xs)): 16 | if xs[i] == 0: 17 | if result < 0: 18 | result = 0 19 | pass 20 | else: 21 | max_result = max_prod * xs[i] 22 | min_result = min_prod * xs[i] 23 | max_prod = max(min_result, max(max_result, xs[i])) 24 | min_prod = min(max_result, min(min_result, xs[i])) 25 | result = max(result, max(max_prod, min_prod)) 26 | return str(result) -------------------------------------------------------------------------------- /foobar/Level-3/bomb_baby.py: -------------------------------------------------------------------------------- 1 | def solution(x, y): 2 | m, f = int(x), int(y) 3 | generations = 0 4 | while m > 0 or f > 0: 5 | if m < 1 or f < 1: 6 | break 7 | if(m == 1 and f ==1 ): 8 | return str(generations) 9 | if(m > f): 10 | if(f > 1): 11 | division = m//f 12 | m = m - f * (division) 13 | generations += division 14 | else: 15 | m = m - f 16 | generations +=1 17 | else: 18 | if(m > 1): 19 | division = f//m 20 | f = f - m * (division) 21 | generations += division 22 | else: 23 | f = f - m 24 | generations +=1 25 | if( m==1 and f ==1): 26 | return str(generations) 27 | else: 28 | return "impossible" 29 | 30 | print(solution("2","1")) 31 | 32 | -------------------------------------------------------------------------------- /foobar/Level-3/fuel-injection-perf.py: -------------------------------------------------------------------------------- 1 | def solution(x): 2 | count = 0 3 | n = int(x) 4 | while(n!=1): 5 | if(isEven(n)): 6 | n = n // 2 7 | else: 8 | # handle case for n = 3 since 3-1 = 2 and 3-2 = 1 9 | # 2 & 1 = 0 and 4 & 3 = 0 10 | if ((n+1 & n) > (n-1 & n-2) or (n == 3)): 11 | n = n-1 12 | else: 13 | n = n + 1 14 | count +=1 15 | return count 16 | 17 | def isEven(n): 18 | return n % 2 ==0 -------------------------------------------------------------------------------- /foobar/Level-3/queue_to_do.py: -------------------------------------------------------------------------------- 1 | # 0: 0, 3, 7, 11, 15 2 | # 1: 1, 5, 9, 13, 3 | # n+1: 2, 6, 10, 14, 18 4 | # n: 4, 8, 12, 16, 20 5 | def xor_n(x): 6 | if(x % 4 == 0): 7 | return x 8 | elif((x - 1) % 4 == 0): 9 | return 1 10 | elif((x - 2) % 4 == 0): 11 | return x+1 12 | else: 13 | return 0 14 | 15 | def solution(start, length): 16 | result = 0 17 | col = length-1 18 | for i in range(length, 0, -1): # 4, 3 19 | end = start + col 20 | result ^= (xor_n(start-1) ^ xor_n(end)) 21 | col -=1 22 | start = start+length 23 | return result -------------------------------------------------------------------------------- /foobar/Level-4/running_with_bunnies.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/foobar/Level-4/running_with_bunnies.py -------------------------------------------------------------------------------- /general/Day1/Day 1 Coding.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/saurabh47/Data-structures-and-algorithms/5aa3aa802ba3d41312fa05972a2e05bb3379be84/general/Day1/Day 1 Coding.pdf -------------------------------------------------------------------------------- /general/Day1/program2/p2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int strlength(char *ptr){ 5 | int count=0; 6 | while(*ptr!='\0'){ 7 | count++; 8 | ptr++; 9 | } 10 | return count; 11 | } 12 | 13 | int main(int argc,char *argv[]){ 14 | int index=0; 15 | if(argc!=3){ 16 | printf("Error"); 17 | }else{ 18 | //int s = atoi(argv[2][0]); 19 | char *out; 20 | int l1 = strlength(argv[1]); 21 | int l2 = strlength(argv[2]); 22 | 23 | //printf("%d\n",strlength(argv[1])); 24 | 25 | out = (char*)malloc(l1*sizeof(char)); 26 | //printf("\nLength of str1=%d str2=%d\n",l1,l2); 27 | for(int i=0;i 2 | 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc==1) 6 | return 0; 7 | int i=0,j=0,l=0,k=0; 8 | 9 | while(argv[1][i]!='\0'){ 10 | l++; 11 | i++; 12 | } 13 | char out[l]; 14 | //printf("Length =%d %s\n",l,argv[1]); 15 | for(j=l-1;j>=1;j--){ 16 | char s = argv[1][j]; 17 | int flag =1; 18 | for(i=j-1;i>=0;i--){ 19 | if(s==argv[1][i]){ 20 | flag =0; 21 | break; 22 | } 23 | } 24 | if(flag){ 25 | //printf("c=%c\n",argv[1][j] ); 26 | out[k]=argv[1][j]; 27 | k++; 28 | } 29 | } 30 | out[k]=argv[1][0]; 31 | 32 | while(k>=0){ 33 | printf("%c",out[k]); 34 | k--; 35 | } 36 | printf("\n"); 37 | return 0; 38 | } -------------------------------------------------------------------------------- /general/findout/code.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | 5 | int b= (0,5); 6 | printf("%d\n",b ); 7 | return 0; 8 | } -------------------------------------------------------------------------------- /general/odd_powers.py: -------------------------------------------------------------------------------- 1 | # Given an integer variable n, find the first n odd powers of 3. 2 | # eg: if n=3, output -> {3, 27, 243}. 3 | 4 | class Solution: 5 | def powerOf(self, n:int, k:int): 6 | result = 1; 7 | while(k > 0): 8 | if(k & 1): 9 | result = result*n 10 | n = n*n 11 | k = k >> 1 12 | return result; 13 | 14 | def findNOddPowers(self, n: int): 15 | result = [] 16 | k = 1 17 | for i in range(n): 18 | result.append(self.powerOf(3,k)); 19 | k+=2 20 | return result 21 | 22 | 23 | if __name__ == '__main__': 24 | solution = Solution() 25 | print(solution.findNOddPowers(5)) 26 | 27 | ### Output 28 | # mahesh@Maheshs-MacBook-Air-M1 bit-manipulation % python3 odd_powers.py 29 | # [3, 27, 243, 2187, 19683] 30 | -------------------------------------------------------------------------------- /general/readme.md: -------------------------------------------------------------------------------- 1 | ### General 2 | 3 | -------------------------------------------------------------------------------- /geometric_algo/circle.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define PI 3.14 3 | int main(int argc,int *argv[]){ 4 | 5 | if(argc==1){ 6 | printf("Error\n"); 7 | return 0; 8 | } 9 | 10 | int r = atoi(argv[1]); 11 | 12 | float area = (float) PI*r*r; 13 | 14 | printf("Area of Circle is %.2f\n",area); 15 | 16 | return 0; 17 | 18 | } -------------------------------------------------------------------------------- /geometric_algo/triangle.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc !=3){ 6 | printf("Error\n"); 7 | return 0; 8 | } 9 | 10 | int b = atoi(argv[1]); 11 | int h = atoi(argv[2]); 12 | float area = (float) (0.5)*b*h; 13 | 14 | printf("Area of Triangle is %.2f\n",area); 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /hackerrank/Readme.md: -------------------------------------------------------------------------------- 1 | ## HackerRank problems 2 | 3 | #### [ArrayRotation](https://www.hackerrank.com/challenges/circular-array-rotation/problem) 4 | 5 | ``` 6 | Given a vector array (A) and a rotation count(k) rotate the array K times,where rotation indicates shifting each element ofthe array 1 digit right, so after k rotationsgiven an index the program should return the element at that index (from the resulting array) 7 | ``` -------------------------------------------------------------------------------- /leetcode/SQL-50/sql-584.sql: -------------------------------------------------------------------------------- 1 | -- Solution 1 2 | SELECT name 3 | FROM Customer 4 | WHERE ISNULL(referee_id) OR referee_id <> 2 5 | 6 | 7 | -- Solution 2 8 | 9 | -- The coalesce allows you to provide a default or fallback value when NULL values are encountered in the data. 10 | 11 | SELECT name 12 | FROM Customer 13 | WHERE COALESCE(referee_id, 0) <> 2 -------------------------------------------------------------------------------- /leetcode/SQL-50/sql-595.sql: -------------------------------------------------------------------------------- 1 | # Write your MySQL query statement below 2 | 3 | SELECT name, population, area 4 | FROM World 5 | WHERE area >= 3000000 OR population >= 25000000; -------------------------------------------------------------------------------- /leetcode/adjacent_duplicates.py: -------------------------------------------------------------------------------- 1 | # Problem: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string/ 2 | 3 | class Solution: 4 | def removeDuplicates(self, s: str) -> str: 5 | stack = [] 6 | for letter in s: 7 | if(len(stack) != 0): 8 | top = stack[-1] 9 | if letter == top: 10 | stack.pop() 11 | else: 12 | stack.append(letter) 13 | else: 14 | stack.append(letter) 15 | result = "".join(stack); 16 | return result; 17 | 18 | if __name__ == '__main__': 19 | s = Solution(); 20 | result = s.removeDuplicates('azxxzy'); 21 | print(result); 22 | result = s.removeDuplicates('aabccba'); 23 | print(result); 24 | result = s.removeDuplicates('aacbcca'); 25 | print(result); 26 | 27 | ### output 28 | # mahesh@Maheshs-MacBook-Air-M1 leetcode % python3 adjacent_duplicates.py 29 | # ay 30 | # a 31 | # cba 32 | # mahesh@Maheshs-MacBook-Air-M1 leetcode % -------------------------------------------------------------------------------- /leetcode/adjacent_k_duplicates.py: -------------------------------------------------------------------------------- 1 | # problem statement: https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/description/ 2 | 3 | class Solution: 4 | def removeDuplicates(self, s: str, k: int) -> str: 5 | result = [] 6 | for letter in s: 7 | if len(result) == 0 or result[-1][0] != letter: 8 | result.append((letter,1)) 9 | else: 10 | key = result[-1][0] 11 | value = result[-1][1] 12 | result.append((key,value+1)) 13 | result.pop(-2) 14 | 15 | if(result[-1][1] == k): 16 | result.pop(-1) 17 | print(result); 18 | 19 | result_string =''; 20 | for key,value in result: 21 | result_string+=key*value 22 | return result_string 23 | 24 | if __name__ == '__main__': 25 | s = Solution(); 26 | result = s.removeDuplicates('ybggbbbbgssssgthyyyy',4); #ybth 27 | print(result); 28 | result = s.removeDuplicates('iiiixxxxxiiccccczzffffflllllllllfffffllyyyyyuuuuuz',5);#izzlz 29 | print(result); -------------------------------------------------------------------------------- /leetcode/bit-manipulation/problem_190.py: -------------------------------------------------------------------------------- 1 | # Problem 190. Reverse Bits (Easy) - https://leetcode.com/problems/reverse-bits/ 2 | class Solution: 3 | def reverseBits(self, n: int) -> int: 4 | reverse = 0 5 | count = 0 6 | while(count < 32): 7 | # left shift reverse by 1 bit 8 | reverse = reverse << 1; 9 | # add lsb of n to reverse using Bitwise OR 10 | reverse = reverse | (n & 1); 11 | # divide n by 2 using Bitwise right shift 12 | n = n >> 1 ; 13 | count += 1 14 | return reverse 15 | 16 | 17 | if __name__ == "__main__": 18 | solution = Solution() 19 | n = 43261596 20 | print(solution.reverseBits(n)) 21 | 22 | # output 23 | 24 | # mahesh@Maheshs-MacBook-Air-M1 bit-manipulation % python3 problem_190.py 25 | # 964176192 26 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/problem_191.py: -------------------------------------------------------------------------------- 1 | # Problem 191: Number of 1 Bits (Easy): https://leetcode.com/problems/number-of-1-bits/ 2 | 3 | class Solution: 4 | def hammingWeight(self, n: int) -> int: 5 | count = 0 6 | while(n!=0): 7 | # if number is odd bitwise AND is 1 8 | if(n & 1 == 1): 9 | count+=1 10 | # right shift by k (here k=1) divides by 2^k 11 | n = n >> 1 12 | return count 13 | 14 | 15 | if __name__ == '__main__': 16 | solution = Solution() 17 | binary = input("Enter a binary number:") 18 | print(solution.hammingWeight(int(binary,2))) 19 | 20 | ### output 21 | # Enter a binary number:00000000101 22 | # 2 23 | # mahesh@Maheshs-MacBook-Air-M1 bit-manipulation % python3 problem1.py 24 | # Enter a binary number:00000000000110101011 25 | # 6 26 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/problem_2220.py: -------------------------------------------------------------------------------- 1 | # Problem 2220. Minimum Bit Flips to Convert Number (Easy): https://leetcode.com/problems/minimum-bit-flips-to-convert-number/description/ 2 | 3 | class Solution: 4 | def minBitFlips(self, start: int, goal: int) -> int: 5 | # XOR of two numbers will give 1 if the bits are different 6 | # XOR start and goal, and count the number of 1s 7 | target = start ^ goal; 8 | count = 0 9 | while(target!=0): 10 | # if number is odd, it means the last bit is 1 11 | if(target & 1 == 1): 12 | count += 1 13 | target = target >> 1 14 | return count 15 | 16 | if __name__ == '__main__': 17 | solution = Solution() 18 | print(solution.minBitFlips(2, 6)) # 1 19 | print(solution.minBitFlips(4, 7)) # 2 20 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/problem_268.py: -------------------------------------------------------------------------------- 1 | # Problem 268. Missing Number (Easy): https://leetcode.com/problems/missing-number/ 2 | from pyparsing import List 3 | 4 | class Solution: 5 | def missingNumber(self, nums: List[int]) -> int: 6 | length = len(nums); 7 | sum_exp = (length * (length+1)) >> 1 8 | sum_act=0 9 | for i in range(length): 10 | sum_act +=nums[i] 11 | return int(sum_exp - sum_act); 12 | 13 | 14 | if __name__ == '__main__': 15 | solution = Solution() 16 | print(solution.missingNumber([3,0,1])) 17 | print(solution.missingNumber([0,1])) 18 | print(solution.missingNumber([9,6,4,2,3,5,7,0,1])) 19 | 20 | ### output 21 | # mahesh@Maheshs-MacBook-Air-M1 bit-manipulation % python3 problem_268.py 22 | # 2 23 | # 2 24 | # 8 25 | 26 | -------------------------------------------------------------------------------- /leetcode/bit-manipulation/problem_476.py: -------------------------------------------------------------------------------- 1 | ### Problem 476. Number Complement (Easy): https://leetcode.com/problems/number-complement/ 2 | ### tags: bit manipulation, easy 3 | 4 | # hint: mask to flip one digit at a time using XOR (^) 5 | # << num to keep track of the number of bits to flip 6 | class Solution: 7 | def findComplement(self, num: int) -> int: 8 | mask = 1 9 | result = 0 10 | init = False 11 | while(num > 0): 12 | if(not init): 13 | result = num ^ mask 14 | init = True 15 | else: 16 | result = result ^ mask 17 | num >>= 1 18 | mask <<= 1 19 | return result 20 | # 0 0 0 0 0 21 | # 0 0 1 0 1 -------------------------------------------------------------------------------- /leetcode/proble_881.py: -------------------------------------------------------------------------------- 1 | ### Problem 881. Boats to Save People (Medium): https://leetcode.com/problems/boats-to-save-people/ 2 | class Solution: 3 | def numRescueBoats(self, people: List[int], limit: int) -> int: 4 | folks = sorted(people) 5 | start = 0 6 | end = len(folks) - 1 7 | boats = 0 8 | # [1, 2, 2, 3] 9 | # [3, 3, 4, 5] 10 | while(start <= end): 11 | if(folks[start] + folks[end] <= limit): 12 | start += 1 13 | end -= 1 14 | boats += 1 15 | return boats 16 | 17 | -------------------------------------------------------------------------------- /leetcode/problem_101.py: -------------------------------------------------------------------------------- 1 | ### Problem 101. Symmetric Tree (Easy) 2 | class Solution: 3 | def isSymmetric(self, root: Optional[TreeNode]) -> bool: 4 | p = root.left 5 | q = root.right 6 | return self.isSymmetricHelper(p,q) 7 | 8 | def isSymmetricHelper(self, left: TreeNode, right: TreeNode): 9 | if((left and not right) or (right and not left)): 10 | return False 11 | if(not right and not left): 12 | return True 13 | if(left.val != right.val): 14 | return False 15 | return self.isSymmetricHelper(left.left,right.right) and self.isSymmetricHelper(left.right,right.left) 16 | -------------------------------------------------------------------------------- /leetcode/problem_102.py: -------------------------------------------------------------------------------- 1 | ### Problem 102. 2 | from collections import deque 3 | 4 | class Solution: 5 | def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: 6 | q = deque() 7 | result = [] 8 | q.append(root) 9 | if(root is None): 10 | return result 11 | while(True): 12 | size = len(q) 13 | if(size == 0): 14 | return result 15 | data = [] 16 | while(size > 0): 17 | temp = q.popleft() 18 | data.append(temp.val) 19 | if(temp.left): 20 | q.append(temp.left) 21 | if(temp.right): 22 | q.append(temp.right) 23 | size -=1 24 | result.append(data) 25 | return result -------------------------------------------------------------------------------- /leetcode/problem_1022.py: -------------------------------------------------------------------------------- 1 | ### Problem 1022. Sum of Root To Leaf Binary Numbers (Easy): https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers/ 2 | 3 | ### Tags: Tree, Depth First Search, Recursion 4 | 5 | # Definition for a binary tree node. 6 | # class TreeNode: 7 | # def __init__(self, val=0, left=None, right=None): 8 | # self.val = val 9 | # self.left = left 10 | # self.right = right 11 | class Solution: 12 | def sumRootToLeaf(self, root: Optional[TreeNode]) -> int: 13 | def path(root, total): 14 | if(root is None): 15 | return 0 16 | if(root.left is None and root.right is None): 17 | return total*2 + root.val 18 | left = path(root.left, total*2 + root.val) 19 | right = path(root.right, total*2 + root.val) 20 | return left + right 21 | return path(root, 0) 22 | -------------------------------------------------------------------------------- /leetcode/problem_104.py: -------------------------------------------------------------------------------- 1 | ### Problem 104: Maximum Depth of Binary Tree (Easy): https://leetcode.com/problems/maximum-depth-of-binary-tree/ 2 | class Solution: 3 | def maxDepth(self, root: Optional[TreeNode]) -> int: 4 | if(not root): 5 | return 0 6 | lh = self.maxDepth(root.left) 7 | rh = self.maxDepth(root.right) 8 | 9 | return max(lh, rh) + 1 -------------------------------------------------------------------------------- /leetcode/problem_1051.py: -------------------------------------------------------------------------------- 1 | ### Problem 1051. Height Checker (Easy) 2 | ### Tags: [Array, Sorting] 3 | 4 | class Solution: 5 | def heightChecker(self, heights: List[int]) -> int: 6 | expected = sorted(heights) 7 | count = 0 8 | for i in range(len(expected)): 9 | if(expected[i] != heights[i]): 10 | count += 1 11 | return count -------------------------------------------------------------------------------- /leetcode/problem_1072.py: -------------------------------------------------------------------------------- 1 | ### Problem 1072. Flip Columns For Maximum Number of Equal Rows (Medium): https://leetcode.com/problems/flip-columns-for-maximum-number-of-equal-rows/ 2 | 3 | ### tags: Array, Hash Table, Matrix 4 | class Solution: 5 | def maxEqualRowsAfterFlips(self, matrix: List[List[int]]) -> int: 6 | def inverted(s): 7 | result = '' 8 | for letter in s: 9 | result += ('1' if letter == '0' else '0') 10 | return result 11 | 12 | lookUp = defaultdict(int) 13 | result = 0 14 | for row in matrix: 15 | k = '' 16 | for char in row: 17 | k += str(char) 18 | if(k[0] == '1'): 19 | k = inverted(k) 20 | lookUp[k] += 1 21 | result = max(result, lookUp[k]) 22 | return result -------------------------------------------------------------------------------- /leetcode/problem_108.py: -------------------------------------------------------------------------------- 1 | ### Problem 108. Convert Sorted Array to Binary Search Tree (Easy): https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/ 2 | 3 | ### Tags: Tree, Depth First Search, Recursion 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]: 12 | def bst(low, high): 13 | mid = low + (high - low) //2 14 | root = TreeNode(nums[mid]) 15 | if(low > high): 16 | return None 17 | root.left = bst(low, mid -1) 18 | root.right = bst(mid + 1, high) 19 | return root 20 | return bst(0, len(nums) - 1) -------------------------------------------------------------------------------- /leetcode/problem_11.py: -------------------------------------------------------------------------------- 1 | # Problem 11: Container With Most Water (Medium): https://leetcode.com/problems/container-with-most-water/ 2 | 3 | class Solution: 4 | def maxArea(self, height) -> int: 5 | max_area= 0 6 | start = 0 7 | end = len(height) - 1 8 | while(start < end): 9 | width = end - start 10 | min_height = min(height[start], height[end]) 11 | area = width*min_height 12 | if(area > max_area): 13 | max_area = area 14 | if(height[start] < height[end]): 15 | start+=1 16 | else: 17 | end-=1 18 | return max_area 19 | 20 | 21 | if __name__ == "__main__": 22 | solution = Solution() 23 | print(solution.maxArea([1,8,6,2,5,4,8,3,7])) # 49 -------------------------------------------------------------------------------- /leetcode/problem_110.py: -------------------------------------------------------------------------------- 1 | ### Problem 110. Balanced Binary Tree (Easy): https://leetcode.com/problems/balanced-binary-tree/ 2 | # hint: Perform inorder tarversal and check for each node if depth is greater than 1 3 | class Solution: 4 | def isBalanced(self, root: Optional[TreeNode]) -> bool: 5 | ans = True 6 | stack = [] 7 | if(root is None): 8 | return True 9 | while(True): 10 | while(root): 11 | stack.append(root) 12 | root = root.left 13 | if(not stack): 14 | break 15 | root = stack.pop() 16 | hl = self.height(root.left) 17 | hr = self.height(root.right) 18 | if(abs(hl - hr) > 1): 19 | return False 20 | root = root.right 21 | return ans 22 | 23 | def height(self, root: TreeNode)->int: 24 | if(root is None): 25 | return 0 26 | else: 27 | return max(self.height(root.left), self.height(root.right)) + 1 -------------------------------------------------------------------------------- /leetcode/problem_111.py: -------------------------------------------------------------------------------- 1 | ### Problem 111. Minimum Depth of Binary Tree (Easy): https://leetcode.com/problems/minimum-depth-of-binary-tree/ 2 | 3 | # hint: run a level order traversal and return the depth when you find a leaf node 4 | from collections import deque 5 | class Solution: 6 | def minDepth(self, root: Optional[TreeNode]) -> int: 7 | q = deque() 8 | depth = 0 9 | if(root is None): 10 | return depth 11 | q.append(root) 12 | while(True): 13 | size = len(q) 14 | if(size == 0): 15 | return depth 16 | depth += 1 17 | while(size > 0): 18 | top = q.popleft() 19 | if((top.left is None) and (top.right is None)): 20 | q = deque() 21 | break 22 | if(top.left): 23 | q.append(top.left) 24 | if(top.right): 25 | q.append(top.right) 26 | size -= 1 27 | return depth 28 | -------------------------------------------------------------------------------- /leetcode/problem_112.py: -------------------------------------------------------------------------------- 1 | ### Problem 112. Path Sum 2 | ### Tags: Tree, Depth First Search, Recursion 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool: 12 | def hasPath(root,targetSum): 13 | if(root is None): 14 | return False 15 | else: 16 | targetSum -= root.val 17 | if(root.left is None and root.right is None): 18 | return targetSum == 0 19 | return hasPath(root.left, targetSum) or hasPath(root.right, targetSum) 20 | return hasPath(root, targetSum) -------------------------------------------------------------------------------- /leetcode/problem_1122.py: -------------------------------------------------------------------------------- 1 | ### Problem 1122. Relative Sort Array (Easy): https://leetcode.com/problems/relative-sort-array/ 2 | ### Tags: Array, Hash Table, Sorting 3 | 4 | class Solution: 5 | def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]: 6 | freq = {} 7 | freq2 = {} 8 | result = [] 9 | for i in range(len(arr1)): 10 | if(arr1[i] in freq): 11 | freq[arr1[i]] += 1 12 | else: 13 | freq[arr1[i]] = 1 14 | 15 | if(i < len(arr2)): 16 | freq2[arr2[i]] = 1 17 | 18 | for i in range(len(arr2)): 19 | while(freq[arr2[i]] > 0): 20 | result.append(arr2[i]) 21 | freq[arr2[i]] -= 1 22 | end = [] 23 | for i in range(len(arr1)): 24 | if(arr1[i] not in freq2): 25 | end.append(arr1[i]) 26 | 27 | end.sort() 28 | for i in range(len(end)): 29 | result.append(end[i]) 30 | return result 31 | -------------------------------------------------------------------------------- /leetcode/problem_118.py: -------------------------------------------------------------------------------- 1 | ### Problem 118. Pascal's Triangle (Easy): https://leetcode.com/problems/pascals-triangle/ 2 | 3 | class Solution: 4 | def generate(self, numRows: int) -> List[List[int]]: 5 | pt = [[1], [1, 1]] 6 | if(numRows == 1): 7 | return [pt[0]] 8 | for row in range(2, numRows): 9 | col = [] 10 | for column in range(row+1): 11 | if(column == 0 or column==row): 12 | col.append(1) 13 | else: 14 | col.append(pt[row-1][column -1] + pt[row-1][column]) 15 | pt.append(col) 16 | return pt -------------------------------------------------------------------------------- /leetcode/problem_119.py: -------------------------------------------------------------------------------- 1 | ### Problem 119. Pascal's Triangle II (Easy): https://leetcode.com/problems/pascals-triangle-ii/ 2 | class Solution: 3 | def getRow(self, rowIndex: int) -> List[int]: 4 | pt = [[1], [1, 1]] 5 | if(rowIndex < 2): 6 | return pt[rowIndex] 7 | for row in range(2, rowIndex + 1): 8 | column = [] 9 | for col in range(row + 1): 10 | if(col == 0 or col == row): 11 | column.append(1) 12 | else: 13 | column.append(pt[row-1][col-1] + pt[row -1][col]) 14 | pt.append(column) 15 | return pt[rowIndex] -------------------------------------------------------------------------------- /leetcode/problem_1190.py: -------------------------------------------------------------------------------- 1 | ### Problem 1190. Reverse Substrings Between Each Pair of Parentheses (Medium): https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/ 2 | ### Tags: Stack 3 | class Solution: 4 | def reverseParentheses(self, s: str) -> str: 5 | stack = [] 6 | for c in s: 7 | if(c != ')'): 8 | stack.append(c) 9 | else: 10 | result = '' 11 | while(stack[-1] != '('): 12 | result += stack.pop() 13 | stack.pop() 14 | for k in result: 15 | stack.append(k) 16 | return ''.join(stack) -------------------------------------------------------------------------------- /leetcode/problem_1200.py: -------------------------------------------------------------------------------- 1 | ### Problem 1200. Minimum Absolute Difference (Easy): https://leetcode.com/problems/minimum-absolute-difference/ 2 | 3 | ### tags: array, sorting 4 | 5 | class Solution: 6 | def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]: 7 | arr.sort() 8 | left = 0 9 | result = [] 10 | min_diff = 1000000 11 | for right in range(left + 1, len(arr)): 12 | diff = arr[right] - arr[left] 13 | min_diff = min(min_diff, diff) 14 | left += 1 15 | left = 0 16 | for right in range(left + 1, len(arr)): 17 | diff = arr[right] - arr[left] 18 | if(diff == min_diff): 19 | result.append([arr[left], arr[right]]) 20 | left += 1 21 | return result -------------------------------------------------------------------------------- /leetcode/problem_129.py: -------------------------------------------------------------------------------- 1 | ### Problem 129. Sum Root to Leaf Numbers (Medium): https://leetcode.com/problems/sum-root-to-leaf-numbers/ 2 | 3 | ### Tags: Tree, Depth First Search, Recursion 4 | class Solution: 5 | def sumNumbers(self, root: Optional[TreeNode]) -> int: 6 | def path(root, sum_n): 7 | if(root is None): 8 | return 0 9 | if(root.left is None and root.right is None): 10 | return sum_n*10 + root.val 11 | left = path(root.left, sum_n*10 + root.val) 12 | right = path(root.right, sum_n*10 + root.val) 13 | return left + right 14 | return path(root, 0) -------------------------------------------------------------------------------- /leetcode/problem_1302.py: -------------------------------------------------------------------------------- 1 | ### Problem 1302. Deepest Leaves Sum (Medium): https://leetcode.com/problems/deepest-leaves-sum/ 2 | 3 | from collections import deque 4 | 5 | class Solution: 6 | def deepestLeavesSum(self, root: Optional[TreeNode]) -> int: 7 | q = deque() 8 | deep_sum = 0 9 | if(root is None): 10 | return deep_sum 11 | q.append(root) 12 | while(True): 13 | size = len(q) 14 | if(size == 0): 15 | return deep_sum 16 | deep_sum = 0 17 | while(size > 0): 18 | front = q.popleft() 19 | deep_sum += front.val 20 | if(front.left): 21 | q.append(front.left) 22 | if(front.right): 23 | q.append(front.right) 24 | size -= 1 25 | return deep_sum -------------------------------------------------------------------------------- /leetcode/problem_1310.py: -------------------------------------------------------------------------------- 1 | ### Problem 1310. XOR Queries of a Subarray 2 | ### tags: array, Prefix Sum, bit manipulation 3 | 4 | # hint: XOR with same number is 0, order doesn't matter 5 | class Solution: 6 | def xorQueries(self, arr: List[int], queries: List[List[int]]) -> List[int]: 7 | prefix = [0] 8 | for num in arr: 9 | prefix.append(prefix[-1] ^ num) 10 | 11 | answers = [] 12 | for i in range(len(queries)): 13 | start, end = queries[i] 14 | res = prefix[end+1] ^ prefix[start] 15 | answers.append(res) 16 | return answers 17 | -------------------------------------------------------------------------------- /leetcode/problem_1318.py: -------------------------------------------------------------------------------- 1 | ### Problem 1318. Minimum Flips to Make a OR b Equal to c 2 | ### tags: bit manipulation 3 | 4 | class Solution: 5 | def minFlips(self, a: int, b: int, c: int) -> int: 6 | # a = 0010 7 | # b = 0110 8 | # a | b= 0110 9 | # 0101 10 | count = 0 11 | while(c > 0 or a > 0 or b > 0): 12 | if(c & 1 == 0): 13 | if(a & 1 and b & 1): 14 | count += 2 15 | elif(a & 1 or b & 1): 16 | count += 1 17 | else: 18 | if((a & 1 == 0) and (b & 1 == 0)): 19 | count += 1 20 | c >>= 1 21 | a >>= 1 22 | b >>= 1 23 | return count -------------------------------------------------------------------------------- /leetcode/problem_133.py: -------------------------------------------------------------------------------- 1 | ### Problem 133. Clone Graph (Medium): https://leetcode.com/problems/clone-graph/ 2 | 3 | ### tags: Graph, BFS, DFS Hash Table 4 | """ 5 | # Definition for a Node. 6 | class Node: 7 | def __init__(self, val = 0, neighbors = None): 8 | self.val = val 9 | self.neighbors = neighbors if neighbors is not None else [] 10 | """ 11 | 12 | from typing import Optional 13 | # BFS Solution 14 | class Solution: 15 | def cloneGraph(self, node: Optional['Node']) -> Optional['Node']: 16 | q = deque() 17 | if(node is None): 18 | return node 19 | q.append(node) 20 | node_map = {} 21 | node_map[node.val] = Node(node.val, []) 22 | while(len(q) != 0): 23 | top = q.popleft() 24 | for n in top.neighbors: 25 | if(n.val not in node_map): 26 | q.append(n) 27 | node_map[n.val] = Node(n.val,[]) 28 | node_map[top.val].neighbors.append(node_map[n.val]) 29 | return node_map[node.val] 30 | -------------------------------------------------------------------------------- /leetcode/problem_1331.py: -------------------------------------------------------------------------------- 1 | ### Problem 1331. Rank Transform of an Array (Easy) 2 | ### tags: array, hash table, sort 3 | class Solution: 4 | def arrayRankTransform(self, arr: List[int]) -> List[int]: 5 | sortedarr = sorted(arr) 6 | result = [] 7 | rank = 1 8 | hash = {} 9 | for i in range(len(sortedarr)): 10 | curr = sortedarr[i] 11 | if(curr not in hash): 12 | hash[curr] = (1, rank) 13 | rank += 1 14 | else: 15 | freq, r = hash[curr] 16 | freq += 1 17 | hash[curr] = (freq, r) 18 | result = [] 19 | for num in arr: 20 | result.append(hash[num][1]) 21 | return result 22 | -------------------------------------------------------------------------------- /leetcode/problem_1346.py: -------------------------------------------------------------------------------- 1 | ### Problem 1346. Check If N and Its Double Exist (Easy): https://leetcode.com/problems/check-if-n-and-its-double-exist/ 2 | 3 | ### tags: array, hash table 4 | class Solution: 5 | def checkIfExist(self, arr: List[int]) -> bool: 6 | hmap = set() 7 | for i in range(len(arr)): 8 | num = arr[i] 9 | target = arr[i] * 2 10 | if(target not in hmap and num / 2 not in hmap): 11 | hmap.add(arr[i]) 12 | else: 13 | return True 14 | return False 15 | -------------------------------------------------------------------------------- /leetcode/problem_136.py: -------------------------------------------------------------------------------- 1 | ### Problem 136. Single Number (Easy) 2 | ### Tags: BitManipulation, HashTable 3 | 4 | class Solution: 5 | def singleNumber(self, nums: List[int]) -> int: 6 | result = 0 7 | for num in nums: 8 | result ^= num 9 | return result -------------------------------------------------------------------------------- /leetcode/problem_1381.py: -------------------------------------------------------------------------------- 1 | ### Problem 1381. Design a Stack With Increment Operation (Medium): https://leetcode.com/problems/design-a-stack-with-increment-operation/ 2 | 3 | ### tags: array, stack, design 4 | class CustomStack: 5 | 6 | def __init__(self, maxSize: int): 7 | self.stack = [] 8 | self.maxSize = maxSize 9 | 10 | def push(self, x: int) -> None: 11 | if(self.isFull()): return 12 | self.stack.append(x) 13 | 14 | def pop(self) -> int: 15 | if(self.isEmpty()): 16 | return -1 17 | return self.stack.pop() 18 | 19 | def increment(self, k: int, val: int) -> None: 20 | for i in range(min(k, len(self.stack))): 21 | self.stack[i] += val 22 | 23 | def isFull(self): 24 | return len(self.stack) == self.maxSize 25 | 26 | def isEmpty(self): 27 | return len(self.stack) == 0 28 | 29 | # Your CustomStack object will be instantiated and called as such: 30 | # obj = CustomStack(maxSize) 31 | # obj.push(x) 32 | # param_2 = obj.pop() 33 | # obj.increment(k,val) -------------------------------------------------------------------------------- /leetcode/problem_1400.py: -------------------------------------------------------------------------------- 1 | #### Problem 1400: Construct K Palindrome Strings 2 | ### tags: String, Hash table 3 | class Solution: 4 | def canConstruct(self, s: str, k: int) -> bool: 5 | if(k > len(s)): 6 | return False 7 | count = Counter(s) 8 | c = 0 9 | for kc, v in count.items(): 10 | c += (v & 1) 11 | return (c <= k) -------------------------------------------------------------------------------- /leetcode/problem_1404.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def numSteps(self, s: str) -> int: 3 | count = 0 4 | num = self.binToNum(s) 5 | while(num != 1): 6 | # if odd 7 | if(num % 2 == 1): 8 | num += 1 9 | else: 10 | num = num >> 1 11 | count += 1 12 | return count 13 | 14 | def binToNum(self, s:str) -> int: 15 | num = 0 16 | for bit in s: 17 | num = (num << 1) | int(bit) 18 | return num 19 | 20 | -------------------------------------------------------------------------------- /leetcode/problem_1408.py: -------------------------------------------------------------------------------- 1 | ### probelem 1408. String Matching in an Array (Easy) 2 | ### tags: string, array 3 | class Solution: 4 | def stringMatching(self, words: List[str]) -> List[str]: 5 | result = [] 6 | for i in range(len(words)): 7 | for j in range(len(words)): 8 | if(i == j): 9 | continue 10 | if(words[i] in words[j]): 11 | result.append(words[i]) 12 | break 13 | return result -------------------------------------------------------------------------------- /leetcode/problem_141.py: -------------------------------------------------------------------------------- 1 | ### Problem 141. Linked List Cycle 2 | class Solution: 3 | def hasCycle(self, head: Optional[ListNode]) -> bool: 4 | index = {} 5 | start = head 6 | count = 0 7 | while(start and start not in index): 8 | index[start] = 0 9 | start = start.next 10 | if(start): 11 | return True 12 | return False 13 | 14 | 15 | # Optimized 16 | # Floyd's Tortoise and Hare Algorithm 17 | # res: https://www.youtube.com/watch?v=RRSItF-Ts4Q 18 | 19 | class Solution: 20 | def hasCycle(self, head: Optional[ListNode]) -> bool: 21 | slow = head 22 | fast = head 23 | while(fast and fast.next): 24 | slow = slow.next 25 | fast = fast.next.next 26 | if(slow == fast): 27 | return True 28 | return False -------------------------------------------------------------------------------- /leetcode/problem_142.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 3 | visited = {} 4 | while(head not in visited and head): 5 | visited[head] = head 6 | head = head.next 7 | return head 8 | 9 | 10 | # Hare and Tortoise mathematical explanation: https://www.youtube.com/watch?v=PvrxZaH_eZ4 11 | class Solution: 12 | def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: 13 | slow = head 14 | fast = head 15 | while(fast and fast.next): 16 | slow = slow.next 17 | fast = fast.next.next 18 | if(slow == fast): 19 | slow = head 20 | while(slow != fast): 21 | fast = fast.next 22 | slow = slow.next 23 | return fast 24 | return None -------------------------------------------------------------------------------- /leetcode/problem_1442.py: -------------------------------------------------------------------------------- 1 | ### Problem 1442. Count Triplets That Can Form Two Arrays of Equal XOR (Medium): https://leetcode.com/problems/count-triplets-that-can-form-two-arrays-of-equal-xor/ 2 | 3 | ### Tags: Array, Bit Manipulation 4 | 5 | # Time Complexity: O(n^3) 6 | class Solution: 7 | def countTriplets(self, arr: List[int]) -> int: 8 | count = 0 9 | for i in range(len(arr)): 10 | a = 0 11 | for j in range(i + 1 ,len(arr)): 12 | a = a ^ arr[j-1] 13 | b = 0 14 | for k in range(j ,len(arr)): 15 | b = b ^ arr[k] 16 | if(a==b): 17 | count +=1 18 | return count -------------------------------------------------------------------------------- /leetcode/problem_1448.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def goodNodes(self, root: TreeNode) -> int: 9 | # paths: 3 : good 10 | # paths: 3 -> 1 : false 11 | # paths: 3 -> 1 -> 3 : good 12 | # paths: 3 -> 4: good 13 | # paths: 3 -> 4 -> 1 : false 14 | # paths: 3 -> 4 -> 5 : good 15 | def isGood(node, max_val): 16 | if(node is None): 17 | return 0 18 | count = 0 19 | if(node.val >= max_val): 20 | count = 1 21 | max_val = node.val 22 | count += isGood(node.left, max_val) 23 | count += isGood(node.right, max_val) 24 | return count 25 | 26 | return isGood(root, root.val) -------------------------------------------------------------------------------- /leetcode/problem_145.py: -------------------------------------------------------------------------------- 1 | ### Problem 145. Binary Tree Postorder Traversal (Hard): https://leetcode.com/problems/binary-tree-postorder-traversal/ 2 | 3 | ### Tags: Tree, Depth First Search, Stack 4 | class Solution: 5 | def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: 6 | result = [] 7 | if(root is None): 8 | return result 9 | stack = [] 10 | while(True): 11 | while(root): 12 | stack.append(root) 13 | result.append(root.val) 14 | root = root.left 15 | if(not stack): 16 | break 17 | root = stack.pop() 18 | root = root.right 19 | return result -------------------------------------------------------------------------------- /leetcode/problem_1455.py: -------------------------------------------------------------------------------- 1 | ### Problem 1455. Check If a Word Occurs As a Prefix of Any Word in a Sentence (Easy): https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ 2 | ### tags: strings, two pointers 3 | 4 | class Solution: 5 | def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: 6 | wordCount = 0 7 | i = 0 8 | while(sentence[i] == ' '): 9 | sentence[i] = '' 10 | i += 1 11 | 12 | for i in range(len(sentence)): 13 | if(sentence[i - 1] == " " or i == 0): 14 | wordCount += 1 15 | k = i 16 | prefix = True 17 | j = 0 18 | while(j < len(searchWord) and k < len(sentence) and sentence[k] == searchWord[j]): 19 | j += 1 20 | k += 1 21 | if(j == len(searchWord)): 22 | return wordCount 23 | return -1 24 | 25 | 26 | -------------------------------------------------------------------------------- /leetcode/problem_1460.py: -------------------------------------------------------------------------------- 1 | ### Problem 1460. Make Two Arrays Equal by Reversing Sub-arrays (Easy): https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays/ 2 | 3 | ### Tags: Array, Hash Table 4 | class Solution: 5 | def canBeEqual(self, target: List[int], arr: List[int]) -> bool: 6 | if(len(target) != len(arr)): 7 | return False 8 | freq1 = Counter(target) 9 | freq2 = Counter(arr) 10 | for num in arr: 11 | if(num not in freq1 or (freq1[num] != freq2[num])): 12 | return False 13 | return True -------------------------------------------------------------------------------- /leetcode/problem_1464.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | class Solution: 4 | def maxProduct(self, nums: List[int]) -> int: 5 | nums = sorted(nums, reverse = True) 6 | return (nums[0] - 1) * (nums[1] - 1) 7 | 8 | class Solution2: 9 | def maxProduct(self, nums: List[int]) -> int: 10 | max_heap = [] 11 | for element in nums: 12 | heapq.heappush(max_heap, -element) 13 | n1 = (heapq.heappop(max_heap) * -1) - 1 14 | n2 = (heapq.heappop(max_heap) * -1) - 1 15 | return n1 * n2 -------------------------------------------------------------------------------- /leetcode/problem_1475.py: -------------------------------------------------------------------------------- 1 | ### Problem 1475. Final Prices With a Special Discount in a Shop (Easy): https://leetcode.com/problems/final-prices-with-a-special-discount-in-a-shop/ 2 | class Solution: 3 | def finalPrices(self, prices: List[int]) -> List[int]: 4 | for i in range(len(prices)): 5 | for j in range(i+1, len(prices)): 6 | if(prices[j]<= prices[i]): 7 | prices[i] -= prices[j] 8 | break 9 | return prices -------------------------------------------------------------------------------- /leetcode/problem_1480.py: -------------------------------------------------------------------------------- 1 | ### Problem 1480. Running Sum of 1d Array (Easy) 2 | class Solution: 3 | def runningSum(self, nums: List[int]) -> List[int]: 4 | for i in range(1,len(nums)): 5 | nums[i] += nums[i-1] 6 | return nums 7 | 8 | # Recursive solution 9 | class Solution2: 10 | def runningSum(self, nums: List[int]) -> List[int]: 11 | result = self.sum_i(len(nums) - 1, nums) 12 | return result 13 | 14 | def sum_i(self, i:int, nums: List[int])-> List[int]: 15 | if(i < 1): 16 | return nums 17 | else: 18 | nums = self.sum_i(i-1, nums) 19 | nums[i] += nums[i-1] 20 | return nums 21 | 22 | if __name__ == '__main__': 23 | s = Solution() 24 | print(s.runningSum([1,2,3,4])) # [1,3,6,10] 25 | print(s.runningSum([1,1,1,1,1])) # [1,2,3,4,5] 26 | print(s.runningSum([3,1,2,10,1])) # [3,4,6,16,17] 27 | print(s.runningSum([3,1,2,10,1,1])) # [3,4,6,16,17,18] -------------------------------------------------------------------------------- /leetcode/problem_1508.py: -------------------------------------------------------------------------------- 1 | ### Problem 1508. Range Sum of Sorted Subarray Sums (Medium): https://leetcode.com/problems/range-sum-of-sorted-subarray-sums/ 2 | 3 | ### Tags: Array, Sorting, Prefix Sum 4 | 5 | class Solution: 6 | def rangeSum(self, nums: List[int], n: int, left: int, right: int) -> int: 7 | arr = [] 8 | for i in range(len(nums)): 9 | sum_n = 0 10 | for j in range(i, len(nums)): 11 | sum_n += nums[j] 12 | arr.append(sum_n) 13 | # arr.extend(nums) 14 | arr.sort() 15 | print(arr) 16 | sum_n = 0 17 | for i in range(left-1, right): 18 | sum_n += arr[i] 19 | return sum_n % (pow(10, 9) + 7) -------------------------------------------------------------------------------- /leetcode/problem_1512.py: -------------------------------------------------------------------------------- 1 | # Problem 1512. Number of Good Pairs (Easy): https://leetcode.com/problems/number-of-good-pairs/ 2 | class Solution: 3 | def numIdenticalPairs(self, nums: List[int]) -> int: 4 | gpairs = {} 5 | count = 0 6 | for i in range(len(nums)): 7 | if nums[i] in gpairs: 8 | count += gpairs[nums[i]] 9 | else: 10 | gpairs[nums[i]] = 0 11 | gpairs[nums[i]] = gpairs[nums[i]] + 1 12 | return count 13 | 14 | # Time Complexity: O(n) 15 | # Space Complexity: O(n) 16 | 17 | if __name__ == '__main__': 18 | s = Solution() 19 | print(s.numIdenticalPairs([1,2,3,1,1,3])) # 4 20 | print(s.numIdenticalPairs([1,1,1,1])) # 6 21 | print(s.numIdenticalPairs([1,2,3])) # 0 22 | print(s.numIdenticalPairs([1,2,3,4,5,6,7,8,9,10])) # 0 23 | print(s.numIdenticalPairs([1,1,1,1,1,1,1,1,1,1])) # 45 24 | -------------------------------------------------------------------------------- /leetcode/problem_1518.py: -------------------------------------------------------------------------------- 1 | ### Problem 1518. Water Bottles (Easy) 2 | 3 | ### Tags: Math 4 | class Solution: 5 | def numWaterBottles(self, numBottles: int, numExchange: int) -> int: 6 | maxDrink = numBottles 7 | emptyBottles = 0 8 | while((numBottles // numExchange) > 0): 9 | maxDrink += (numBottles // numExchange) 10 | emptyBottles = numBottles % numExchange 11 | numBottles = (numBottles // numExchange) 12 | numBottles += emptyBottles 13 | return maxDrink -------------------------------------------------------------------------------- /leetcode/problem_1598.py: -------------------------------------------------------------------------------- 1 | ### Problem 1598: Crawler Log Folder (Easy): https://leetcode.com/problems/crawler-log-folder/ 2 | ### Tags: Array, String, Stack 3 | 4 | class Solution: 5 | def minOperations(self, logs: List[str]) -> int: 6 | depth = 0 7 | for log in logs: 8 | if(log == '../'): 9 | if(depth > 0): 10 | depth -= 1 11 | elif(log == './'): 12 | pass 13 | else: 14 | depth += 1 15 | return depth -------------------------------------------------------------------------------- /leetcode/problem_16.py: -------------------------------------------------------------------------------- 1 | ### Problem 16: 3Sum Closest (Medium): https://leetcode.com/problems/3sum-closest/ 2 | # Tags: Array, Two Pointers 3 | class Solution: 4 | def threeSumClosest(self, nums: List[int], target: int) -> int: 5 | start = 0 6 | end = len(nums) -1 7 | nums.sort() 8 | sum3 = nums[0] + nums[1] + nums[2] 9 | for i in range(len(nums)-2): 10 | start = i+1 11 | end = len(nums) -1 12 | while(start < end): 13 | s = nums[i] + nums[start] + nums[end] 14 | if(abs(target-sum3) > abs(target - s)): 15 | sum3 = s 16 | if(s > target): 17 | end -= 1 18 | else: 19 | start += 1 20 | return sum3 -------------------------------------------------------------------------------- /leetcode/problem_160.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: 3 | addr = {} 4 | if(not headA or not headB): 5 | return None 6 | while(headA): 7 | addr[headA] = headA 8 | headA = headA.next 9 | while(headB): 10 | if(headB in addr): 11 | return headB 12 | headB = headB.next 13 | return None 14 | 15 | # Time complexity: O(n) 16 | # Space complexity: O(n) 17 | 18 | -------------------------------------------------------------------------------- /leetcode/problem_1605.py: -------------------------------------------------------------------------------- 1 | ### Problem 1605. Find Valid Matrix Given Row and Column Sums (Medium): https://leetcode.com/problems/find-valid-matrix-given-row-and-column-sums/ 2 | 3 | ### tags: greedy, matrix 4 | 5 | class Solution: 6 | def restoreMatrix(self, rowSum: List[int], colSum: List[int]) -> List[List[int]]: 7 | result = [[0 for j in range(len(colSum))] for i in range(len(rowSum))] 8 | for row in range(len(rowSum)): 9 | for col in range(len(colSum)): 10 | min_val = min(colSum[col], rowSum[row]) 11 | result[row][col] = min_val 12 | rowSum[row] -= min_val 13 | colSum[col] -= min_val 14 | return result -------------------------------------------------------------------------------- /leetcode/problem_1636.py: -------------------------------------------------------------------------------- 1 | ### Problem 1636. Sort Array by Increasing Frequency (Easy): https://leetcode.com/problems/sort-array-by-increasing-frequency/ 2 | 3 | class Solution: 4 | def frequencySort(self, nums: List[int]) -> List[int]: 5 | 6 | def sort_num(num): 7 | return (freq[num], -num) 8 | freq = {} 9 | for num in nums: 10 | if num not in freq: 11 | freq[num] = 1 12 | else: 13 | freq[num] += 1 14 | # nums.sort(key = sort_num) 15 | # sort based on the tuple if first parameter is same 16 | # uses second parameter -num to sort 17 | nums.sort(key = lambda num: (freq[num], -num)) 18 | return nums 19 | 20 | # Time complexity: O(nlogn) -------------------------------------------------------------------------------- /leetcode/problem_1684.py: -------------------------------------------------------------------------------- 1 | ### Problem 1684. 2 | ### tags: array, hash_table, string, bit manipulation, counting 3 | class Solution: 4 | def countConsistentStrings(self, allowed: str, words: List[str]) -> int: 5 | def isSetEqual(hash_1, hash_2): 6 | for k in hash_2: 7 | if(k not in hash_1): 8 | return False 9 | return True 10 | 11 | hash_1 = set(allowed) 12 | count = 0 13 | for word in words: 14 | hash_2 = set(word) 15 | if(isSetEqual(hash_1, hash_2)): 16 | count += 1 17 | return count 18 | -------------------------------------------------------------------------------- /leetcode/problem_1780.py: -------------------------------------------------------------------------------- 1 | #### Problem 1780. Check if Number is a Sum of Powers of Three 2 | ### tags: [backtracking] 3 | 4 | class Solution: 5 | def checkPowersOfThree(self, n: int) -> bool: 6 | def backtrack(x, s): 7 | if(s == n): 8 | return True 9 | if(s > n or 3**x > n): 10 | return False 11 | else: 12 | if(backtrack(x+1, s + 3**x)): 13 | return True 14 | return backtrack(x+1, s) 15 | 16 | return backtrack(0, 0) 17 | -------------------------------------------------------------------------------- /leetcode/problem_179.py: -------------------------------------------------------------------------------- 1 | ### Problem 179. Largest Number 2 | ### tags: array, string, greedy, sorting 3 | class Solution: 4 | def largestNumber(self, nums: List[int]) -> str: 5 | def compare(x, y): 6 | if(x + y > y + x): 7 | return -1 8 | else: 9 | return 1 10 | for i in range(len(nums)): 11 | nums[i] = str(nums[i]) 12 | 13 | nums = sorted(nums, key=cmp_to_key(compare)) 14 | return str(int(''.join(nums))) -------------------------------------------------------------------------------- /leetcode/problem_1791.py: -------------------------------------------------------------------------------- 1 | ### Problem 1791. Find Center of Star Graph (Medium) 2 | ### tags: Graph, Degree, Hash Table 3 | class Solution: 4 | def findCenter(self, edges: List[List[int]]) -> int: 5 | deg = defaultdict(int) 6 | for src, dest in edges: 7 | deg[src]+=1 8 | deg[dest]+=1 9 | return max(deg, key=deg.get) 10 | 11 | -------------------------------------------------------------------------------- /leetcode/problem_1792.py: -------------------------------------------------------------------------------- 1 | ### Problem 1792. Maximum Average Pass Ratio (Medium): https://leetcode.com/problems/maximum-average-pass-ratio/ 2 | # tags: heap, greedy 3 | 4 | # hint: store max increase in a heap and add student to the class with the max increase 5 | class Solution: 6 | def maxAverageRatio(self, classes: List[List[int]], extraStudents: int) -> float: 7 | min_h = [] 8 | for i in range(len(classes)): 9 | p, t = classes[i] 10 | increase = ((p + 1)/ (t + 1)) - (p / t) 11 | t = (-1 * increase, p, t) 12 | heapq.heappush(min_h, t) 13 | 14 | for student in range(extraStudents): 15 | percentage, p, t = heapq.heappop(min_h) 16 | p += 1 17 | t += 1 18 | increase = ((p + 1)/ (t + 1)) - (p / t) 19 | t = (-1* increase, p, t) 20 | heapq.heappush(min_h, t) 21 | 22 | result = 0 23 | for per, p, t in min_h: 24 | result += (p/t) 25 | return (result/len(classes)) -------------------------------------------------------------------------------- /leetcode/problem_1800.py: -------------------------------------------------------------------------------- 1 | ### Problem 1800. Maximum Ascending Subarray Sum 2 | ### tags: array 3 | class Solution: 4 | def maxAscendingSum(self, nums: List[int]) -> int: 5 | max_s = 0 6 | curr_s = 0 7 | prev = 0 8 | for end in range(len(nums)): 9 | if(nums[end] <= prev): 10 | curr_s = nums[end] 11 | else: 12 | curr_s += nums[end] 13 | prev = nums[end] 14 | max_s = max(max_s, curr_s) 15 | return max_s -------------------------------------------------------------------------------- /leetcode/problem_1894.py: -------------------------------------------------------------------------------- 1 | ### Problem 1894. Find the Amount of Chalk Used (Medium): https://leetcode.com/problems/find-the-amount-of-chalk-used/ 2 | 3 | ### tags: array, binary search, prefix sum 4 | class Solution: 5 | def chalkReplacer(self, chalk: List[int], k: int) -> int: 6 | if(len(chalk) == 1): 7 | return 0 8 | total = sum(chalk) 9 | while(k > total): 10 | k -= total 11 | if(k == total): 12 | return 0 13 | 14 | for i in range(len(chalk)): 15 | c = chalk[i] 16 | if(c > k): 17 | return i 18 | k -= c 19 | return len(chalk) - 1 20 | -------------------------------------------------------------------------------- /leetcode/problem_191.py: -------------------------------------------------------------------------------- 1 | ### Problem 191. Number of 1 Bits (Easy): https://leetcode.com/problems/number-of-1-bits/ 2 | class Solution: 3 | def hammingWeight(self, n: int) -> int: 4 | count = 0 5 | for i in range(32): 6 | if((1 << i) & n): 7 | count += 1 8 | return count -------------------------------------------------------------------------------- /leetcode/problem_1937.py: -------------------------------------------------------------------------------- 1 | ### Problem 1937. Maximum Number of Points with Cost (Medium) 2 | ### Tags: Dynamic Programming 3 | 4 | # https://www.youtube.com/watch?v=STEJHYc9rMw 5 | class Solution: 6 | def maxPoints(self, points: List[List[int]]) -> int: 7 | n = len(points) 8 | m = len(points[0]) 9 | left = [0] * m 10 | right = [0] * m 11 | # dp[i][j] deontes max points gained at i,j 12 | dp = points[0] 13 | 14 | for row in range(1, len(points)): 15 | for col in range(m): 16 | if(col == 0): 17 | left[col] = dp[col] 18 | else: 19 | left[col] = max(left[col-1] - 1, dp[col]) 20 | 21 | 22 | for col in range(m-1, -1, -1): 23 | if(col == m-1): 24 | right[col] = dp[col] 25 | else: 26 | right[col] = max(right[col+1] - 1, dp[col]) 27 | 28 | for col in range(m): 29 | dp[col] = max(left[col], right[col]) + points[row][col] 30 | return max(dp) -------------------------------------------------------------------------------- /leetcode/problem_1945.py: -------------------------------------------------------------------------------- 1 | ### Problem 1945. Sum of Digits of String After Convert (Easy): https://leetcode.com/problems/sum-of-digits-of-string-after-convert/ 2 | 3 | ### tags: string, simulation 4 | class Solution: 5 | def getLucky(self, s: str, k: int) -> int: 6 | def str_sum(sno): 7 | sum_n=0 8 | for n in sno: 9 | sum_n += int(n) 10 | return sum_n 11 | numbers = '' 12 | for ch in s: 13 | numbers += str((ord(ch) % 97) + 1) 14 | 15 | result = 0 16 | while(k > 0): 17 | result = str_sum(numbers) 18 | numbers = str(result) 19 | k -= 1 20 | return result -------------------------------------------------------------------------------- /leetcode/problem_1961.py: -------------------------------------------------------------------------------- 1 | ### Problem 1961. Check If String Is a Prefix of Array 2 | ### tags: array, two pointers, strings 3 | 4 | class Solution: 5 | def isPrefixString(self, s: str, words: List[str]) -> bool: 6 | count = 0 7 | index = -1 8 | con_s = '' 9 | for i in range(len(words)): 10 | count += len(words[i]) 11 | con_s += words[i] 12 | if(count == len(s)): 13 | index = i 14 | break 15 | if(index == -1): 16 | return False 17 | return con_s == s 18 | -------------------------------------------------------------------------------- /leetcode/problem_1963.py: -------------------------------------------------------------------------------- 1 | ### Problem 1963. Minimum Number of Swaps to Make the String Balanced (Medium): https://leetcode.com/problems/minimum-number-of-swaps-to-make-the-string-balanced 2 | 3 | class Solution: 4 | def minSwaps(self, s: str) -> int: 5 | result = 0 6 | maxClose = 0 7 | for bracket in s: 8 | if(bracket == '['): 9 | result -= 1 10 | else: 11 | result += 1 12 | maxClose = max(result, maxClose) 13 | return (maxClose + 1) // 2 -------------------------------------------------------------------------------- /leetcode/problem_20.py: -------------------------------------------------------------------------------- 1 | # Problem 20: Valid Parentheses (Easy): https://leetcode.com/problems/valid-parentheses/ 2 | 3 | class Solution: 4 | def isValid(self, s: str) -> bool: 5 | stack = [] 6 | for i in range(len(s)): 7 | if(s[i] == '{' or s[i] == '(' or s[i] == '['): 8 | stack.append(s[i]) 9 | elif(s[i]==')' or s[i]=='}' or s[i]==']'): 10 | if(len(stack) == 0): 11 | return False 12 | else: 13 | if((s[i]==')' and stack[-1] == '(') or (s[i]=='}' and stack[-1] == '{') or (s[i]==']' and stack[-1] == '[')): 14 | stack.pop() 15 | else: 16 | return False 17 | return len(stack) == 0 18 | 19 | if __name__ == "__main__": 20 | print(Solution().isValid("()[]{}")) # True -------------------------------------------------------------------------------- /leetcode/problem_2006.py: -------------------------------------------------------------------------------- 1 | ### Problem 2006. Count Number of Pairs With Absolute Difference K 2 | class Solution: 3 | def countKDifference(self, nums: List[int], k: int) -> int: 4 | diffs = {} 5 | count = 0 6 | for i in range(len(nums)): 7 | d = nums[i] - k 8 | a = nums[i] + k 9 | if(d in diffs): 10 | count += diffs[d] 11 | if(a in diffs): 12 | count += diffs[a] 13 | 14 | if(nums[i] in diffs): 15 | diffs[nums[i]] += 1 16 | else: 17 | diffs[nums[i]] = 1 18 | return count -------------------------------------------------------------------------------- /leetcode/problem_2016.py: -------------------------------------------------------------------------------- 1 | ### Problem 2016. Maximum Difference Between Increasing Elements (Easy) 2 | class Solution: 3 | def maximumDifference(self, nums: List[int]) -> int: 4 | start = 0 5 | end = start 6 | max_diff = 0 7 | while(end < len(nums)): 8 | diff = nums[end] - nums[start] 9 | if(nums[end] < nums[start]): 10 | start = end 11 | if(nums[end] - nums[start] > max_diff): 12 | max_diff = diff 13 | end += 1 14 | if(max_diff == 0): 15 | return -1 16 | else: 17 | return max_diff 18 | -------------------------------------------------------------------------------- /leetcode/problem_202.py: -------------------------------------------------------------------------------- 1 | # Problem 202. Happy Number (Easy): https://leetcode.com/problems/happy-number/ 2 | 3 | class Solution: 4 | def isHappy(self, n: int) -> bool: 5 | result = 0 6 | count = 0 7 | visited = {} 8 | while(n != 1): 9 | while(n != 0): 10 | rem = n%10 11 | n = n//10 12 | result += pow(rem, 2) 13 | count +=1 14 | n = result 15 | result = 0 16 | # If we encounter the same number again, then it will go into an infinite loop 17 | if(n in visited): 18 | return False 19 | else: 20 | visited[n] = True 21 | return True -------------------------------------------------------------------------------- /leetcode/problem_2022.py: -------------------------------------------------------------------------------- 1 | # Problem 2022: Convert 1D Array Into 2D Array (Medium) 2 | # tags: array, matrix 3 | class Solution: 4 | def construct2DArray(self, original: List[int], m: int, n: int) -> List[List[int]]: 5 | result = [] 6 | if(m * n != len(original)): 7 | return result 8 | i=0 9 | for row in range(m): 10 | r = [] 11 | for col in range(n): 12 | r.append(original[i]) 13 | i+=1 14 | result.append(r) 15 | return result -------------------------------------------------------------------------------- /leetcode/problem_2028.py: -------------------------------------------------------------------------------- 1 | ### Problem 2028. Find missing observations 2 | ### tags: array, math, simulation 3 | class Solution: 4 | def missingRolls(self, rolls: List[int], mean: int, n: int) -> List[int]: 5 | sumX = (mean) * (len(rolls) + n) - sum(rolls) 6 | result = [] 7 | if(sumX < n or sumX > (6 * n)): 8 | return [] 9 | while(n): 10 | numX = min(6, sumX - n + 1) 11 | result.append(numX) 12 | sumX -= numX 13 | n -= 1 14 | return result 15 | -------------------------------------------------------------------------------- /leetcode/problem_203.py: -------------------------------------------------------------------------------- 1 | ### Problem 203. Remove Linked List Elements (Easy): https://leetcode.com/problems/remove-linked-list-elements/ 2 | # Definition for singly-linked list. 3 | # class ListNode: 4 | # def __init__(self, val=0, next=None): 5 | # self.val = val 6 | # self.next = next 7 | class Solution: 8 | def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: 9 | current = head 10 | prev = None 11 | while(current): 12 | if(current.val == val): 13 | if(prev == None): 14 | current = current.next 15 | head = current 16 | else: 17 | prev.next = current.next 18 | current = current.next 19 | else: 20 | prev = current 21 | current = current.next 22 | return head 23 | -------------------------------------------------------------------------------- /leetcode/problem_2037.py: -------------------------------------------------------------------------------- 1 | ### Problem 2037. Minimum Number of Moves to Seat Everyone (Easy) 2 | ### Tags: Array, Greedy 3 | class Solution: 4 | def minMovesToSeat(self, seats: List[int], students: List[int]) -> int: 5 | seats.sort() 6 | students.sort() 7 | moves = 0 8 | for i in range(len(seats)): 9 | moves+= abs(seats[i] - students[i]) 10 | return moves -------------------------------------------------------------------------------- /leetcode/problem_205.py: -------------------------------------------------------------------------------- 1 | ### Problem 205. Isomorphic Strings (Easy): https://leetcode.com/problems/isomorphic-strings/ 2 | ### Tags: String, Hash Table 3 | 4 | class Solution: 5 | def isIsomorphic(self, s: str, t: str) -> bool: 6 | if(len(s) != len(t)): 7 | return False 8 | 9 | lmap = {} 10 | mapped = {} 11 | for i in range(len(s)): 12 | letter_s = s[i] 13 | letter_t = t[i] 14 | if(letter_s in lmap): 15 | if(lmap[letter_s] != letter_t): 16 | return False 17 | else: 18 | if(t[i] in mapped): 19 | return False 20 | lmap[letter_s] = letter_t 21 | mapped[letter_t] = letter_s 22 | return True 23 | -------------------------------------------------------------------------------- /leetcode/problem_2053.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | class Solution: 3 | def kthDistinct(self, arr: List[str], k: int) -> str: 4 | freq = Counter(arr) 5 | uniq = [key for key in freq.keys() if(freq[key] == 1)] 6 | if(len(uniq) < k): 7 | return '' 8 | return uniq[k-1] -------------------------------------------------------------------------------- /leetcode/problem_2064.py: -------------------------------------------------------------------------------- 1 | ### Problem 2064. Minimized Maximum of Products Distributed to Any Storeclass Solution: 2 | ### tags: array, Binary Search 3 | 4 | def minimizedMaximum(self, n: int, quantities: List[int]) -> int: 5 | def can_distribute(quantity): 6 | stores = 0 7 | for q in quantities: 8 | stores += math.ceil(q / quantity) 9 | return stores <= n 10 | start = 1 11 | end = max(quantities) 12 | result = 0 13 | while(start <= end): 14 | quantity = start + (end - start) // 2 15 | if(can_distribute(quantity)): 16 | result = quantity 17 | end = quantity - 1 18 | else: 19 | start = quantity + 1 20 | 21 | return result -------------------------------------------------------------------------------- /leetcode/problem_2073.py: -------------------------------------------------------------------------------- 1 | ### Problem 2073. Time Required to Buy N Tickets (Medium): https://leetcode.com/problems/time-required-to-buy-n-tickets/ 2 | 3 | ### Tags: Array, Greedy 4 | 5 | class Solution: 6 | def timeRequiredToBuy(self, tickets: List[int], k: int) -> int: 7 | time = 0 8 | for i in range(len(tickets)): 9 | ticket = tickets[i] 10 | if(i <= k): 11 | time += min(ticket, tickets[k]) 12 | else: 13 | time += min(ticket, tickets[k] - 1) 14 | return time 15 | -------------------------------------------------------------------------------- /leetcode/problem_2109.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def addSpaces(self, s: str, spaces: List[int]) -> str: 3 | index = 0 4 | i = 0 5 | res = '' 6 | while(index < len(spaces) and i < len(s)): 7 | if(i < spaces[index]): 8 | res += s[i] 9 | i += 1 10 | elif(i == spaces[index]): 11 | res += " " 12 | index += 1 13 | while(i < len(s)): 14 | res += s[i] 15 | i += 1 16 | return res -------------------------------------------------------------------------------- /leetcode/problem_2161.py: -------------------------------------------------------------------------------- 1 | ### Problem 2161. Partition Array According to Given Pivot 2 | ### tags: [array, two-pointers] 3 | 4 | class Solution: 5 | def pivotArray(self, nums: List[int], pivot: int) -> List[int]: 6 | lt, gt, pv = [], [], [] 7 | for num in nums: 8 | if(num < pivot): 9 | lt.append(num) 10 | elif(num > pivot): 11 | gt.append(num) 12 | else: 13 | pv.append(num) 14 | lt.extend(pv) 15 | lt.extend(gt) 16 | return lt 17 | -------------------------------------------------------------------------------- /leetcode/problem_217.py: -------------------------------------------------------------------------------- 1 | # Problem 217: Contains Duplicate (Easy): https://leetcode.com/problems/contains-duplicate/ 2 | class Solution: 3 | def containsDuplicate(self, nums): 4 | freq = {} 5 | for number in nums: 6 | if(number in freq): 7 | return True 8 | else: 9 | freq[number] = 1 10 | return False 11 | 12 | if __name__ == "__main__": 13 | nums = [1,2,3,1] 14 | print(Solution().containsDuplicate(nums)) -------------------------------------------------------------------------------- /leetcode/problem_2185.py: -------------------------------------------------------------------------------- 1 | ### Problem 2185. Counting Words With a Given Prefix (Easy): https://leetcode.com/problems/counting-words-with-a-given-prefix/ 2 | 3 | ### tags: array, string, string matchings 4 | class Solution: 5 | def prefixCount(self, words: List[str], pref: str) -> int: 6 | wordCount = 0 7 | i = 0 8 | for word in words: 9 | if(len(word) < len(pref)): 10 | continue 11 | k = 0 12 | j = 0 13 | while(j < len(pref) and k < len(word) and word[k] == pref[j]): 14 | j += 1 15 | k += 1 16 | if(j == len(pref)): 17 | wordCount += 1 18 | return wordCount -------------------------------------------------------------------------------- /leetcode/problem_219.py: -------------------------------------------------------------------------------- 1 | ### Problem 219. Contains Duplicate II (Easy): https://leetcode.com/problems/contains-duplicate-ii/ 2 | 3 | # Tags : Array, Hash Table 4 | class Solution: 5 | def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool: 6 | fr = {} 7 | for i in range(len(nums)): 8 | if(nums[i] not in fr): 9 | fr[nums[i]] = i 10 | else: 11 | if(abs(i-fr[nums[i]]) <= k): 12 | return True 13 | else: 14 | fr[nums[i]] = i 15 | return False 16 | -------------------------------------------------------------------------------- /leetcode/problem_2220.py: -------------------------------------------------------------------------------- 1 | ### Problem 2220. Minimum Bit Flips to Convert Number 2 | ### tags: bit manipulation 3 | class Solution: 4 | def minBitFlips(self, start: int, goal: int) -> int: 5 | # 100011 6 | # 010110 7 | # 110101 (XOR) 8 | mask = 1 9 | count = 0 10 | t = start ^ goal 11 | while(t > 0): 12 | if(t & 1): 13 | count += 1 14 | t >>= 1 15 | return count -------------------------------------------------------------------------------- /leetcode/problem_223.py: -------------------------------------------------------------------------------- 1 | ### Problem 223. Rectangle Area (Medium): https://leetcode.com/problems/rectangle-area/ 2 | ### Tags: Math, Geometry 3 | class Solution: 4 | def computeArea(self, ax1: int, ay1: int, ax2: int, ay2: int, bx1: int, by1: int, bx2: int, by2: int) -> int: 5 | a1 = (ax2-ax1) * (ay2-ay1) 6 | a2 = (bx2-bx1) * (by2-by1) 7 | 8 | # no overlapping 9 | if((ax2 < bx1 or ax1 > bx2) or ((by2 <= ay1) or (by1 >= ay2))): 10 | return a1 + a2 11 | x1 = max(ax1, bx1) 12 | y1 = max(ay1, by1) 13 | 14 | x2 = min(ax2, bx2) 15 | y2 = min(ay2, by2) 16 | 17 | overlapped = abs(x2-x1) * abs(y2-y1) 18 | 19 | return a1 + a2 - overlapped -------------------------------------------------------------------------------- /leetcode/problem_2236.py: -------------------------------------------------------------------------------- 1 | ### Problem 2236. Root equals sum of children (Easy): https://leetcode.com/problems/root-equals-sum-of-children/ 2 | class Solution: 3 | def checkTree(self, root: Optional[TreeNode]) -> bool: 4 | return root.val == (root.left.val + root.right.val) -------------------------------------------------------------------------------- /leetcode/problem_225.py: -------------------------------------------------------------------------------- 1 | class MyStack: 2 | 3 | def __init__(self): 4 | self.queue = [] 5 | 6 | def push(self, x: int) -> None: 7 | self.queue.append(x) 8 | 9 | def pop(self) -> int: 10 | if(self.queue): 11 | return self.queue.pop(); 12 | 13 | def top(self) -> int: 14 | if(self.queue): 15 | return self.queue[-1] 16 | 17 | 18 | def empty(self) -> bool: 19 | return len(self.queue) == 0 20 | 21 | 22 | # Your MyStack object will be instantiated and called as such: 23 | # obj = MyStack() 24 | # obj.push(x) 25 | # param_2 = obj.pop() 26 | # param_3 = obj.top() 27 | # param_4 = obj.empty() -------------------------------------------------------------------------------- /leetcode/problem_2255.py: -------------------------------------------------------------------------------- 1 | ### Problem 2255. Count Prefixes of a Given String (Easy): https://leetcode.com/problems/count-number-of-words/ 2 | 3 | ### tags: string, array 4 | class Solution: 5 | def countPrefixes(self, words: List[str], s: str) -> int: 6 | def is_prefix(word): 7 | i, j = 0, 0 8 | if(len(word) > len(s)): 9 | return False 10 | while(i < len(word) and j < len(s) and word[i] == s[j]): 11 | i += 1 12 | j += 1 13 | return i == len(word) 14 | 15 | count = 0 16 | for word in words: 17 | if(is_prefix(word)): 18 | count += 1 19 | return count -------------------------------------------------------------------------------- /leetcode/problem_226.py: -------------------------------------------------------------------------------- 1 | ### Problem 226. Invert Binary Tree (Easy) https://leetcode.com/problems/invert-binary-tree/ 2 | 3 | ### Tags: Binary Tree, Recursion 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: 12 | if(root is None): 13 | return root 14 | 15 | temp = root.left 16 | root.left = root.right 17 | root.right = temp 18 | self.invertTree(root.left) 19 | self.invertTree(root.right) 20 | return root -------------------------------------------------------------------------------- /leetcode/problem_2265.py: -------------------------------------------------------------------------------- 1 | ### Problem 2265. Count Nodes Equal to Average of Subtree (Medium): https://leetcode.com/problems/count-nodes-equal-to-average-of-subtree/ 2 | 3 | ### Tags: Tree, Recursion 4 | 5 | class Solution: 6 | def averageOfSubtree(self, root: TreeNode) -> int: 7 | result = 0 8 | def average(root: TreeNode): 9 | nonlocal result 10 | if(root is None): 11 | return (0, 0) 12 | left_pair = average(root.left) 13 | right_pair = average(root.right) 14 | count = 1 + left_pair[1] + right_pair[1] 15 | sum_n = root.val + left_pair[0] + right_pair[0] 16 | avg = (sum_n // count) 17 | 18 | if(avg == root.val): 19 | result += 1 20 | return (sum_n, count) 21 | 22 | average(root) 23 | return result -------------------------------------------------------------------------------- /leetcode/problem_232.py: -------------------------------------------------------------------------------- 1 | ### Problem 232. Implement Queue using Stacks (Easy): https://leetcode.com/problems/implement-queue-using-stacks/ 2 | 3 | class MyQueue: 4 | 5 | def __init__(self): 6 | self.stack =[] 7 | 8 | def push(self, x: int) -> None: 9 | self.stack.append(x) 10 | 11 | def pop(self) -> int: 12 | if(self.stack): 13 | return self.stack.pop(0) 14 | 15 | def peek(self) -> int: 16 | if(self.stack): 17 | return self.stack[0] 18 | 19 | def empty(self) -> bool: 20 | return len(self.stack) == 0 21 | 22 | 23 | # Your MyQueue object will be instantiated and called as such: 24 | # obj = MyQueue() 25 | # obj.push(x) 26 | # param_2 = obj.pop() 27 | # param_3 = obj.peek() 28 | # param_4 = obj.empty() -------------------------------------------------------------------------------- /leetcode/problem_2331.py: -------------------------------------------------------------------------------- 1 | # Definition for a binary tree node. 2 | # class TreeNode: 3 | # def __init__(self, val=0, left=None, right=None): 4 | # self.val = val 5 | # self.left = left 6 | # self.right = right 7 | class Solution: 8 | def evaluateTree(self, root: Optional[TreeNode]) -> bool: 9 | if((not root.left) and (not root.right)): 10 | return root.val == 1 11 | 12 | if(root.val == 2): 13 | return ( 14 | self.evaluateTree(root.left) or self.evaluateTree(root.right) 15 | ) 16 | if(root.val == 3): 17 | return ( 18 | self.evaluateTree(root.left) and self.evaluateTree(root.right) 19 | ) -------------------------------------------------------------------------------- /leetcode/problem_234.py: -------------------------------------------------------------------------------- 1 | # Problem 234. Palindrome Linked List (Easy): https://leetcode.com/problems/palindrome-linked-list/ 2 | 3 | class Solution: 4 | def isPalindrome(self, head: Optional[ListNode]) -> bool: 5 | start = head 6 | forward = '' 7 | while(start): 8 | forward += str(start.val) 9 | start = start.next 10 | return forward == forward[::-1] 11 | 12 | -------------------------------------------------------------------------------- /leetcode/problem_236.py: -------------------------------------------------------------------------------- 1 | ### Problem 236: Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. 2 | ### Tags: [Tree] 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, x): 7 | # self.val = x 8 | # self.left = None 9 | # self.right = None 10 | 11 | # time complexity: O(n), space complexity: O(n) 12 | class Solution: 13 | def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': 14 | if(root is None): 15 | return None 16 | elif(root.val == p.val or root.val == q.val): 17 | return root 18 | 19 | found_left = self.lowestCommonAncestor(root.left, p, q) 20 | found_right = self.lowestCommonAncestor(root.right, p, q) 21 | 22 | if(found_left and found_right): 23 | return root 24 | elif(found_left and not found_right): 25 | return found_left 26 | elif(not found_left and found_right): 27 | return found_right 28 | else: 29 | return None -------------------------------------------------------------------------------- /leetcode/problem_237.py: -------------------------------------------------------------------------------- 1 | # Problem 237. Delete Node in a Linked List (Medium): https://leetcode.com/problems/delete-node-in-a-linked-list/description/ 2 | 3 | # hint:You are not supposed to deletet the node as mentioned in the problem statement. 4 | class Solution: 5 | def deleteNode(self, node): 6 | prev = None 7 | while(node.next): 8 | node.val = node.next.val 9 | prev = node 10 | node = node.next 11 | prev.next = None 12 | 13 | -------------------------------------------------------------------------------- /leetcode/problem_2373.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def largestLocal(self, grid: List[List[int]]) -> List[List[int]]: 3 | m = len(grid) - 2 4 | maxLocal = [[0 for i in range(m)] for i in range(m)] 5 | for i in range(m): 6 | for j in range(m): 7 | max_num = 0 8 | for k in range(i, i+3): 9 | for l in range(j, j+3): 10 | if(grid[k][l] > max_num): 11 | max_num = grid[k][l] 12 | maxLocal[i][j] = max_num 13 | return maxLocal -------------------------------------------------------------------------------- /leetcode/problem_2395.py: -------------------------------------------------------------------------------- 1 | ### Problem 2395. Find Subarrays with Equal Sum (Medium) 2 | ### tags: Array, Hash table 3 | 4 | # Time complexity: O(n^2) 5 | # Memory complexity: O(1) 6 | class Solution: 7 | def findSubarrays(self, nums: List[int]) -> bool: 8 | for i in range(len(nums) - 1): 9 | for j in range(i+1, len(nums) - 1): 10 | if(nums[i] + nums[i + 1] == nums[j] + nums[j + 1]): 11 | return True 12 | return False 13 | 14 | # Time complexity: O(n) 15 | # Memory complexity: O(n) 16 | class Solution: 17 | def findSubarrays(self, nums: List[int]) -> bool: 18 | lookUp = {} 19 | for i in range(1, len(nums)): 20 | s = nums[i] + nums[i - 1] 21 | if(s in lookUp): 22 | return True 23 | else: 24 | lookUp[s] = i - 1 25 | return False -------------------------------------------------------------------------------- /leetcode/problem_2418.py: -------------------------------------------------------------------------------- 1 | ### Problem 2418. Sort People by Height 2 | ### Tags: Array, Sorting 3 | class Solution: 4 | def sortPeople(self, names: List[str], heights: List[int]) -> List[str]: 5 | mapping = {} 6 | for i in range(len(heights)): 7 | height = heights[i] 8 | name = names[i] 9 | mapping[height] = name 10 | rev_heights = sorted(heights,reverse = True) 11 | result = [] 12 | for i in range(len(rev_heights)): 13 | height = rev_heights[i] 14 | result.append(mapping[height]) 15 | return result -------------------------------------------------------------------------------- /leetcode/problem_2486.py: -------------------------------------------------------------------------------- 1 | ### Problem 2486. Append Characters to String to Make Subsequence (Medium) 2 | ### Tags: String, Two Pointers, Greedy 3 | 4 | # Hint: compare the characters of s and t, if they are equal, move both pointers, otherwise move only the pointer of s 5 | class Solution: 6 | def appendCharacters(self, s: str, t: str) -> int: 7 | i = 0 8 | j = 0 9 | count = 0 10 | while(i < len(s) and j < len(t)): 11 | if(s[i] == t[j]): 12 | i += 1 13 | j += 1 14 | else: 15 | i += 1 16 | if(i == len(s)): 17 | return len(t) - j 18 | else: 19 | return 0 -------------------------------------------------------------------------------- /leetcode/problem_2490.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def isCircularSentence(self, sentence: str) -> bool: 3 | 4 | # one word 5 | # first and last letter of sentence should be equal 6 | # if space at i > 0 i-1 and i + 1 should be equal 7 | # no leading or trailing space 8 | for i, letter in enumerate(sentence): 9 | if(sentence[i] == ' ' and i > 0 and sentence[i - 1] != sentence[i + 1]): 10 | return False 11 | elif(i == 0 and sentence[0] != sentence[-1]): 12 | return False 13 | return True -------------------------------------------------------------------------------- /leetcode/problem_2516.py: -------------------------------------------------------------------------------- 1 | ### Problem 2516. Take K of Each Character From Left and Right Side (Medium): https://leetcode.com/problems/take-k-of-each-character-from-left-and-right/ 2 | 3 | ### tags: hash table, sliding window, string 4 | 5 | ### hint: increase the window until we have k of each character, resulting string is outside of the window 6 | 7 | class Solution: 8 | def takeCharacters(self, s: str, k: int) -> int: 9 | freq = Counter(s) 10 | if(not (freq['a'] >= k and freq['b'] >=k and freq['c'] >=k)): 11 | return -1 12 | 13 | start = 0 14 | result = float('inf') 15 | for end in range(len(s)): 16 | freq[s[end]] -=1 17 | while(freq['a'] < k or freq['b'] < k or freq['c'] < k): 18 | freq[s[start]] += 1 19 | start += 1 20 | 21 | result = min(result, len(s) - (end - start + 1)) 22 | return result 23 | -------------------------------------------------------------------------------- /leetcode/problem_2554.py: -------------------------------------------------------------------------------- 1 | ### Problem 2554. Maximum Number of Integers to Choose From a Range I 2 | ### tags: Array, Hash Table 3 | class Solution: 4 | def maxCount(self, banned: List[int], n: int, maxSum: int) -> int: 5 | # 0: NC, 1: C, -1: Ban 6 | # [-1, 0, 0, 0, -1] 7 | nums = [0] * n 8 | for index in banned: 9 | if(index <= len(nums)): 10 | nums[index - 1] = -1 11 | s = 0 12 | count = 0 13 | for i in range(len(nums)): 14 | num = nums[i] 15 | index = i + 1 16 | if(num == -1): 17 | continue 18 | if(s + index > maxSum): 19 | break 20 | s = s + index 21 | nums[i] = 1 22 | count += 1 23 | # print("nums = ", nums) 24 | return count -------------------------------------------------------------------------------- /leetcode/problem_2558.py: -------------------------------------------------------------------------------- 1 | ### Problem 2558. Pick Gifts (Medium) 2 | 3 | class Solution: 4 | def pickGifts(self, gifts: List[int], k: int) -> int: 5 | result = 0 6 | max_h = [] 7 | for i in range(len(gifts)): 8 | result += gifts[i] 9 | heapq.heappush(max_h, gifts[i]*-1) 10 | for i in range(k): 11 | max_g = -1 * heapq.heappop(max_h) 12 | g = math.floor(math.sqrt(max_g)) 13 | heapq.heappush(max_h, -1 * g) 14 | result = result - max_g + g 15 | return result -------------------------------------------------------------------------------- /leetcode/problem_2559.py: -------------------------------------------------------------------------------- 1 | ### 2559. Count Vowel Strings in Ranges 2 | ### tags: prefix sum, array 3 | class Solution: 4 | def vowelStrings(self, words: List[str], queries: List[List[int]]) -> List[int]: 5 | result = [] 6 | vowels = ['a', 'e', 'i', 'o', 'u'] 7 | prefix_vowels = [] 8 | 9 | def isVowel(i): 10 | return words[i][0] in vowels and words[i][-1] in vowels 11 | prefix_vowels.append(1 if isVowel(0) else 0) 12 | 13 | for i in range(1, len(words)): 14 | w = 1 if isVowel(i) else 0 15 | prefix_vowels.append(prefix_vowels[i-1] + w) 16 | print(prefix_vowels) 17 | 18 | for s, e in queries: 19 | c = 1 if isVowel(s) else 0 20 | result.append(prefix_vowels[e] - prefix_vowels[s] + c) 21 | return result -------------------------------------------------------------------------------- /leetcode/problem_258.py: -------------------------------------------------------------------------------- 1 | ### Problem 258. Add Digits (Easy): https://leetcode.com/problems/add-digits/ 2 | class Solution: 3 | def addDigits(self, num: int) -> int: 4 | while(num > 9): 5 | sum = 0 6 | while(num != 0): 7 | sum += num % 10 8 | num = num // 10 9 | num = sum 10 | return num -------------------------------------------------------------------------------- /leetcode/problem_2582.py: -------------------------------------------------------------------------------- 1 | ### Problem 2582. Pass the Pillow (Easy): https://leetcode.com/problems/pass-the-pillow/ 2 | 3 | class Solution: 4 | def passThePillow(self, n: int, time: int) -> int: 5 | if(time < n): 6 | return time + 1 7 | elif(time == n): 8 | return n - 1 9 | else: 10 | pos = 1 11 | inc = 1 12 | for i in range(time): 13 | if(pos == n and inc == 1): 14 | inc *= -1 15 | if(pos == 1 and inc == -1): 16 | inc *= -1 17 | pos += inc 18 | return pos -------------------------------------------------------------------------------- /leetcode/problem_263.py: -------------------------------------------------------------------------------- 1 | ### Problem 263. Ugly Number 2 | 3 | ### Tags: Math, Recursion 4 | 5 | class Solution: 6 | def isUgly(self, n: int) -> bool: 7 | if(n == 1): 8 | return True 9 | if(n < 1): 10 | return False 11 | if(n % 2 == 0): 12 | return self.isUgly(n//2) 13 | elif(n % 3 == 0): 14 | return self.isUgly(n//3) 15 | elif(n % 5 == 0): 16 | return self.isUgly(n//5) 17 | else: 18 | return False -------------------------------------------------------------------------------- /leetcode/problem_264.py: -------------------------------------------------------------------------------- 1 | ### Problem 264. Ugly Number II (Medium): https://leetcode.com/problems/ugly-number-ii/ 2 | ### tags: heap, dynamic programming 3 | class Solution: 4 | def nthUglyNumber(self, n: int) -> int: 5 | seen = set() 6 | heap = [1] 7 | i = 1 8 | factors = [2, 3, 5] 9 | for i in range(n): 10 | num = heapq.heappop(heap) 11 | if(i == n - 1): 12 | return num 13 | for f in factors: 14 | if(f * num not in seen): 15 | seen.add(num * f) 16 | heapq.heappush(heap, num * f) -------------------------------------------------------------------------------- /leetcode/problem_2678.py: -------------------------------------------------------------------------------- 1 | ### Problem 2678. Number of Senior Citizens 2 | 3 | ### Tags: Array, String 4 | 5 | class Solution: 6 | def countSeniors(self, details: List[str]) -> int: 7 | count = 0 8 | for passenger in details: 9 | age = passenger[11:13] 10 | if(int(age[0]) > 6): 11 | count +=1 12 | elif(age[0] == '6' and age[1] != '0'): 13 | count+=1 14 | return count -------------------------------------------------------------------------------- /leetcode/problem_2696.py: -------------------------------------------------------------------------------- 1 | ### Problem 2696:Minimum String Length After Removing Substrings (Easy): https://leetcode.com/problems/minimum-string-length-after-removing-substrings 2 | 3 | ### tags: stack 4 | class Solution: 5 | def minLength(self, s: str) -> int: 6 | stack = [] 7 | end = 0 8 | while(end != len(s)): 9 | if(not stack): 10 | stack.append(s[end]) 11 | else: 12 | stack.append(s[end]) 13 | top = "".join(stack[-2:]) 14 | if(top == 'AB' or top == "CD"): 15 | stack.pop() 16 | stack.pop() 17 | end += 1 18 | return len(stack) -------------------------------------------------------------------------------- /leetcode/problem_27.py: -------------------------------------------------------------------------------- 1 | # Problem 27 (Easy): https://leetcode.com/problems/remove-element/ 2 | 3 | class Solution: 4 | def removeElement(self, nums: List[int], val: int) -> int: 5 | count = 0 6 | i = 0 7 | while(i < len(nums)): 8 | print(len(nums), i) 9 | if(nums[i] == val): 10 | del nums[i] 11 | else: 12 | i = i + 1 13 | count += 1 14 | return count 15 | 16 | if __name__ == "__main__": 17 | nums = [3,2,2,3] 18 | val = 3 19 | print(Solution().removeElement(nums, val)) # 2 20 | nums = [0,1,2,2,3,0,4,2] 21 | val = 2 22 | print(Solution().removeElement(nums, val)) # 5 23 | nums = [1] 24 | val = 1 25 | print(Solution().removeElement(nums, val)) # 0 26 | nums = [1,2,4,5,6] 27 | val = 3 28 | print(Solution().removeElement(nums, val)) # 5 -------------------------------------------------------------------------------- /leetcode/problem_274.py: -------------------------------------------------------------------------------- 1 | # Problem 274 : H-Index (https://leetcode.com/problems/h-index/) 2 | class Solution: 3 | def hIndex(self, citations: List[int]) -> int: 4 | hfreq = {} 5 | start = 0 6 | max_cit = 0 7 | min_cit = 1000 8 | length = len(citations) 9 | sorted_citations = sorted(citations) 10 | while(start < length): 11 | hfreq[sorted_citations[start]] = length - start 12 | start += 1 13 | while(start != length and sorted_citations[start - 1] == sorted_citations[start]): 14 | start += 1 15 | hMax = 0 16 | for key, value in hfreq.items(): 17 | if min(key,value) >= hMax: 18 | hMax = min(key,value) 19 | return hMax 20 | 21 | if __name__ == '__main__': 22 | s = Solution(); 23 | result = s.hIndex([3,0,6,1,5]); #3 24 | print(result); 25 | result = s.hIndex([1,3,1]); #1 26 | print(result); -------------------------------------------------------------------------------- /leetcode/problem_2816.py: -------------------------------------------------------------------------------- 1 | # Problem 2816. Double the Linked List (Medium): https://leetcode.com/problems/double-the-linked-list/ 2 | 3 | class Solution: 4 | def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]: 5 | current = self.reverse(head) 6 | carry = 0 7 | temp = current 8 | prev = None 9 | while(temp): 10 | num = temp.val*2 + carry 11 | temp.val = num % 10 12 | carry = num//10 13 | prev = temp 14 | temp = temp.next 15 | if(carry != 0): 16 | prev.next = ListNode(carry) 17 | return self.reverse(current) 18 | 19 | def reverse(self, head: ListNode)-> ListNode: 20 | current = head 21 | prev = None 22 | while(current): 23 | temp = current.next 24 | current.next = prev 25 | prev = current 26 | current = temp 27 | return prev 28 | -------------------------------------------------------------------------------- /leetcode/problem_290.py: -------------------------------------------------------------------------------- 1 | ### Problem 290. Word Pattern (Easy) 2 | ### Tags: Strings, Hash Table 3 | 4 | class Solution: 5 | def wordPattern(self, pattern: str, s: str) -> bool: 6 | words = s.split(' ') 7 | if(len(words) != len(pattern)): 8 | return False 9 | matches = {} 10 | rev_match = {} 11 | for index, word in enumerate(words): 12 | if((pattern[index] in matches) and matches[pattern[index]] != word): 13 | return False 14 | else: 15 | if((word in rev_match) and (rev_match[word] != pattern[index])): 16 | return False 17 | matches[pattern[index]] = word 18 | rev_match[word] = pattern[index] 19 | return True 20 | -------------------------------------------------------------------------------- /leetcode/problem_2924.py: -------------------------------------------------------------------------------- 1 | ### Problem 2924. Find the Champion (Medium): https://leetcode.com/problems/find-the-champion/ 2 | ### tags: graph 3 | 4 | class Solution: 5 | def findChampion(self, n: int, edges: List[List[int]]) -> int: 6 | incoming = {} 7 | for i in range(n): 8 | incoming[i] = 0 9 | 10 | for src, dest in edges: 11 | incoming[dest] += 1 12 | 13 | count = 0 14 | champions = [] 15 | for k , v in incoming.items(): 16 | if(v == 0): 17 | champions.append(k) 18 | if(len(champions) > 1): 19 | return -1 20 | return champions[0] 21 | -------------------------------------------------------------------------------- /leetcode/problem_2965.py: -------------------------------------------------------------------------------- 1 | ### Problem 2965. Find Missing and Repeated Values (Easy): https://leetcode.com/problems/find-missing-and-repeated-values/ 2 | ### tags: array, set, math 3 | 4 | class Solution: 5 | def findMissingAndRepeatedValues(self, grid: List[List[int]]) -> List[int]: 6 | s = set() 7 | dup = -1 8 | for i in range(len(grid)): 9 | for j in range(len(grid[0])): 10 | if(grid[i][j] in s): 11 | dup = grid[i][j] 12 | else: 13 | s.add(grid[i][j]) 14 | missing = -1 15 | for i in range(1, len(s) + 2): 16 | if(i not in s): 17 | missing = i 18 | break 19 | return [dup, missing] 20 | -------------------------------------------------------------------------------- /leetcode/problem_2974.py: -------------------------------------------------------------------------------- 1 | ### Problem 2974. Minimum Number Game (Easy) 2 | 3 | class Solution: 4 | def numberGame(self, nums: List[int]) -> List[int]: 5 | heapq.heapify(nums) 6 | result = [] 7 | while(len(nums) > 0): 8 | sm_alice = heapq.heappop(nums) 9 | sm_bob = heapq.heappop(nums) 10 | result.append(sm_bob) 11 | result.append(sm_alice) 12 | return result -------------------------------------------------------------------------------- /leetcode/problem_3.py: -------------------------------------------------------------------------------- 1 | # Problem 3: Longest Substring Without Repeating Characters (Medium): https://leetcode.com/problems/longest-substring-without-repeating-characters/ 2 | 3 | class Solution(object): 4 | def lengthOfLongestSubstring(self,s): 5 | count = 0 6 | back = 0 7 | front = 0 8 | if(len(s)==0): 9 | return count 10 | while(front < len(s)): 11 | string = s[back:front] 12 | if(string.find(s[front]) == -1): 13 | front += 1 14 | count = max(count, len(string)) 15 | else: 16 | back += 1 17 | return count+1 18 | 19 | if __name__ == "__main__": 20 | s = "abcabcbb" 21 | print(Solution().lengthOfLongestSubstring(s)) # 3 22 | -------------------------------------------------------------------------------- /leetcode/problem_3016.py: -------------------------------------------------------------------------------- 1 | ### Problem 3016.Minimum Number of Pushes to Type Word II (Medium) 2 | ### tags: greedy, string, sorting, counter, hashmap 3 | class Solution: 4 | def minimumPushes(self, word: str) -> int: 5 | maps = {} 6 | visited = [False for i in range(26)] 7 | freq = Counter(word) 8 | sorted_freq = sorted(freq.items(), key=lambda item: item[1], reverse=True) 9 | count = 0 10 | tap = 1 11 | taps = 0 12 | for i in range(len(sorted_freq)): 13 | if(count % 8 == 0 and count != 0): 14 | tap += 1 15 | taps += (tap * sorted_freq[i][1]) 16 | count += 1 17 | return taps -------------------------------------------------------------------------------- /leetcode/problem_303.py: -------------------------------------------------------------------------------- 1 | ### Problem 303. Range Sum Query - Immutable (Easy) 2 | ### tags: prefix sum, array 3 | class NumArray: 4 | 5 | def __init__(self, nums: List[int]): 6 | self.pref_sum = [nums[0]] 7 | self.arr = nums 8 | for i in range(1, len(nums)): 9 | self.pref_sum.append(self.pref_sum[i-1] + nums[i]) 10 | 11 | def sumRange(self, left: int, right: int) -> int: 12 | return self.pref_sum[right] - self.pref_sum[left] + self.arr[left] 13 | 14 | 15 | # Your NumArray object will be instantiated and called as such: 16 | # obj = NumArray(nums) 17 | # param_1 = obj.sumRange(left,right) -------------------------------------------------------------------------------- /leetcode/problem_3042.py: -------------------------------------------------------------------------------- 1 | ### Problem 3042. Count Prefix and Suffix Pairs I 2 | ### tags: string, array, hashfunction 3 | class Solution: 4 | def countPrefixSuffixPairs(self, words: List[str]) -> int: 5 | count = 0 6 | for i in range(len(words)): 7 | for j in range(i+1, len(words)): 8 | if(self.isPrefixAndSuffix(words[i], words[j])): 9 | count += 1 10 | return count 11 | 12 | def isPrefixAndSuffix(self, str1, str2): 13 | if(len(str2)< len(str1)): 14 | return False 15 | else: 16 | n = len(str1) 17 | m = len(str2) 18 | pref = str2[0:n] 19 | suff = str2[m - n: m] 20 | return suff == pref == str1 -------------------------------------------------------------------------------- /leetcode/problem_3043.py: -------------------------------------------------------------------------------- 1 | ### Problem 3043. Longest Common Prefix (Medium): https://leetcode.com/problems/longest-common-prefix/ 2 | 3 | ### tags: array, hashtable, string, trie 4 | class Solution: 5 | def longestCommonPrefix(self, arr1: List[int], arr2: List[int]) -> int: 6 | prefixes = set() 7 | 8 | for num in arr2: 9 | while(num != 0): 10 | prefixes.add(num) 11 | num //= 10 12 | 13 | max_len = 0 14 | for num in arr1: 15 | if(num in prefixes): 16 | max_len = max(max_len, len(str(num))) 17 | else: 18 | while(num != 0): 19 | if(num in prefixes): 20 | max_len = max(max_len, len(str(num))) 21 | break 22 | num //= 10 23 | return max_len 24 | 25 | 26 | -------------------------------------------------------------------------------- /leetcode/problem_3075.py: -------------------------------------------------------------------------------- 1 | ### Problem 3075. Maximum Happiness Sum (Medium) 2 | class Solution: 3 | def maximumHappinessSum(self, happiness: List[int], k: int) -> int: 4 | sorted_happiness = sorted(happiness) 5 | total_happiness = 0 6 | reduction = 0 7 | n = len(sorted_happiness) 8 | for i in range(n-1, n-k-1, -1): 9 | happy = sorted_happiness[i] - reduction 10 | total_happiness += max(happy, 0) 11 | reduction += 1 12 | # 1 2 3 4 5 13 | 5, 3, 2, 1 14 | return total_happiness -------------------------------------------------------------------------------- /leetcode/problem_3110.py: -------------------------------------------------------------------------------- 1 | ### Problem 3110. Score of a String (Easy): https://leetcode.com/problems/score-of-a-string/ 2 | class Solution: 3 | def scoreOfString(self, s: str) -> int: 4 | score = 0 5 | for i in range(1, len(s)): 6 | score += abs(ord(s[i]) - ord(s[i-1])) 7 | return score 8 | 9 | -------------------------------------------------------------------------------- /leetcode/problem_3114.py: -------------------------------------------------------------------------------- 1 | ### Problem 3114. Latest Time You Can Obtain After Replacing Characters (Easy): https://leetcode.com/problems/latest-time-by-replacing-hidden-digits/ 2 | class Solution: 3 | def findLatestTime(self, s: str) -> str: 4 | s = list(s) 5 | if(s[0] == '?' and s[1] == '?'): 6 | s[0] = '1' 7 | s[1] = '1' 8 | elif(s[0] == '?' and int(s[1]) < 2 ): 9 | s[0] = '1' 10 | elif(s[0] == '?' and int(s[1]) > 1 ): 11 | s[0] = '0' 12 | elif(s[0] == '0' and s[1] == '?'): 13 | s[1] = '9' 14 | elif(s[0] == '1' and s[1] == '?'): 15 | s[1] = '1' 16 | 17 | if(s[3] == '?'): 18 | s[3] = '5' 19 | if(s[4] == '?'): 20 | s[4] = '9' 21 | return "".join(s) -------------------------------------------------------------------------------- /leetcode/problem_3120.py: -------------------------------------------------------------------------------- 1 | ### Problem 3120. Number of Special Characters in a String (Easy): https://leetcode.com/problems/number-of-special-characters-in-a-string/ 2 | 3 | class Solution: 4 | def numberOfSpecialChars(self, word: str) -> int: 5 | special = {} 6 | unique = '' 7 | for letter in word: 8 | isupper = letter.isupper() 9 | if(letter not in special): 10 | special[letter] = 1 11 | if(isupper): 12 | if(letter.lower() not in special): 13 | unique += letter 14 | else: 15 | if(letter.upper() not in special): 16 | unique += letter 17 | else: 18 | special[letter] += 1 19 | count = 0 20 | for letter in unique: 21 | if(letter.isupper() and (letter.lower() in special)): 22 | count += 1 23 | elif(letter.islower() and (letter.upper() in special)): 24 | count += 1 25 | return count -------------------------------------------------------------------------------- /leetcode/problem_3136.py: -------------------------------------------------------------------------------- 1 | ### Problem 3136. Valid Word (Easy): https://leetcode.com/problems/valid-word/ 2 | class Solution: 3 | def isValid(self, word: str) -> bool: 4 | result = True 5 | hasVowel = False 6 | hasCon = False 7 | if(len(word) < 3): 8 | return False 9 | for letter in word: 10 | ascii = ord(letter) 11 | if(not ((ascii >= 97 and ascii < 123) or (ascii >= 65 and ascii < 91) or (ascii >= 48 and ascii < 58))): 12 | result = False 13 | break 14 | else: 15 | if(letter == 'a' or letter =='e' or letter =='i' or letter == 'o' or letter == 'u' or letter == 'A' or letter =='E' or letter =='I' or letter == 'O' or letter == 'U'): 16 | hasVowel = True 17 | else: 18 | if((not hasCon) and not (ascii >= 48 and ascii < 58)): 19 | hasCon = True 20 | 21 | if(not hasVowel or (not hasCon)): 22 | return False 23 | return result 24 | -------------------------------------------------------------------------------- /leetcode/problem_3151.py: -------------------------------------------------------------------------------- 1 | ### Problem 3151. Check if Array Is Special 2 | ### Tags: Array 3 | 4 | class Solution: 5 | def isArraySpecial(self, nums: List[int]) -> bool: 6 | for i in range(1, len(nums)): 7 | x = nums[i-1] 8 | y = nums[i] 9 | # check if different parity 10 | if((x ^ y) & 1 == 0): 11 | return False 12 | return True -------------------------------------------------------------------------------- /leetcode/problem_3217.py: -------------------------------------------------------------------------------- 1 | ### Probblem 3217: Remove Linked List Elements 2 | ### tags: Array, Hash table, Linked List 3 | # Definition for singly-linked list. 4 | # class ListNode: 5 | # def __init__(self, val=0, next=None): 6 | # self.val = val 7 | # self.next = next 8 | class Solution: 9 | def modifiedList(self, nums: List[int], head: Optional[ListNode]) -> Optional[ListNode]: 10 | hashset = set(nums) 11 | current = head 12 | prev = None 13 | while(current): 14 | if(current.val in hashset): 15 | if(current == head): 16 | current = current.next 17 | head = current 18 | else: 19 | prev.next = current.next 20 | current = current.next 21 | else: 22 | prev = current 23 | current = current.next 24 | return head -------------------------------------------------------------------------------- /leetcode/problem_3243.py: -------------------------------------------------------------------------------- 1 | ### Problem 3243. Shortest Distance to Target Color 2 | ### tags: graph, bfs 3 | 4 | class Solution: 5 | def shortestDistanceAfterQueries(self, n: int, queries: List[List[int]]) -> List[int]: 6 | adj = {} 7 | def shortest_distance(source): 8 | q = deque() 9 | q.append((source, 0)) 10 | distance = 0 11 | visited = set() 12 | visited.add(0) 13 | while(len(q) != 0): 14 | t, dist = q.popleft() 15 | if(t == n - 1): 16 | return dist 17 | for neighbor in adj[t]: 18 | if(neighbor not in visited): 19 | q.append((neighbor, dist + 1)) 20 | visited.add(neighbor) 21 | 22 | for i in range(n - 1): 23 | adj[i] = [i + 1] 24 | adj[n-1] = [] 25 | result = [] 26 | for src, dest in queries: 27 | adj[src].append(dest) 28 | result.append(shortest_distance(0)) 29 | return result -------------------------------------------------------------------------------- /leetcode/problem_3264.py: -------------------------------------------------------------------------------- 1 | #### Problem 3264. Final Array State After K Multiplication Operations I 2 | ### tags: heap, array 3 | class Solution: 4 | def getFinalState(self, nums: List[int], k: int, multiplier: int) -> List[int]: 5 | min_h = [] 6 | for i in range(len(nums)): 7 | heapq.heappush(min_h, (nums[i], i)) 8 | 9 | for i in range(k): 10 | min_val, index = heapq.heappop(min_h) 11 | heapq.heappush(min_h,(min_val * multiplier, index)) 12 | nums[index] = min_val * multiplier 13 | return nums -------------------------------------------------------------------------------- /leetcode/problem_34.py: -------------------------------------------------------------------------------- 1 | ### Problem 34. Find First and Last Position of Element in Sorted Array (Medium): https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ 2 | 3 | class Solution: 4 | def searchRange(self, nums: List[int], target: int) -> List[int]: 5 | result = [-1, -1] 6 | if(len(nums) == 0 or target < nums[0] or target > nums[-1]): 7 | return result 8 | i = 0 9 | while(nums[i] != target and i < len(nums)): 10 | if(nums[i] > target): 11 | return [-1, -1] 12 | i+=1 13 | result[0] = i 14 | i = len(nums) - 1 15 | while(nums[i] != target and i > result[0]): 16 | i -= 1 17 | result[1] = i 18 | return result 19 | 20 | -------------------------------------------------------------------------------- /leetcode/problem_344.py: -------------------------------------------------------------------------------- 1 | ### Problem 344. Reverse String (Easy): https://leetcode.com/problems/reverse-string/ 2 | class Solution: 3 | def reverseString(self, s: List[str]) -> None: 4 | """ 5 | Do not return anything, modify s in-place instead. 6 | """ 7 | return self.reversed(0, len(s)-1, s) 8 | 9 | def reversed(self, start:int, end:int, s: List[str])-> List[str]: 10 | if(start >= end): 11 | return s 12 | else: 13 | temp = s[end] 14 | s[end] = s[start] 15 | s[start] = temp 16 | return self.reversed(start + 1, end - 1, s) 17 | 18 | ### Iterative 19 | class Solution2: 20 | def reverseString(self, s: List[str]) -> None: 21 | start = 0 22 | end = len(s) - 1 23 | while(start < end): 24 | temp = s[end] 25 | s[end] = s[start] 26 | s[start] = temp 27 | start += 1 28 | end -= 1 29 | return s -------------------------------------------------------------------------------- /leetcode/problem_380.py: -------------------------------------------------------------------------------- 1 | # Problem 380. Insert Delete GetRandom O(1) (Medium): https://leetcode.com/problems/insert-delete-getrandom-o1/ 2 | 3 | class RandomizedSet: 4 | 5 | def __init__(self): 6 | self.arr = {} 7 | 8 | def insert(self, val: int) -> bool: 9 | if(val not in self.arr): 10 | self.arr[val] = val 11 | return True 12 | else: 13 | return False 14 | 15 | def remove(self, val: int) -> bool: 16 | if(val not in self.arr): 17 | return False 18 | else: 19 | del self.arr[val] 20 | return True 21 | 22 | def getRandom(self) -> int: 23 | high = len(self.arr) - 1 24 | index = random.randint(0, high) 25 | return self.arr[list(self.arr.keys())[index]] 26 | 27 | 28 | # Your RandomizedSet object will be instantiated and called as such: 29 | # obj = RandomizedSet() 30 | # param_1 = obj.insert(val) 31 | # param_2 = obj.remove(val) 32 | # param_3 = obj.getRandom() -------------------------------------------------------------------------------- /leetcode/problem_383.py: -------------------------------------------------------------------------------- 1 | # Problem 383. Ransom Note (https://leetcode.com/problems/ransom-note/) 2 | class Solution: 3 | def canConstruct(self, ransomNote: str, magazine: str) -> bool: 4 | freq1 = {} 5 | freq2 = {} 6 | for letter in ransomNote: 7 | if letter not in freq1: 8 | freq1[letter] = 1 9 | else: 10 | freq1[letter] += 1 11 | 12 | for letter in magazine: 13 | if letter not in freq2: 14 | freq2[letter] = 1 15 | else: 16 | freq2[letter] += 1 17 | for key, value in freq1.items(): 18 | if((key not in freq2) or ((key in freq2) and freq2[key] < value)): 19 | return False 20 | return True 21 | 22 | if __name__ == '__main__': 23 | s = Solution() 24 | print(s.canConstruct("a", "b")) # False 25 | print(s.canConstruct("aa", "ab")) # False 26 | print(s.canConstruct("aa", "aab")) # True 27 | -------------------------------------------------------------------------------- /leetcode/problem_386.py: -------------------------------------------------------------------------------- 1 | ### Problem 386. Lexicographical Numbers (Medium): https://leetcode.com/problems/lexicographical-numbers/ 2 | 3 | class Solution: 4 | def lexicalOrder(self, n: int) -> List[int]: 5 | nums = [] 6 | def dfs(x): 7 | if(x > n): 8 | return 9 | nums.append(x) 10 | x *= 10 11 | for i in range(10): 12 | dfs(x+i) 13 | 14 | for i in range(1,10): 15 | dfs(i) 16 | return nums 17 | 18 | # Optimized 19 | class Solution: 20 | def lexicalOrder(self, n: int) -> List[int]: 21 | nums = [] 22 | stack = [] 23 | x = 1 24 | seen = {} 25 | while len(nums) < n: 26 | nums.append(x) 27 | if(x * 10 <= n): 28 | x *= 10 29 | else: 30 | while(x == n or x % 10 == 9): 31 | x = x // 10 32 | x += 1 33 | return nums -------------------------------------------------------------------------------- /leetcode/problem_387.py: -------------------------------------------------------------------------------- 1 | ### Problem 387. First Unique Character in a String (Easy): https://leetcode.com/problems/first-unique-character-in-a-string/ 2 | ### Tags: Hash Table, String, Queue 3 | class Solution: 4 | def firstUniqChar(self, s: str) -> int: 5 | chars = {} 6 | q = [] 7 | head = None 8 | # [love] 9 | for i in range(len(s)): 10 | if s[i] not in chars: 11 | chars[s[i]] = 1 12 | q.append(i) 13 | else: 14 | chars[s[i]] += 1 15 | for i in range(len(q)): 16 | if(chars[s[q[i]]] == 1): 17 | return q[i] 18 | return -1 -------------------------------------------------------------------------------- /leetcode/problem_39.py: -------------------------------------------------------------------------------- 1 | ### Problem 39. Combination Sum (Medium): https://leetcode.com/problems/combination-sum/ 2 | ### tags: backtracking, recursion 3 | class Solution: 4 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: 5 | result = [] 6 | def dfs(index, total, arr): 7 | if(index >= len(candidates) or total > target): 8 | return 9 | if(total == target): 10 | result.append(arr.copy()) 11 | return 12 | 13 | arr.append(candidates[index]) 14 | dfs(index, total + candidates[index], arr) 15 | arr.pop() 16 | dfs(index + 1, total, arr) 17 | 18 | dfs(0, 0, []) 19 | return result -------------------------------------------------------------------------------- /leetcode/problem_392.py: -------------------------------------------------------------------------------- 1 | # Problem 392: Is Subsequence (https://leetcode.com/problems/is-subsequence/) 2 | class Solution: 3 | def isSubsequence(self, s: str, t: str) -> bool: 4 | i,j = 0, 0 5 | if(len(s) == len(t)): 6 | return s == t 7 | while(i < len(s) and j < len(t)): 8 | if(s[i] == t[j]): 9 | i += 1 10 | j += 1 11 | else: 12 | j += 1 13 | return len(s) == i 14 | 15 | if __name__ == '__main__': 16 | s = Solution() 17 | print(s.isSubsequence("abc","ahbgdc")) # True 18 | print(s.isSubsequence("axc","ahbgdc")) # False 19 | print(s.isSubsequence("abc","abc")) # True 20 | print(s.isSubsequence("abc","ahbgdc")) # True 21 | print(s.isSubsequence("","ahbgdc")) # True 22 | print(s.isSubsequence("","")) # True 23 | print(s.isSubsequence("a","")) # False -------------------------------------------------------------------------------- /leetcode/problem_40.py: -------------------------------------------------------------------------------- 1 | ### Problem 40. Combination Sum II (Medium): https://leetcode.com/problems/combination-sum-ii/ 2 | ### tags: backtracking, recursion 3 | 4 | class Solution: 5 | def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: 6 | candidates.sort() 7 | result = [] 8 | def dfs(total, arr, index): 9 | if(total == target): 10 | result.append(arr.copy()) 11 | return 12 | if(index >= len(candidates) or total > target): 13 | return 14 | arr.append(candidates[index]) 15 | dfs(total + candidates[index], arr, index + 1) 16 | arr.pop() 17 | while(index + 1 < len(candidates) and (candidates[index + 1] == candidates[index])): 18 | index += 1 19 | dfs(total, arr, index + 1) 20 | 21 | 22 | dfs(0, [], 0) 23 | return result -------------------------------------------------------------------------------- /leetcode/problem_404.py: -------------------------------------------------------------------------------- 1 | ### Problem 404. Sum of Left Leaves (Easy): https://leetcode.com/problems/sum-of-left-leaves/ 2 | ### Tags: Tree, Depth First Search, Recursion 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int: 12 | def sum_left(root, sum_n, isLeft): 13 | if(root is None): 14 | return 0 15 | if(root.left is None and root.right is None): 16 | if(isLeft): 17 | sum_n += root.val 18 | return sum_n 19 | else: 20 | return 0 21 | left_sum = sum_left(root.left, sum_n, True) 22 | right_sum = sum_left(root.right, sum_n, False) 23 | return left_sum + right_sum 24 | return sum_left(root, 0, False) -------------------------------------------------------------------------------- /leetcode/problem_409.py: -------------------------------------------------------------------------------- 1 | ### Problem 409. Longest Palindrome (Easy) 2 | 3 | ### Tags: String, Hash Table, Greedy 4 | class Solution: 5 | def longestPalindrome(self, s: str) -> int: 6 | count = 0 7 | freq = {} 8 | taken = {} 9 | for letter in s: 10 | if(letter not in freq): 11 | freq[letter] = 1 12 | else: 13 | freq[letter] += 1 14 | for key, value in freq.items(): 15 | f = value // 2 16 | if(f > 0): 17 | taken[key] = f 18 | freq[key] -= f*2 19 | count += (f*2) 20 | for key, value in freq.items(): 21 | if(value > 0 and key in taken): 22 | count += 1 23 | break 24 | if(count % 2 == 0 and count < len(s)): 25 | return count + 1 26 | return count -------------------------------------------------------------------------------- /leetcode/problem_442.py: -------------------------------------------------------------------------------- 1 | ### Problem 442. Find All Duplicates in an Array 2 | ### tags: Array, Hash Table 3 | 4 | class Solution: 5 | def findDuplicates(self, nums: List[int]) -> List[int]: 6 | lookUp = Counter(nums) 7 | result = [] 8 | for key, freq in lookUp.items(): 9 | if(freq == 2): 10 | result.append(key) 11 | return result -------------------------------------------------------------------------------- /leetcode/problem_443.py: -------------------------------------------------------------------------------- 1 | ### Problem 443. String Compression (Medium) https://leetcode.com/problems/string-compression/ 2 | # tags: string, two-pointers 3 | class Solution: 4 | def compress(self, chars: List[str]) -> int: 5 | prev = chars[0] 6 | count = 0 7 | result = '' 8 | for i, curr in enumerate(chars): 9 | if(prev == curr): 10 | count += 1 11 | else: 12 | result +=prev 13 | if(count > 1): 14 | result += str(count) 15 | prev = curr 16 | count = 1 17 | result +=prev 18 | if(count > 1): 19 | result += str(count) 20 | for i, char in enumerate(result): 21 | if(i >= len(chars)): 22 | chars.append(char) 23 | else: 24 | chars[i] = char 25 | # Pop extra chars 26 | while(len(result) < len(chars)): 27 | chars.pop() 28 | 29 | 30 | -------------------------------------------------------------------------------- /leetcode/problem_448.py: -------------------------------------------------------------------------------- 1 | ### Problem : 448. Find All Numbers Disappeared in an Array 2 | ### tags: Array, Hash Table 3 | class Solution: 4 | def findDisappearedNumbers(self, nums: List[int]) -> List[int]: 5 | lookUp = set() 6 | for num in nums: 7 | lookUp.add(num) 8 | 9 | result = [] 10 | for i in range(1, (len(nums)) + 1): 11 | if(i not in lookUp): 12 | result.append(i) 13 | return result -------------------------------------------------------------------------------- /leetcode/problem_451.py: -------------------------------------------------------------------------------- 1 | # Problem 451. Sort Characters By Frequency (Medium): https://leetcode.com/problems/sort-characters-by-frequency/ 2 | 3 | class Solution: 4 | def frequencySort(self, s: str) -> str: 5 | freq = {} 6 | for i in range(len(s)): 7 | char = s[i] 8 | if(char not in freq): 9 | freq[char] = 1 10 | else: 11 | freq[char] += 1 12 | result = sorted([(v, k) for k, v in freq.items()], reverse=True) 13 | temp = '' 14 | for i in range(len(result)): 15 | tup = result[i] 16 | temp += (tup[1]*tup[0]) 17 | return temp -------------------------------------------------------------------------------- /leetcode/problem_50.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def myPow(self, x: float, n: int) -> float: 3 | if(n == 0): 4 | return 1 5 | if(n < 0): 6 | return 1 / (x * self.myPow(x, -n - 1)) 7 | if( n % 2 == 0): 8 | ans = self.myPow(x, n // 2) 9 | return ans * ans 10 | return x * self.myPow(x, n-1) 11 | 12 | class Solution: 13 | def myPow(self, x: float, n: int) -> float: 14 | result = 1 15 | k = n 16 | if( n == 0): 17 | return result 18 | if( x == 0): 19 | return 0 20 | if(n < 0): 21 | k = abs(n) 22 | x = 1 / x 23 | while(k > 0): 24 | if(k % 2 == 0): 25 | k = k // 2 26 | x = x * x 27 | else: 28 | result *= x 29 | k -= 1 30 | return result -------------------------------------------------------------------------------- /leetcode/problem_506.py: -------------------------------------------------------------------------------- 1 | ### Problem: 506. Relative Ranks (Easy): https://leetcode.com/problems/relative-ranks/ 2 | class Solution: 3 | def findRelativeRanks(self, score: List[int]) -> List[str]: 4 | scores = sorted(score,reverse = True) 5 | result = [] 6 | index = {} 7 | for i in range(len(scores)): 8 | result.append("") 9 | index[scores[i]] = i 10 | for i in range(len(score)): 11 | if(index[score[i]] == 0): 12 | result[i] = "Gold Medal" 13 | elif(index[score[i]] == 1): 14 | result[i] = "Silver Medal" 15 | elif(index[score[i]] == 2): 16 | result[i] = "Bronze Medal" 17 | else: 18 | result[i] = str(index[score[i]] + 1) 19 | return result 20 | -------------------------------------------------------------------------------- /leetcode/problem_509.py: -------------------------------------------------------------------------------- 1 | ### Problem 509. Fibonacci Number (Easy) 2 | ### Tags: Dynamic Programming 3 | 4 | class Solution: 5 | def fib(self, n: int) -> int: 6 | # 0 1 1 2 3 5 7 | x, y = 0, 1 8 | z = 0 9 | if(n == 0): 10 | return n 11 | if(n < 3): 12 | return 1 13 | for i in range(2,n+1): 14 | z = x + y 15 | x = y 16 | y = z 17 | return z -------------------------------------------------------------------------------- /leetcode/problem_513.py: -------------------------------------------------------------------------------- 1 | ### Problem 513. Find Bottom Left Tree Value (Medium): https://leetcode.com/problems/find-bottom-left-tree-value/ 2 | 3 | from collections import deque 4 | class Solution: 5 | def findBottomLeftValue(self, root: Optional[TreeNode]) -> int: 6 | q = deque() 7 | q.append(root) 8 | leftMost = root.val 9 | while(True): 10 | size = len(q) 11 | if(size == 0): 12 | return leftMost 13 | first = True 14 | while(size > 0): 15 | top = q.popleft() 16 | if(first): 17 | leftMost = top.val 18 | first = not first 19 | if(top.left): 20 | q.append(top.left) 21 | if(top.right): 22 | q.append(top.right) 23 | size -=1 24 | return leftMost 25 | -------------------------------------------------------------------------------- /leetcode/problem_535.py: -------------------------------------------------------------------------------- 1 | class Codec: 2 | def __init__(self): 3 | self.urls = {} 4 | self.arr = [] 5 | 6 | def randomString(self): 7 | result = '' 8 | for i in range(7): 9 | result += chr(randint(97, 122)) 10 | return result 11 | 12 | def encode(self, longUrl: str) -> str: 13 | code = self.randomString() 14 | baseUrl = 'http://tinyurl.com/' 15 | self.urls[code] = longUrl 16 | return baseUrl + code 17 | 18 | def decode(self, shortUrl: str) -> str: 19 | code = shortUrl.split('/')[-1] 20 | return self.urls[code] 21 | 22 | # Your Codec object will be instantiated and called as such: 23 | # codec = Codec() 24 | # codec.decode(codec.encode(url)) -------------------------------------------------------------------------------- /leetcode/problem_539.py: -------------------------------------------------------------------------------- 1 | ### Problem 539. Minimum Time Difference 2 | ### tags: array, math, string, sorting 3 | class Solution: 4 | def findMinDifference(self, timePoints: List[str]) -> int: 5 | 6 | def toMinute(p1): 7 | time1 = p1.split(":") 8 | hr = int(time1[0]) 9 | min = int(time1[1]) 10 | return hr * 60 + min 11 | 12 | for i in range(len(timePoints)): 13 | timePoints[i] = "{}".format(toMinute(timePoints[i])) 14 | timePoints.sort(key = lambda x: int(x)) 15 | 16 | min_diff = 24*60 - int(timePoints[-1]) + int(timePoints[0]) 17 | 18 | for i in range(1,len(timePoints)): 19 | prev = int(timePoints[i-1]) 20 | curr = int(timePoints[i]) 21 | min_diff = min(abs(curr - prev), min_diff) 22 | return min_diff 23 | 24 | -------------------------------------------------------------------------------- /leetcode/problem_547.py: -------------------------------------------------------------------------------- 1 | ### Problem 547. Number of Provinces (Medium): https://leetcode.com/problems/number-of-provinces/ 2 | ### tags: Graph, Connected Components, Depth First Search, Breadth First Search 3 | 4 | class Solution: 5 | def findCircleNum(self, isConnected: List[List[int]]) -> int: 6 | adj = {} 7 | n = len(isConnected) 8 | visited = set() 9 | count = 0 10 | for conn in range(n): 11 | if(conn in visited): 12 | continue 13 | count += 1 14 | q = deque() 15 | q.append(conn) 16 | visited.add(conn) 17 | while(len(q) != 0): 18 | top = q.popleft() 19 | neighbors = isConnected[top] 20 | for i in range(n): 21 | if(neighbors[i] == 1 and i not in visited): 22 | q.append(i) 23 | visited.add(i) 24 | # print("visited from i=", conn ," =", visited) 25 | return count 26 | 27 | -------------------------------------------------------------------------------- /leetcode/problem_55.py: -------------------------------------------------------------------------------- 1 | # Problem 55. Jump Game (Medium): https://leetcode.com/problems/jump-game/ 2 | 3 | # hint: uses greedy approach by trying to reach a index lower every time 4 | # if we reach at the beginning, then we can jump until the end of the array 5 | # Time: O(n), Space: O(1) 6 | 7 | class Solution: 8 | def canJump(self, nums: List[int]) -> bool: 9 | lastIndex = len(nums) - 1; 10 | current = lastIndex - 1 11 | while(current >= 0): 12 | if(nums[current] + current >= lastIndex): 13 | lastIndex = current 14 | current -= 1 15 | if(lastIndex == 0): 16 | return True 17 | else: 18 | return False 19 | 20 | # Alternate solution: Take the jump that is greater than current jump 21 | 22 | if __name__ == "__main__": 23 | nums = [2,3,1,1,4] 24 | print(Solution().canJump(nums)) # True 25 | nums = [3,2,1,0,4] 26 | print(Solution().canJump(nums)) # False 27 | nums = [2,0,0] 28 | print(Solution().canJump(nums)) # True 29 | nums = [0] 30 | print(Solution().canJump(nums)) # True -------------------------------------------------------------------------------- /leetcode/problem_567.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def checkInclusion(self, s1: str, s2: str) -> bool: 3 | freqS1 = {} 4 | freqS2 = {} 5 | for i in range(len(s1)): 6 | if(s1[i] in freqS1): 7 | freqS1[s1[i]] += 1 8 | else: 9 | freqS1[s1[i]] = 1 10 | for i in range(len(s2)): 11 | if(s2[i] in freqS2): 12 | freqS2[s2[i]] += 1 13 | else: 14 | freqS2[s2[i]] = 1 15 | if(i >= len(s1)): 16 | overflowedIndex = i - len(s1) 17 | if(freqS2[s2[overflowedIndex]] == 1): 18 | del freqS2[s2[overflowedIndex]] 19 | else: 20 | freqS2[s2[overflowedIndex]] -= 1 21 | print(freqS1, freqS2) 22 | if(freqS1 == freqS2): 23 | return True 24 | return False 25 | 26 | 27 | if __name__ == "__main__": 28 | print(Solution().checkInclusion("ab", "eidbaooo")) -------------------------------------------------------------------------------- /leetcode/problem_590.py: -------------------------------------------------------------------------------- 1 | ### Problem 590. N-ary Tree Postorder Traversal (Easy): https://leetcode.com/problems/n-ary-tree-postorder-traversal/ 2 | ### tags: tree, easy 3 | class Solution: 4 | def postorder(self, root: 'Node') -> List[int]: 5 | stack = [] 6 | result = [] 7 | if(root is None): 8 | return result 9 | stack.append(root) 10 | while(stack): 11 | root = stack.pop() 12 | result.append(root.val) 13 | for child in root.children: 14 | stack.append(child) 15 | return result[::-1] 16 | -------------------------------------------------------------------------------- /leetcode/problem_6.py: -------------------------------------------------------------------------------- 1 | 2 | # Problem 6: ZigZag Conversion (Medium): https://leetcode.com/problems/zigzag-conversion/ 3 | 4 | class Solution: 5 | def convert(self, s: str, numRows: int) -> str: 6 | result = {} 7 | factor = 1 8 | key = 0 9 | for i in range(len(s)): 10 | if(key not in result): 11 | result[key]='' 12 | result[key] += s[i] 13 | key = key + factor 14 | if(key>=(numRows-1) or key<= 0): 15 | factor = factor * -1 16 | result = ''.join(result.values()) 17 | 18 | 19 | if __name__ == '__main__': 20 | s = Solution() 21 | s.convert("PAYPALISHIRING", 3) 22 | -------------------------------------------------------------------------------- /leetcode/problem_624.py: -------------------------------------------------------------------------------- 1 | ### Problem 624. Maximum Distance in Arrays (Easy): https://leetcode.com/problems/maximum-distance-in-arrays/ 2 | 3 | ### tags: array 4 | 5 | class Solution: 6 | def maxDistance(self, arrays: List[List[int]]) -> int: 7 | max_num = arrays[0][-1] 8 | min_num = arrays[0][0] 9 | result = 0 10 | for i in range(1, len(arrays)): 11 | arr = arrays[i] 12 | result = max(result, max(arr[-1] - min_num, max_num - arr[0])) 13 | if(arr[-1] > max_num): 14 | max_num = arr[-1] 15 | if(arr[0] < min_num): 16 | min_num = arr[0] 17 | return result -------------------------------------------------------------------------------- /leetcode/problem_633.py: -------------------------------------------------------------------------------- 1 | ### Problem. 633 Sum of Square Numbers (Easy): https://leetcode.com/problems/sum-of-square-numbers/ 2 | 3 | ### Tags: Math, Two Pointers 4 | ### Similar to Problem 167. Two Sum II - Input array is sorted (Easy): https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/ 5 | class Solution: 6 | def judgeSquareSum(self, c: int) -> bool: 7 | hs = {} 8 | for i in range(int(sqrt(c))+1): 9 | hs[i*i] = i 10 | target = c - i*i 11 | if(target in hs): 12 | return True 13 | return False 14 | 15 | ### Two pointer approach 16 | 17 | class Solution: 18 | def judgeSquareSum(self, c: int) -> bool: 19 | a = 0 20 | b = int(sqrt(c)) 21 | while(a <= b): 22 | if(a*a + b*b < c): 23 | a+=1 24 | elif(a*a + b*b > c): 25 | b-=1 26 | else: 27 | return True 28 | return False -------------------------------------------------------------------------------- /leetcode/problem_659.py: -------------------------------------------------------------------------------- 1 | ### Problem 659. Encode and Decode Strings (Medium): https://leetcode.com/problems/encode-and-decode-strings/ (Premium) 2 | 3 | ### tags: string, encoding, decoding 4 | 5 | class Solution: 6 | def encode(self, strs: List[str]) -> str: 7 | if(len(strs)==0): 8 | return "" 9 | encoded = "" 10 | for s in strs: 11 | l = len(s) 12 | delimeter = '#' 13 | encoded += (str(l) + delimeter + s) 14 | return encoded 15 | 16 | def decode(self, s: str) -> List[str]: 17 | start = 0 18 | end = 0 19 | result = [] 20 | while(end != len(s)): 21 | start = end 22 | while(s[end] != '#'): 23 | end += 1 24 | num = int(s[start:end]) 25 | start = end + 1 26 | end += (num + 1) 27 | st = s[start: end] 28 | result.append(st) 29 | return result 30 | -------------------------------------------------------------------------------- /leetcode/problem_66.py: -------------------------------------------------------------------------------- 1 | ### Problem 66. Plus One (Easy): https://leetcode.com/problems/plus-one/ 2 | class Solution: 3 | def plusOne(self, digits: List[int]) -> List[int]: 4 | num = 0 5 | for n in digits: 6 | num = num * 10 + n 7 | num = num + 1 8 | res = [int(x) for x in str(num)] 9 | return res -------------------------------------------------------------------------------- /leetcode/problem_67.py: -------------------------------------------------------------------------------- 1 | ### Problem 67. Add Binary (Easy): https://leetcode.com/problems/add-binary/ 2 | 3 | class Solution: 4 | def addBinary(self, a: str, b: str) -> str: 5 | i = len(a) - 1 6 | j = len(b) - 1 7 | carry = 0 8 | result = '' 9 | while(i >= 0 or j >= 0 or carry): 10 | if(i >= 0): 11 | carry += int(a[i]) 12 | i -= 1 13 | if(j >= 0): 14 | carry += int(b[j]) 15 | j -= 1 16 | # carry can be either 0 or 1 17 | result = str(carry % 2 ) + result 18 | carry //=2 19 | return result -------------------------------------------------------------------------------- /leetcode/problem_69.py: -------------------------------------------------------------------------------- 1 | ### Problem 69. Sqrt(x) (https://leetcode.com/problems/sqrtx/) 2 | 3 | class Solution: 4 | def mySqrt(self, x: int) -> int: 5 | if( x == 0 or x == 1): 6 | return x 7 | start = 1 8 | end = x 9 | while(start <= end): 10 | mid = start + ((end - start) // 2) 11 | square = mid * mid 12 | if(square == x): 13 | return mid 14 | elif(square > x): 15 | end = mid - 1 16 | else: 17 | start = mid+1 18 | return round(end) -------------------------------------------------------------------------------- /leetcode/problem_700.py: -------------------------------------------------------------------------------- 1 | ### Problem 700. Search in a Binary Search Tree (Easy) 2 | 3 | ### Tags: Binary Search Tree 4 | 5 | 6 | # Definition for a binary tree node. 7 | # class TreeNode: 8 | # def __init__(self, val=0, left=None, right=None): 9 | # self.val = val 10 | # self.left = left 11 | # self.right = right 12 | class Solution: 13 | def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]: 14 | while(root): 15 | if(root.val > val): 16 | root = root.left 17 | elif(root.val < val): 18 | root = root.right 19 | else: 20 | return root 21 | return root -------------------------------------------------------------------------------- /leetcode/problem_703.py: -------------------------------------------------------------------------------- 1 | class KthLargest: 2 | def __init__(self, k: int, nums: List[int]): 3 | self.harr = nums 4 | self.k = k 5 | # creates min heap 6 | heapq.heapify(self.harr) 7 | while(len(self.harr) > k): 8 | heapq.heappop(self.harr) 9 | 10 | def add(self, val: int) -> int: 11 | heapq.heappush(self.harr, val) 12 | if(self.k < len(self.harr)): 13 | heapq.heappop(self.harr) 14 | return self.harr[0] -------------------------------------------------------------------------------- /leetcode/problem_729.py: -------------------------------------------------------------------------------- 1 | ### Problem 729. My Calendar I (Medium): https://leetcode.com/problems/my-calendar-i/ 2 | ### tags: 3 | class MyCalendar: 4 | 5 | def __init__(self): 6 | self.events = [] 7 | 8 | def book(self, start: int, end: int) -> bool: 9 | for s, e in self.events: 10 | if not (end <= s or start >= e): 11 | return False 12 | self.events.append((start, end)) 13 | return True -------------------------------------------------------------------------------- /leetcode/problem_731.py: -------------------------------------------------------------------------------- 1 | ### Problem 731. My Calendar II (Medium): https://leetcode.com/problems/my-calendar-ii/ 2 | ### tags: array, binary-search, segment-tree, ordered-set 3 | class MyCalendarTwo: 4 | 5 | def __init__(self): 6 | self.events = [] 7 | self.overlapping = [] 8 | 9 | def book(self, start: int, end: int) -> bool: 10 | for os, oe in self.overlapping: 11 | if(not (start >= oe or os >= end)): 12 | return False 13 | for s, e in self.events: 14 | if(not (start >= e or end <= s)): 15 | ostart = max(start, s) 16 | oend = min(end, e) 17 | self.overlapping.append((ostart, oend)) 18 | self.events.append((start,end)) 19 | return True 20 | # Your MyCalendarTwo object will be instantiated and called as such: 21 | # obj = MyCalendarTwo() 22 | # param_1 = obj.book(start,end) -------------------------------------------------------------------------------- /leetcode/problem_733.py: -------------------------------------------------------------------------------- 1 | ### Problem 733. Flood Fill (Easy): https://leetcode.com/problems/flood-fill/ 2 | ### tags: Array, DFS, BFS, Matrix 3 | class Solution: 4 | def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]: 5 | target = image[sr][sc] 6 | rows = len(image) 7 | cols = len(image[0]) 8 | if target == color: 9 | return image 10 | 11 | def fill(r, c): 12 | image[r][c] = color 13 | if(r - 1 >= 0 and image[r - 1][c] == target): 14 | fill(r - 1, c) 15 | if(r + 1 < rows and image[r + 1][c] == target): 16 | fill(r + 1, c) 17 | if(c - 1 >= 0 and image[r][c - 1] == target): 18 | fill(r, c - 1) 19 | if(c + 1 < cols and image[r][c + 1] == target): 20 | fill(r, c + 1) 21 | 22 | fill(sr, sc) 23 | return image -------------------------------------------------------------------------------- /leetcode/problem_76.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | def minWindow(self, s: str, t: str) -> str: 3 | start = 0 4 | end = len(t)-1; 5 | freq = self.countFreq(t) 6 | subStr = '' 7 | while(end != len(s)): 8 | subStr = s[start:end+1] 9 | if(self.containsSubstring(subStr,freq)): 10 | return subStr 11 | else: 12 | start += 1 13 | end += 1 14 | return subStr 15 | 16 | def countFreq(self, s): 17 | freq = {} 18 | for key in s: 19 | if(key not in freq): 20 | freq[key] = 1 21 | else: 22 | freq[key] = freq[key]+1 23 | return freq 24 | 25 | def containsSubstring(self, s, t): 26 | for key, value in t.items(): 27 | if(s.count(key) != t[key]): 28 | return False 29 | return True 30 | 31 | if __name__ == "__main__": 32 | s = Solution() 33 | print(s.minWindow("ADOBECODEBANC", "ABC")) # BANC 34 | 35 | 36 | -------------------------------------------------------------------------------- /leetcode/problem_771.py: -------------------------------------------------------------------------------- 1 | # Problem 771. Jewels and Stones (Easy): https://leetcode.com/problems/jewels-and-stones/ 2 | class Solution: 3 | def numJewelsInStones(self, jewels: str, stones: str) -> int: 4 | jew_map = {} 5 | for j in jewels: 6 | if j not in jew_map: 7 | jew_map[j] = 1 8 | else: 9 | jew_map[j] += 1 10 | count = 0 11 | for stone in stones: 12 | if stone in jew_map: 13 | count +=1 14 | return count 15 | 16 | # Time complexity: O(n) 17 | # Space complexity: O(n) 18 | 19 | if __name__ == '__main__': 20 | s = Solution() 21 | print(s.numJewelsInStones("aA","aAAbbbb")) # 3 22 | print(s.numJewelsInStones("z","ZZ")) # 0 23 | print(s.numJewelsInStones("a","A")) # 0 24 | print(s.numJewelsInStones("a","a")) # 1 25 | print(s.numJewelsInStones("a","")) # 0 26 | -------------------------------------------------------------------------------- /leetcode/problem_78.py: -------------------------------------------------------------------------------- 1 | # hint: https://www.youtube.com/watch?v=h4zNvA4lbtc 2 | 3 | class Solution: 4 | def subsets(self, nums: List[int]) -> List[List[int]]: 5 | result = [] 6 | # power set of an array consists of 2^n 7 | # so we can consider set bits in binary 8 | size = len(nums) 9 | for i in range(1 << size): 10 | subset = [] 11 | for j in range(size): 12 | # check if bit is set by AND with i 13 | if((1 << j) & i): 14 | subset.append(nums[j]) 15 | result.append(subset) 16 | return result -------------------------------------------------------------------------------- /leetcode/problem_796.py: -------------------------------------------------------------------------------- 1 | ### Problem 796: Rotate String (Easy): https://leetcode.com/problems/rotate-string/ 2 | 3 | class Solution: 4 | def rotateString(self, s: str, goal: str) -> bool: 5 | return len(s) == len(goal) and s in goal+goal 6 | 7 | class Solution2: 8 | def rotateString(self, s: str, goal: str) -> bool: 9 | if(len(s) != len(goal)): 10 | return False 11 | 12 | anas = [] 13 | start = s 14 | rotated = '' 15 | while(rotated != s): 16 | rotated = start[1::] + start[0] 17 | anas.append(rotated) 18 | start = rotated 19 | 20 | for a in anas: 21 | if(a == goal): 22 | return True 23 | return False 24 | 25 | class Solution: 26 | def rotateString(self, s: str, goal: str) -> bool: 27 | i = 0 28 | while(i < len(s)): 29 | s = s[1:] + s[0] 30 | if(s==goal): 31 | break 32 | i+=1 33 | return s==goal -------------------------------------------------------------------------------- /leetcode/problem_826.py: -------------------------------------------------------------------------------- 1 | ### Problem 826. Most Profit Assigning Work (Medium) 2 | ### Tags: Two Pointers, Sorting 3 | 4 | class Solution: 5 | def maxProfitAssignment(self, difficulty: List[int], profit: List[int], worker: List[int]) -> int: 6 | 7 | # d [68,35,52,47,86] => [35, 47, 52, 68, 86] 8 | # p [67,17,1,81,3] => [17, 81, 1, 67, 3] 9 | # w[92,10,85,84,82] => [10, 82, 84, 85, 92] 10 | 11 | # 81 + 0 + 81 + 81 + 81 = 324 12 | 13 | p = [x for _, x in sorted(zip(difficulty, profit))] 14 | difficulty.sort() 15 | worker.sort() 16 | total = 0 17 | i = 0 18 | m = 0 19 | for w in worker: 20 | while(i < len(difficulty) and w >= difficulty[i]): 21 | pr = p[i] 22 | m = max(m, pr) 23 | i += 1 24 | total += m 25 | return total 26 | 27 | -------------------------------------------------------------------------------- /leetcode/problem_860.py: -------------------------------------------------------------------------------- 1 | ### Problem 860. Lemonade Change (Easy): https://leetcode.com/problems/lemonade-change/ 2 | ### tags: array, greedy 3 | class Solution: 4 | def lemonadeChange(self, bills: List[int]) -> bool: 5 | fives = 0 6 | tens = 0 7 | twenties = 0 8 | for bill in bills: 9 | if(bill == 5): 10 | fives += 1 11 | elif(bill == 10): 12 | tens += 1 13 | if(fives > 0): 14 | fives -= 1 15 | else: 16 | return False 17 | elif(bill == 20): 18 | twenties += 1 19 | if(tens > 0 and fives > 0): 20 | tens -= 1 21 | fives -= 1 22 | elif(fives > 2): 23 | fives -= 3 24 | else: 25 | return False 26 | return True -------------------------------------------------------------------------------- /leetcode/problem_875.py: -------------------------------------------------------------------------------- 1 | ### Problem 875. Koko Eating Bananas (Medium): https://leetcode.com/problems/koko-eating-bananas/ 2 | ### tags: binary search, math 3 | 4 | ### hint: try all possible eating speeds and find the minimum speed that can be used to eat all the bananas within h hours 5 | class Solution: 6 | def minEatingSpeed(self, piles: List[int], h: int) -> int: 7 | 8 | def eating_time(speed): 9 | hrs = 0 10 | for pile in piles: 11 | hrs += math.ceil(pile/speed) 12 | return hrs 13 | 14 | start = 1 15 | end = max(piles) 16 | speed = end 17 | while(start <= end): 18 | mid = start + (end - start) // 2 19 | time = eating_time(mid) 20 | if(time <= h): 21 | speed = min(speed, mid) 22 | end = mid - 1 23 | else: 24 | start = mid + 1 25 | return speed -------------------------------------------------------------------------------- /leetcode/problem_877.py: -------------------------------------------------------------------------------- 1 | ### Problem 877. Stone Game (Medium): https://leetcode.com/problems/stone-game/ 2 | ### tags: dynamic programming 3 | class Solution: 4 | def stoneGame(self, piles: List[int]) -> bool: 5 | cache = {} 6 | def dfs(start, end): 7 | if(start > end): 8 | return 0 9 | if((start, end) in cache): 10 | return cache[(start, end)] 11 | bobs_turn = True if (end - start) % 2 != 0 else False 12 | left, right = 0, 0 13 | if(not bobs_turn): 14 | left = piles[start] 15 | right = piles[end] 16 | # alice can choose either of the choice 17 | res1 = dfs(start + 1, end) + left 18 | res2 = dfs(start, end - 1) + right 19 | 20 | cache[(start, end)] = max(res1, res2) 21 | return cache[(start, end)] 22 | return dfs(0, len(piles) - 1) -------------------------------------------------------------------------------- /leetcode/problem_884.py: -------------------------------------------------------------------------------- 1 | ### Problem 884.Uncommon Words from Two Sentences 2 | ### tags: hashtable, string, counter 3 | class Solution: 4 | def uncommonFromSentences(self, s1: str, s2: str) -> List[str]: 5 | result1 = Counter(s1.split()) 6 | result2 = Counter(s2.split()) 7 | print(result1, result2) 8 | result = set() 9 | for word, val in result1.items(): 10 | if(word not in result2 and val == 1): 11 | result.add(word) 12 | for word,val in result2.items(): 13 | if(word not in result1 and val == 1): 14 | result.add(word) 15 | return result -------------------------------------------------------------------------------- /leetcode/problem_885.py: -------------------------------------------------------------------------------- 1 | ### Problem 885. Spiral Matrix III 2 | ### Tags: Array, Matrix, Simulation 3 | class Solution: 4 | def spiralMatrixIII(self, rows: int, cols: int, rStart: int, cStart: int) -> List[List[int]]: 5 | result = [] 6 | # E = 0, S = 1, W = 2, N = 3 7 | directions = [[0,1],[1,0],[0,-1],[-1,0]] 8 | direction = 0 9 | units = 1 10 | while(len(result) < rows * cols): 11 | for x in range(2): 12 | for step in range(units): 13 | if(rStart>=0 and rStart=0 and cStart < cols): 14 | result.append([rStart, cStart]) 15 | rStart += directions[direction][0] 16 | cStart += directions[direction][1] 17 | direction = (direction + 1) % 4 18 | units += 1 19 | return result 20 | -------------------------------------------------------------------------------- /leetcode/problem_9.py: -------------------------------------------------------------------------------- 1 | # Problem 9: Palindrome Number (Easy): https://leetcode.com/problems/palindrome-number/ 2 | class Solution: 3 | def isPalindrome(self, x: int) -> bool: 4 | result = 0 5 | isNegative = x < 0 6 | if(isNegative): 7 | return False 8 | temp = abs(x) 9 | while(temp != 0): 10 | right = temp % 10 11 | result = result*10 + right 12 | temp = temp//10 13 | return result == x 14 | 15 | if __name__ == "__main__": 16 | print(Solution().isPalindrome(121)) # True 17 | print(Solution().isPalindrome(-121)) # False 18 | print(Solution().isPalindrome(10)) # False 19 | print(Solution().isPalindrome(-101)) # False 20 | print(Solution().isPalindrome(0)) # True 21 | print(Solution().isPalindrome(11)) # True 22 | print(Solution().isPalindrome(1001)) # True -------------------------------------------------------------------------------- /leetcode/problem_901.py: -------------------------------------------------------------------------------- 1 | ### Problem 901. Online Stock Span (Medium): https://leetcode.com/problems/online-stock-span/ 2 | ### tags: stack 3 | class StockSpanner: 4 | 5 | def __init__(self): 6 | self.stocks = [] 7 | 8 | def next(self, price: int) -> int: 9 | span = 1 10 | # [(100, 1), (80, 1), (70, 2), (60, 1), (75, 4), (85, ) 11 | # [1, , 1 , 2 , 1, , 4 ] 12 | while(self.stocks and self.stocks[-1][0] <= price): 13 | span += self.stocks[-1][1] 14 | self.stocks.pop() 15 | self.stocks.append((price, span)) 16 | return span 17 | 18 | 19 | # Your StockSpanner object will be instantiated and called as such: 20 | # obj = StockSpanner() 21 | # param_1 = obj.next(price) -------------------------------------------------------------------------------- /leetcode/problem_933.py: -------------------------------------------------------------------------------- 1 | ### Problem 933. Number of Recent Calls (Easy): https://leetcode.com/problems/number-of-recent-calls/ 2 | 3 | ### Tags: Queue 4 | from queue import Queue 5 | class RecentCounter: 6 | def __init__(self): 7 | self.q = Queue() 8 | 9 | def ping(self, t: int) -> int: 10 | self.q.put(t) 11 | top = self.q.queue[0] 12 | if(top < t - 3000): 13 | while(top < t - 3000): 14 | self.q.get() 15 | top = self.q.queue[0] 16 | return self.q.qsize() 17 | 18 | # Solution 2 19 | # Faster using Double ended queue 20 | from collections import deque 21 | class RecentCounter: 22 | def __init__(self): 23 | self.q = deque() 24 | 25 | def ping(self, t: int) -> int: 26 | self.q.append(t) 27 | top = self.q[0] 28 | if(top < t - 3000): 29 | while(top < t - 3000): 30 | self.q.popleft() 31 | top = self.q[0] 32 | return len(self.q) 33 | 34 | -------------------------------------------------------------------------------- /leetcode/problem_938.py: -------------------------------------------------------------------------------- 1 | ### Problem 938. Range Sum of BST (Easy) 2 | class Solution: 3 | def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: 4 | result = 0 5 | stack = [] 6 | start = root 7 | while(True): 8 | while(start): 9 | stack.append(start) 10 | start = start.left 11 | if(not stack): 12 | break 13 | start = stack.pop() 14 | if(start.val >= low and start.val <= high): 15 | result +=start.val 16 | start = start.right 17 | return result 18 | 19 | ### Recursive Solution 20 | class Solution: 21 | def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int: 22 | def rangeSum(r): 23 | if(r is None): 24 | return 0 25 | val = 0 26 | if(r.val >= low and r.val <= high): 27 | val = r.val 28 | return rangeSum(r.left) + val + rangeSum(r.right) 29 | return rangeSum(root) 30 | -------------------------------------------------------------------------------- /leetcode/problem_945.py: -------------------------------------------------------------------------------- 1 | ### Problem 945. Minimum Increment to Make Array Unique (Medium): https://leetcode.com/problems/minimum-increment-to-make-array-unique/description/ 2 | ### Tags: Array, Hash Table, Sort 3 | 4 | ### Time Complexity: O(nlogn) 5 | class Solution: 6 | def minIncrementForUnique(self, nums: List[int]) -> int: 7 | uniq = {} 8 | nums.sort() 9 | moves=0 10 | i = 0 11 | j = i+1 12 | while(j < len(nums)): 13 | if(nums[i] == nums[j]): 14 | nums[j] += 1 15 | moves += 1 16 | elif(nums[i] > nums[j]): 17 | diff = nums[i] - nums[j] 18 | nums[j] = nums[j] + diff + 1 19 | moves += (diff + 1) 20 | i = j 21 | j+= 1 22 | return moves -------------------------------------------------------------------------------- /leetcode/problem_974.py: -------------------------------------------------------------------------------- 1 | ### Problem 974. Subarray Sums Divisible by K (Medium): https://leetcode.com/problems/subarray-sums-divisible-by-k/ 2 | 3 | ### Tags: Array, Hash Table, Math 4 | class Solution: 5 | def subarraysDivByK(self, nums: List[int], k: int) -> int: 6 | pref_sum = {} 7 | rem = {0: 1} 8 | s = 0 9 | count = 0 10 | for i in range(len(nums)): 11 | num = nums[i] 12 | s += num 13 | r = s % k 14 | if(r in rem): 15 | count += rem[r] 16 | rem[r] += 1 17 | else: 18 | rem[r] = 1 19 | 20 | return count -------------------------------------------------------------------------------- /linked_list/reverse_linked_list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * function ListNode(val, next) { 4 | * this.val = (val===undefined ? 0 : val) 5 | * this.next = (next===undefined ? null : next) 6 | * } 7 | */ 8 | /** 9 | * @param {ListNode} head 10 | * @return {ListNode} 11 | */ 12 | var reverseList = function (head) { 13 | let p = null; 14 | let c = head; 15 | 16 | while (c != null) { 17 | let temp = c.next; 18 | c.next = p; 19 | p = c; 20 | c = temp; 21 | } 22 | 23 | return p; 24 | }; -------------------------------------------------------------------------------- /number_theory/GCD_HCF/gcd.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc!=3) 6 | return 0; 7 | int a,b,S; 8 | a = atoi(argv[1]); 9 | b = atoi(argv[2]); 10 | 11 | for(S=a=1;S--) 12 | if(a%S==0&&b%S==0) 13 | break; 14 | 15 | printf("HCF/GCD OF GIVEN TWO NO IS %d\n",S); 16 | 17 | return 0; 18 | } -------------------------------------------------------------------------------- /number_theory/GCD_HCF/gcd3.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc!=4) 6 | return 0; 7 | 8 | int a,b,c,S; 9 | a = atoi(argv[1]); 10 | b = atoi(argv[2]); 11 | c = atoi(argv[3]); 12 | 13 | S=a=1;S--) 17 | if(a%S==0&&b%S==0&&c%S==0) 18 | break; 19 | printf("HCF/GCF OF 3 No. is %d\n",S); 20 | 21 | return 0; 22 | } -------------------------------------------------------------------------------- /number_theory/GCD_HCF/gcdn.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define MAX 100000 3 | int main(int argc,char *argv[]){ 4 | if(argc==1) 5 | return 0; 6 | int S =MAX; 7 | 8 | for(int i=1;i=1;S--){ 16 | for(int i=1;i 2 | 3 | int main(){ 4 | int a,b,H; 5 | 6 | printf("Enter the Numbers\n"); 7 | scanf("%d%d",&a,&b); 8 | 9 | for(H= a=1;H--) 10 | if(a%H==0 && b%H==0) 11 | break; 12 | 13 | printf("\nHCF of Two Numbers=%d\n",H); 14 | 15 | 16 | } 17 | 18 | -------------------------------------------------------------------------------- /number_theory/LCM_HCF/lcm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | 5 | int a,b,L,i,MAX; 6 | 7 | printf("Enter the Two Numbers\n"); 8 | scanf("%d%d",&a,&b); 9 | 10 | for(L=a>b?a:b;L<=a*b;L=L+(a>b?a:b)){ 11 | printf("%d\n",L); 12 | if(L%a==0&&L%b==0) 13 | break; 14 | } 15 | 16 | printf("LCM of Given No = %d\n",L); 17 | 18 | 19 | return 0; 20 | } -------------------------------------------------------------------------------- /number_theory/armstrong.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc!= 2){ 6 | printf("Error\n"); 7 | return 0; 8 | } 9 | 10 | 11 | int n = atoi(argv[1]); 12 | printf("Given No is %d\n",n); 13 | int len=0; 14 | int no =n; 15 | int out=0; 16 | while(no!=0){ 17 | no=no/10; 18 | len++; 19 | } 20 | printf("Length = %d\n",len); 21 | 22 | no = n; 23 | while(no!=0){ 24 | int rem = n%10; 25 | int val = 1; 26 | for(int i=0;i 2 | #include 3 | 4 | int main(int argc,char *argv[]){ 5 | if(argc!=2) 6 | return 0; 7 | int n,in = atoi(argv[1]); 8 | n=in; 9 | int dec=0,oct=0,i=0; 10 | 11 | while(n!=0){ 12 | int r = n%10; 13 | dec=dec+r*pow(2,i); 14 | i++; 15 | n/=10; 16 | } 17 | printf("Decimal = %d",dec); 18 | i=0; 19 | while(dec!=0){ 20 | int r = dec%8; 21 | printf("\nReminder = %d",r); 22 | oct = oct+r*pow(10,i); 23 | printf("\nOCT = %d",oct); 24 | dec/=8; 25 | i++; 26 | } 27 | 28 | printf("\nOctal Number = %d\n",oct); 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /number_theory/conversions/oct_bin.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc,char *argv[]){ 5 | if(argc==1) 6 | return 0; 7 | int in = atoi(argv[1]); 8 | int n,i=0; 9 | n=in; 10 | int dec=0,bin = 0; 11 | while(n!=0){ 12 | int r = n%10; 13 | dec= r*pow(8,i)+dec; 14 | n/=10; 15 | i++; 16 | } 17 | printf("Decimal = %d\n",dec); 18 | 19 | i=0; 20 | while(dec!=0){ 21 | int r = dec%2; 22 | bin = bin +r*pow(10,i); 23 | dec/=2; 24 | i++; 25 | } 26 | printf("Binary = %d\n",bin); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /number_theory/palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc==1){ 6 | printf("Error\n"); 7 | return 0; 8 | } 9 | 10 | int in = atoi(argv[1]); 11 | int n = in,rev=0; 12 | while(n!=0){ 13 | int rem = n%10; 14 | rev = rev*10+rem; 15 | n/=10; 16 | } 17 | if(in==rev){ 18 | printf("Given No is Palindrome\n"); 19 | }else{ 20 | printf("Given No is Not Palindrome\n"); 21 | } 22 | 23 | return 0; 24 | } -------------------------------------------------------------------------------- /number_theory/perfect.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | 5 | if(argc ==1){ 6 | printf("Error\n"); 7 | return 0; 8 | } 9 | 10 | int in = atoi(argv[1]); 11 | int n=in,i=1,j=0,fact[100]; 12 | int sum = 0; 13 | while(i 2 | 3 | int main(){ 4 | 5 | int x,p,out=1; 6 | printf("Enter the No and its power\n"); 7 | scanf("%d %d",&x,&p); 8 | 9 | for (int i = 1; i <=p; ++i) 10 | { 11 | out = x*out; 12 | } 13 | 14 | printf("%d^%d=%d\n",x,p,out); 15 | return 0; 16 | } -------------------------------------------------------------------------------- /number_theory/series/factorial.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int fact(int n){ 4 | 5 | if(n==0){ 6 | return 1; 7 | }else{ 8 | return n*fact(n-1); 9 | } 10 | } 11 | 12 | int main(int argc,char *argv[]){ 13 | if(argc==1) 14 | return 0; 15 | 16 | int n = atoi(argv[1]); 17 | 18 | printf("Factorial of %d is %d\n",n,fact(n)); 19 | 20 | return 0; 21 | } -------------------------------------------------------------------------------- /number_theory/series/fibo.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | if(argc==1) 5 | return 0; 6 | int t1=1,t2=1,sum = 0; 7 | int in = atoi(argv[1]); 8 | int tnext=1; 9 | 10 | for(int i=1;i<=in;i++){ 11 | t1= t2; 12 | t2= tnext; 13 | tnext = t1+t2; 14 | printf("%d ",t1); 15 | } 16 | printf("\nNth term=%d\n",t1); 17 | 18 | return 0; 19 | } -------------------------------------------------------------------------------- /number_theory/series/series.c: -------------------------------------------------------------------------------- 1 | /* 2 | given input n it prints first n elements of this series 3 | 2,6,6,12,12,12,20,20,20,20,30,30,30,30,30.... 4 | */ 5 | 6 | #include 7 | 8 | int main() 9 | { 10 | int n,diff=2,val=0,count=0; 11 | printf("enter n:"); 12 | scanf("%d",&n); 13 | for(int i=0;i 2 | 3 | enum bool{false,true}; 4 | 5 | enum bool isprime(int m){ 6 | int count=0; 7 | if(m==1 || m==0) 8 | return false; 9 | for(int i=2;i<=m;i++){ 10 | if(m%i==0){ 11 | count++; 12 | } 13 | } 14 | if(count<=1) 15 | return true; 16 | else 17 | return false; 18 | } 19 | 20 | int main(int argc,char *argv[]){ 21 | int m = atoi(argv[1]); 22 | int n = atoi(argv[2]); 23 | int sum=0; 24 | for(int i=m;i<=n;i++){ 25 | int result = isprime(i); 26 | if(result==true) // no is prime 27 | sum= sum+i; 28 | } 29 | printf("sum=%d",sum); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /number_theory/sqrt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main(int argc,char *argv[]){ 6 | 7 | if(argc==1){ 8 | printf("Error\n"); 9 | return 0; 10 | } 11 | 12 | int n; 13 | n= atoi(argv[1]); 14 | float i=0.00; 15 | while(i*i<=n){ 16 | printf("\ni= %f",i); 17 | i+=0.001; 18 | } 19 | i-=0.001; 20 | 21 | printf("Sqaure Root of Given No is %.4f\n",i); 22 | printf("Using squrt=%lf\n",sqrt(n)); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /number_theory/squrt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc,char *argv[]){ 5 | 6 | if(argc==1){ 7 | printf("Error\n"); 8 | return 0; 9 | } 10 | 11 | int n; 12 | n= atoi(argv[1]); 13 | float i=0.00; 14 | while(i*i<=n){ 15 | printf("\ni= %f",i); 16 | i+=0.001; 17 | } 18 | i-=0.001; 19 | 20 | printf("Sqaure Root of Given No is %.4f\n",i); 21 | //printf("Using squrt=%lf\n",sqrt(n)); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /number_theory/swap.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a,int *b){ 4 | int c=*a; 5 | *a = *b; 6 | *b = c; 7 | } 8 | 9 | int main(int argc,char *argv[]){ 10 | if(argc!=3) 11 | return 0; 12 | 13 | int i1 = atoi(argv[1]); 14 | int i2 = atoi(argv[2]); 15 | 16 | /*int temp = i1; 17 | i1=i2; 18 | i2=i1;*/ 19 | swap(&i1,&i2); 20 | 21 | printf("i1= %d,i2= %d\n",i1,i2); 22 | 23 | 24 | return 0; 25 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "popular_coding_questions_solution", 3 | "version": "1.0.0", 4 | "description": "This Repository contains all the important coding solutions, which may be asked in Mass Recruitment exams like WIPRO elite NLTH,TCS Ninja Online Tests etc and it also contains previous year solved Coding Questions.", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "type": "module", 10 | "repository": { 11 | "type": "git", 12 | "url": "git+https://github.com/saurabh47/Popular_Coding_Questions_Solution.git" 13 | }, 14 | "author": "", 15 | "license": "ISC", 16 | "bugs": { 17 | "url": "https://github.com/saurabh47/Popular_Coding_Questions_Solution/issues" 18 | }, 19 | "homepage": "https://github.com/saurabh47/Popular_Coding_Questions_Solution#readme" 20 | } 21 | -------------------------------------------------------------------------------- /patterns/pattern_1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | 5 | int n,space,p=1,q=1,s,val2; 6 | int tc[100]; 7 | printf("Enter the values\n"); 8 | scanf("%d",&n); 9 | 10 | //printf("%d\n",5/2); 11 | for(int i=0;i 2 | 3 | void swap(int *a,int *b){ 4 | int c = *a; 5 | *a = *b; 6 | *b = c; 7 | } 8 | 9 | int main(int argc,char *argv[]){ 10 | if(argc==1) 11 | return 0; 12 | int arr[argc-1]; 13 | int i =0; 14 | int n=argc-1,j=0; 15 | 16 | for(i=0;iarr[j+1]){ 23 | swap(&arr[j],&arr[j+1]); 24 | } 25 | } 26 | } 27 | 28 | for(i=0;i O(n^2) (Best case -> O(n)) 4 | * Space Complexity -> O(1) 5 | * This technique is useful for the partially sorted array 6 | * In case of sorted array time complexity will be O(n) 7 | * https://leetcode.com/problems/sort-an-array/ 8 | * @param {number[]} nums 9 | * @return {number[]} 10 | */ 11 | var sortArray = function (nums) { 12 | insertionSort(nums); 13 | return nums; 14 | }; 15 | 16 | function insertionSort(arr) { 17 | let n = arr.length; 18 | 19 | for (let i = 1; i < n; i++) { 20 | let temp = arr[i]; 21 | let j = i - 1; 22 | for (; j >= 0; j--) { 23 | if (arr[j] > temp) { 24 | arr[j + 1] = arr[j]; 25 | } else { 26 | break; 27 | } 28 | } 29 | arr[j + 1] = temp; 30 | } 31 | } 32 | 33 | 34 | 35 | console.log(sortArray([5, 2, 3, 4, 1, 4])); -------------------------------------------------------------------------------- /sorting/SelectionSort/selection_sort.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Selection Sort 3 | * Time Complexity -> O(n^2) 4 | * Space Complexity -> O(1) 5 | * https://leetcode.com/problems/sort-an-array/ 6 | * @param {number[]} nums 7 | * @return {number[]} 8 | */ 9 | var sortArray = function (nums) { 10 | selectionSort(nums); 11 | return nums 12 | }; 13 | 14 | function selectionSort(arr) { 15 | let n = arr.length; 16 | for (let i = 0; i < n - 1; i++) { 17 | let minIdx = i; 18 | for (let j = i + 1; j < n; j++) { 19 | if (arr[j] < arr[minIdx]) { 20 | minIdx = j; 21 | } 22 | } 23 | swap(arr, i, minIdx); 24 | } 25 | } 26 | 27 | function swap(arr, s, d) { 28 | let t = arr[d]; 29 | arr[d] = arr[s]; 30 | arr[s] = t; 31 | } 32 | 33 | console.log(sortArray([5, 2, 3, 4, 1, 4])); -------------------------------------------------------------------------------- /sorting/SelectionSort/selection_sort.py: -------------------------------------------------------------------------------- 1 | # Selection Sort 2 | 3 | # Time Complexity: O(n^2) 4 | # Space Complexity: O(1) 5 | 6 | def swap(i, j): 7 | temp = arr[i] 8 | arr[i] = arr[j] 9 | arr[j] = temp 10 | 11 | def selection_sort(arr): 12 | for i in range(len(arr)): 13 | smallest = i 14 | for j in range(i, len(arr)): 15 | if(arr[j] < arr[smallest]): 16 | smallest = j 17 | swap(smallest, i) 18 | print(arr) 19 | print("sorted arr=", arr) 20 | 21 | print("Enter the number of elements in the array") 22 | n = int(input()) 23 | print("Enter the elements of the array") 24 | arr = list(map(int, input().split())) 25 | selection_sort(arr) -------------------------------------------------------------------------------- /sorting/SelectionSort/sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | // printf("%c",argv[1][1]); 5 | int n=sizeof(argv[1])/2; 6 | char arr[n]; 7 | // printf("%d",sizeof(argv[1])); 8 | int k=0; 9 | for(int i=0;i Selection Sort cannot be optimized to perform better than O(n^2) in terms of time complexity. Even if you maintain a min index array, the time complexity remains the same. Because the original changes after swap which will invalidate the min index array. 10 | 11 | The problems with selection sort are: 12 | - It has O(n^2) time complexity, which makes it inefficient on large lists. 13 | - The time complexity is still O(N^2) even if the list is already sorted. 14 | - It has O(n) swaps, which is not ideal for memory usage. 15 | 16 | -------------------------------------------------------------------------------- /stack/valid_parentheses.js: -------------------------------------------------------------------------------- 1 | /** 2 | * https://leetcode.com/explore/learn/card/queue-stack/230/usage-stack/1361/ 3 | * @param {string} s 4 | * @return {boolean} 5 | */ 6 | var isValid = function (s) { 7 | 8 | let stack = []; 9 | 10 | for (let c of s) { 11 | let top = stack[stack.length - 1]; 12 | if (top && (top === '(' && c === ')') || 13 | (top === '[' && c === ']') || 14 | (top === '{' && c === '}')) { 15 | stack.pop(); 16 | } else { 17 | stack.push(c); 18 | } 19 | } 20 | return stack.length === 0; 21 | 22 | }; 23 | 24 | console.log(isValid("()[]{}")) 25 | console.log(isValid("(]")) -------------------------------------------------------------------------------- /string_manipulation/Readme.md: -------------------------------------------------------------------------------- 1 | ### String Manipulation 2 | 3 | ## [Palindrome](https://en.wikipedia.org/wiki/Palindrome) 4 | 5 | A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, 6 | e.g Anna,1221,Noon,Racecar etc 7 | 8 | ## Number Palindrome 9 | 10 | given an input number print its reverse as output 11 | e.g input-->123 output-->321 12 | 13 | ## String Palindrome 14 | 15 | Input: IAMGOD 16 | Output: DOGMAI 17 | 18 | #### [Removing vowels from string](https://en.wikipedia.org/wiki/Vowel) 19 | ``` 20 | A vowel is a syllabic speech sound pronounced without any stricture in the vocal tract. Vowels are one of the two principal classes of speech sounds, the other being the consonant. Vowels vary in quality, in loudness and also in quantity. 21 | In english language there are 5 vowels "a, e, i, o, u" 22 | ``` 23 | 24 | #### Capitalizing string or Decaptializing 25 | ``` 26 | input : hello world 27 | output: Hello World 28 | ``` 29 | -------------------------------------------------------------------------------- /string_manipulation/StringReverse.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int sl(char *p) 4 | { 5 | int l = 0; 6 | while (*p != '\0') 7 | { 8 | l++; 9 | p++; 10 | } 11 | return l; 12 | } 13 | 14 | void main(int argc, char *argv[]) 15 | 16 | { 17 | 18 | char *s, r[100]; 19 | int i; 20 | 21 | s = (argv[1]); 22 | 23 | int l = sl(s); 24 | int end = l - 1; 25 | 26 | for (i = 0; i < l; i++) 27 | { 28 | r[i] = s[end]; 29 | end--; 30 | } 31 | r[i] = '\0'; 32 | 33 | printf("\n%s", r); 34 | 35 | getch(); 36 | } 37 | -------------------------------------------------------------------------------- /string_manipulation/camel.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | int main (int argc,char *argv[]) { 6 | int i = 0; 7 | char c; 8 | char str[100]; 9 | 10 | gets(str); 11 | for(i=0;str[i]!='\0';i++) 12 | { 13 | if(i==0) 14 | str[i]=toupper(str[i]); 15 | else if(str[i]==32) 16 | str[i+1]=toupper(str[i+1]); 17 | 18 | } 19 | 20 | printf("%s",str); 21 | 22 | 23 | return(0); 24 | } 25 | -------------------------------------------------------------------------------- /string_manipulation/camel_cmd.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int main(int argc,char *argv[]){ 5 | if(argc == 1) 6 | return 0; 7 | 8 | for(int i=1;i=97&&argv[i][0]<=127){ 10 | argv[i][0] = argv[i][0] -32; 11 | } 12 | } 13 | 14 | for(int i=1;i 2 | 3 | int main(int argc,char *argv[]){ 4 | int i=0; 5 | int val=argv[1][0]; // 65-A Z-90 97-a 122-z 6 | char c; 7 | printf("%c",val); 8 | while(argv[1][i]!='\0'){ 9 | val=argv[1][i]; 10 | if(val>=97 && val <=122){ // small letter 11 | int k=val-32; //ascii val of caps char 12 | c=k; // get char for that ascii 13 | argv[1][i]=c; 14 | } 15 | if(val>=65 && val<=90){ // capital letter 16 | int k=val+32; //ascii value of small char 17 | c=k; 18 | argv[1][i]=c; 19 | } 20 | i++; 21 | } 22 | printf("\n%s",argv[1]); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /string_manipulation/eliminatevowels.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(int argc,char *argv[]){ 4 | if(argc==1) 5 | return 0; 6 | char arr[100]; 7 | 8 | int k=0; 9 | for(int i=0;argv[1][i]!='\0';i++){ 10 | if((argv[1][i]=='a') || (argv[1][i]=='e') || (argv[1][i]=='i') || (argv[1][i]=='o') || (argv[1][i]=='u')){} 11 | else{ 12 | arr[k]=argv[1][i]; 13 | k++; 14 | } 15 | } 16 | 17 | printf("%s\n", arr); 18 | 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /string_manipulation/lower.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void upper_string(char []); 4 | 5 | int main(int argc,char *argv[]) 6 | { 7 | char string[100]; 8 | // = argv[1]; 9 | 10 | printf("Enter a string to convert it into upper case\n"); 11 | gets(string); 12 | 13 | upper_string(string); 14 | 15 | printf("The string in upper case: %s\n", string); 16 | 17 | return 0; 18 | } 19 | 20 | void upper_string(char *s) { 21 | int c = 0; 22 | while (*s != '\0') { 23 | if (*s >= 'A' && *s <= 'Z') { 24 | *s = *s + 32; 25 | //printf("%u\n", s); 26 | } 27 | s++; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /string_manipulation/string_length.c: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | String Length Function without using string.h library 4 | */ 5 | int strlength(char *ptr){ 6 | int count=0; 7 | while(*ptr!='\0'){ 8 | count++; 9 | ptr++; 10 | } 11 | return count; 12 | } -------------------------------------------------------------------------------- /string_manipulation/string_palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int getLen(char *p){ 5 | int l=0; 6 | while(*p!='\0'){ 7 | p++; 8 | l++; 9 | } 10 | return l; 11 | } 12 | 13 | int main(int argc,char *argv[]){ 14 | 15 | if(argc==1){ 16 | printf("Error\n"); 17 | return 0; 18 | } 19 | //printf("Length L = %d\n",getLen(argv[1])); 20 | 21 | int i=0,flag=0; 22 | int L = getLen(argv[1]),j = L-1; 23 | while(i<=L/2){ 24 | if(argv[1][i]!=argv[1][j]){ 25 | flag =1; 26 | break; 27 | } 28 | i++; 29 | j--; 30 | } 31 | 32 | 33 | 34 | if(flag){ 35 | printf("Given string is Not Palindrome\n"); 36 | }else{ 37 | printf("Given string is Palindrome\n"); 38 | } 39 | 40 | return 0; 41 | } -------------------------------------------------------------------------------- /string_manipulation/upper.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | void upper_string(char []); 4 | 5 | int main(int argc,char *argv[]) 6 | { 7 | char string[100]; 8 | // = argv[1]; 9 | 10 | printf("Enter a string to convert it into upper case\n"); 11 | gets(string); 12 | 13 | upper_string(string); 14 | 15 | printf("The string in upper case: %s\n", string); 16 | 17 | return 0; 18 | } 19 | 20 | void upper_string(char *s) { 21 | int c = 0; 22 | while (*s != '\0') { 23 | if (*s >= 'a' && *s <= 'z') { 24 | *s = *s - 32; 25 | //printf("%u\n", s); 26 | } 27 | s++; 28 | } 29 | } 30 | --------------------------------------------------------------------------------