ghostmkg/dsa-code/main 540k tokens More Tools
```
├── .gitignore
├── .history/
   ├── java/
      ├── Chatbot_20251011133817.java (300 tokens)
      ├── Chatbot_20251011135524.java (300 tokens)
      ├── HeapSort_20251011141215.java
      ├── HeapSort_20251011141222.java
      ├── HeapSort_20251011141235.java (400 tokens)
      ├── LeadersInArr_20251011135825.java
      ├── LeadersInArr_20251011135904.java (100 tokens)
      ├── Sorting/
         ├── HeapSort_20251011140107.java
         ├── HeapSort_20251011140130.java (400 tokens)
         ├── HeapSort_20251011140206.java (400 tokens)
         ├── HeapSort_20251011140225.java (400 tokens)
         ├── HeapSort_20251011140327.java (400 tokens)
         ├── HeapSort_20251011140402.java (400 tokens)
         ├── HeapSort_20251011140409.java (400 tokens)
         ├── HeapSort_20251011140505.java
         ├── HeapSort_20251011140530.java
         ├── HeapSort_20251011140554.java (400 tokens)
         ├── HeapSort_20251011140931.java (400 tokens)
         ├── HeapSort_20251011140956.java (400 tokens)
├── .idea/
   ├── .gitignore
   ├── misc.xml (100 tokens)
   ├── modules.xml (100 tokens)
   ├── vcs.xml
├── .vscode/
   ├── c_cpp_properties.json (100 tokens)
   ├── launch.json (700 tokens)
   ├── settings.json (300 tokens)
   ├── tasks.json (100 tokens)
├── 75-Dsa-Problems/
   ├── Binary-Search/
      ├── Arranging_coins.cpp
      ├── FindMinRotatedArray.cpp (200 tokens)
      ├── FindPeak.cpp (100 tokens)
      ├── graph/
         ├── NumberOfIslands.cpp (500 tokens)
      ├── kokoEating.cpp (200 tokens)
      ├── searchRotatedArray.cpp (200 tokens)
├── Add Code Here/
   ├── .DS_Store
   ├── JAVA/
      ├── AnagramChecker.java (1400 tokens)
      ├── BinarySearch.java (400 tokens)
      ├── BubbleSort_ascending.java (200 tokens)
      ├── CycleSort.class
      ├── CycleSort.java (400 tokens)
      ├── EvenOddChecker.java (200 tokens)
      ├── FibonacciMemoization.java (900 tokens)
      ├── MergeSort.class
      ├── MergeSort.java (200 tokens)
      ├── ReverseArray.java (100 tokens)
├── Algorithms/
   ├── dijkstra.py (200 tokens)
├── AreaCalculator.class
├── AreaCalculator.java (400 tokens)
├── Best Time to Buy and Sell Stock.cpp (100 tokens)
├── BinarySearchTree.py (800 tokens)
├── C/
   ├── 1d_array_sum.c (100 tokens)
   ├── Binary_Search_Tree.c (200 tokens)
   ├── Bubble Sort - C (200 tokens)
   ├── Bubble_Sort.c (100 tokens)
   ├── Climbing_Stairs.c (300 tokens)
   ├── Factorial_using_recursion.c (100 tokens)
   ├── FrogJump.c (600 tokens)
   ├── Insertion.c (200 tokens)
   ├── List-Flattening.c (400 tokens)
   ├── Merge_Sort.c (200 tokens)
   ├── Queue.c (200 tokens)
   ├── Queue_implementation_using_array.c (200 tokens)
   ├── Quick_Sort.c (200 tokens)
   ├── Recursive_Quick_Sort.c (200 tokens)
   ├── Reverse_Array.c (100 tokens)
   ├── Sieve_of_Eratosthene.c (200 tokens)
   ├── Singly_Linked_List.c (200 tokens)
   ├── Stack.c (200 tokens)
   ├── Stack_implementation_Using_array.c (100 tokens)
   ├── Two sum questions (100 tokens)
   ├── array_deletion.c (200 tokens)
   ├── array_insertion.c (300 tokens)
   ├── array_manipulation.c (1400 tokens)
   ├── array_searching.c (200 tokens)
   ├── array_traversal.c (100 tokens)
   ├── array_update.c (100 tokens)
   ├── binarysearch.c (200 tokens)
   ├── bubble_sorting.c (100 tokens)
   ├── bubblesort.c (200 tokens)
   ├── circular_queue.c
   ├── count_set_bits.c (100 tokens)
   ├── deadlock_avoidance.c (300 tokens)
   ├── fibonacci.c
   ├── file_handling_with_linear_search.c (200 tokens)
   ├── floyd_warshall.c (300 tokens)
   ├── gcd.c (100 tokens)
   ├── graphs/
      ├── graph_bfs
      ├── graph_bfs.c (300 tokens)
   ├── helloworld.c
   ├── insertion_sort_using_rand_function.c (100 tokens)
   ├── kadane.c (200 tokens)
   ├── leastCommonSubsequence.c (500 tokens)
   ├── linear_search_with_rand_function.c (200 tokens)
   ├── longest_word_length.c (100 tokens)
   ├── majority_element.c (200 tokens)
   ├── matrix_multiplication.c (200 tokens)
   ├── mini_http_cache_server.c (2.3k tokens)
   ├── prime_number_fuction.c
   ├── pyramid_pattern.c (300 tokens)
   ├── race_circular_track_simulation.c (1300 tokens)
   ├── remove_duplicate_characters.c (100 tokens)
   ├── reverse_string_using_stack.c (100 tokens)
   ├── revesearray.c (100 tokens)
   ├── search_in_rotated_sorted_array.c
   ├── selection_sort.c (200 tokens)
   ├── selectionsort.c (100 tokens)
   ├── sortarray.c (200 tokens)
   ├── stringpalindrome.c (100 tokens)
   ├── syscall_interceptor.c (400 tokens)
   ├── towerofhanoi.c (200 tokens)
   ├── transpose_matrix.c (400 tokens)
├── Contribution_Dsa.md (200 tokens)
├── DSA#/
   ├── DSA-ALGORITHM (200 tokens)
   ├── Hard-LinkedListproblems.cpp (800 tokens)
   ├── JobScheduling.java (400 tokens)
   ├── LRU_Cache.cpp (600 tokens)
   ├── LinkedlistAlgos.cpp (200 tokens)
   ├── NOTES.md (700 tokens)
   ├── RatInAMaze DSA Algo CPP (300 tokens)
   ├── Sorting-Algos/
      ├── BubbleSort.java (200 tokens)
      ├── CountingSort.cpp (100 tokens)
      ├── HeapSort.java (400 tokens)
      ├── Huffman_Algorithm.cpp (300 tokens)
      ├── MergeSort.java (300 tokens)
      ├── QuickSort.java (300 tokens)
      ├── RadixSort.cpp (200 tokens)
      ├── ShellSort.cpp (100 tokens)
      ├── Sorting-Algorithms-Using-Python/
         ├── MergeSort.py (100 tokens)
         ├── QuickSort.py (200 tokens)
      ├── heap_sort.cpp (200 tokens)
      ├── selectionSort.java (200 tokens)
      ├── selection_sort.cpp (100 tokens)
   ├── heap_operation.py (300 tokens)
   ├── linkedlist_operation.py (300 tokens)
├── DSA-Project/
   ├── DSA-Project.iml (100 tokens)
   ├── src/
      ├── Main.java (300 tokens)
      ├── Task.java (100 tokens)
      ├── TodoList.java (200 tokens)
├── Dfs.java (200 tokens)
├── DoublyLinkedList.java (600 tokens)
├── Dsa_sum (200 tokens)
├── FactorialExample.class
├── FactorialExample.java (100 tokens)
├── Int_as_sum_of_powers.py (100 tokens)
├── LICENSE (omitted)
├── LIS_Dsa (300 tokens)
├── LIS_Dsa_Code.md (300 tokens)
├── LongestCommonPrefix.java (200 tokens)
├── MergeSort.java (600 tokens)
├── MoveZeros.java (100 tokens)
├── MultiplicationTable.class
├── MultiplicationTable.java (100 tokens)
├── Product of Array Except Self.cpp (100 tokens)
├── Projects/
   ├── android/
      ├── NotesApp/
         ├── app/
            ├── src/
               ├── main/
                  ├── java/
                     ├── com/
                        ├── example/
                           ├── notesapp/
                              ├── MainActivity.java (300 tokens)
                  ├── res/
                     ├── layout/
                        ├── activity_main.xml (300 tokens)
      ├── NumberGuessingGame/
         ├── app/
            ├── src/
               ├── main/
                  ├── java/
                     ├── com/
                        ├── example/
                           ├── numberguess/
                              ├── MainActivity.java (600 tokens)
                  ├── res/
                     ├── layout/
                        ├── activity_main.xml (300 tokens)
      ├── SimpleCounterApp/
         ├── app/
            ├── src/
               ├── main/
                  ├── java/
                     ├── com/
                        ├── example/
                           ├── simplecounter/
                              ├── MainActivity.java (200 tokens)
                  ├── res/
                     ├── layout/
                        ├── activity_main.xml (200 tokens)
   ├── java_projects/
      ├── CalculatorApp/
         ├── Calculator.java (100 tokens)
         ├── Main.java (300 tokens)
      ├── StudentManagement/
         ├── Main.class
         ├── Main.java (400 tokens)
         ├── Student.class
         ├── Student.java (100 tokens)
      ├── ToDoListApp/
         ├── Main.java (500 tokens)
         ├── Task.java (100 tokens)
├── QuickSort (300 tokens)
├── README.md (800 tokens)
├── README_hi.md (700 tokens)
├── RadixSort.java (300 tokens)
├── Roman to Integer.cpp (100 tokens)
├── SQL/
   ├── A1.sql (300 tokens)
   ├── A2.sql (400 tokens)
   ├── A3.sql (400 tokens)
   ├── A4.sql (200 tokens)
   ├── ActiveUsersInLast30Days.sql
   ├── AverageDepartmentSalary.sql (100 tokens)
   ├── BiggestSingleNumber.sql
   ├── CityWithHighestAverageSalary.sql
   ├── CombineTwoTables.sql
   ├── ConsecutiveNumbers.sql (200 tokens)
   ├── CountSalaryCategories.sql (100 tokens)
   ├── CustomerRetentionRate.sql (100 tokens)
   ├── CustomerWhoVisitedButDidNotMakeAnyTransaction.sql (100 tokens)
   ├── CustomersWhoNeverOrder.sql
   ├── DeleteDuplicateEmails.sql
   ├── DepartmentHighestSalary.sql (100 tokens)
   ├── DepartmentTop3Salaries.sql (100 tokens)
   ├── DepartmentTopThreeSalaries.sql (100 tokens)
   ├── DuplicateEmails.sql
   ├── DuplicateProducts.sql
   ├── EmployeeBonus.sql
   ├── EmployeeManagerHierarchy.sql
   ├── EmployeeProjectCount.sql
   ├── EmployeesWithoutBonus.sql
   ├── ExchangeSeats.sql
   ├── FindFollowersCount.sql
   ├── FixNamesInTable.sql
   ├── MonthlyActiveUsers.sql
   ├── MonthlyRevenueGrowth.sql (100 tokens)
   ├── MonthlyTransactions1.sql (100 tokens)
   ├── MostPurchasedProduct.sql
   ├── NotBoringMovies.sql
   ├── NthHighestSalary.sql
   ├── PatientsWithACondition.sql.sql
   ├── ProjectEmployeesI.sql
   ├── ProjectWithMostEmployees.sql
   ├── RankScores.sql
   ├── RisingTemperature.sql
   ├── SalesPerson.sql
   ├── SecondHighestSalary.sql
   ├── SwapSalary.sql
   ├── TopCustomers.sql
   ├── TopSellingCategory.sql (100 tokens)
   ├── TriangleJudgement.sql
   ├── high_value_orders_percentage.sql
├── Square_SubMat_With_Ones.py (300 tokens)
├── TODO.md (100 tokens)
├── TreeTraversal.java (300 tokens)
├── Unique_Paths.py
├── c++/
   ├── 118_PascalsTriangle.cpp (100 tokens)
   ├── 121_BestTimeToBuySellStock.cpp (100 tokens)
   ├── 1226-the-dining-philosophers.cpp (200 tokens)
   ├── 135_Candy.cpp (300 tokens)
   ├── 1518_Water_Bottles.cpp (300 tokens)
   ├── 2104-sum-of-subarray-ranges.cpp (500 tokens)
   ├── 2149RearrangeArrayElementsBySign.cpp (100 tokens)
   ├── 2dmatrix.cpp (100 tokens)
   ├── 30_SubstringwithConcatenationofAllWords.cpp (900 tokens)
   ├── 3100-Water-Bottles-II.cpp (200 tokens)
   ├── 4-Median-of-Two-Sorted-Arrays.cpp (100 tokens)
   ├── 417-PacificAtlanticWaterFlow/
      ├── 417-PacificAtlanticWaterFlow.cpp (600 tokens)
      ├── 417-PacificAtlanticWaterFlow.java (600 tokens)
      ├── README.md (1500 tokens)
   ├── 41_FirstMissingPositive.cpp (200 tokens)
   ├── 53_MaxSubArray.cpp (100 tokens)
   ├── 546_RemoveBoxes.cpp (400 tokens)
   ├── 60_Permutation_Sequence.cpp (200 tokens)
   ├── 62_UniquePaths.cpp (100 tokens)
   ├── 705_design_hashset.cpp (200 tokens)
   ├── 706_design_hashmap.cpp (300 tokens)
   ├── 75_SortColors.cpp (100 tokens)
   ├── 79_WordSearch.cpp (300 tokens)
   ├── 87_ScrambleString.cpp (500 tokens)
   ├── Access Code.cpp (100 tokens)
   ├── Accessing_Inherited_Functions.cpp (400 tokens)
   ├── ActivitySelection.cpp (200 tokens)
   ├── Add Arranging Coins Implementation in C++ #449.cpp (100 tokens)
   ├── Add multiple nodes at the start of the Linked List.cpp (100 tokens)
   ├── AddBinary.cpp (200 tokens)
   ├── Aggressive Cows.cpp (200 tokens)
   ├── Algorithm/
      ├── Bucket Sort.cpp (200 tokens)
      ├── KMP.cpp (200 tokens)
      ├── binarySearch.cpp (300 tokens)
      ├── bubble_sort.cpp (200 tokens)
      ├── heapsort.cpp (300 tokens)
      ├── kandane_algo.cpp (200 tokens)
      ├── merge_sort.cpp (300 tokens)
      ├── quick_sort.cpp (200 tokens)
      ├── shell_sort.cpp (200 tokens)
   ├── Alien Dictionary.cpp (300 tokens)
   ├── All Unique Permutation in Array CPP.cpp (100 tokens)
   ├── Allocate Minimum Number of Pages Implementation.cpp (200 tokens)
   ├── Arranging Coins Implementation.cpp
   ├── Array/
      ├── 11. ContainerWithMostWater.cpp (100 tokens)
      ├── 2sum.cpp (200 tokens)
      ├── 349. IntersectioofTwoArrays.cpp (100 tokens)
      ├── 4-sum.cpp (300 tokens)
      ├── 48_RotateImage.cpp (400 tokens)
      ├── BinarySearch.cpp (200 tokens)
      ├── Duplicate.cpp (100 tokens)
      ├── FindMissingNumber
      ├── FindMissingNumber.cpp (100 tokens)
      ├── Kadane.cpp (100 tokens)
      ├── KadanesAlgorithm.cpp (3k tokens)
      ├── Largest_elements.cpp (200 tokens)
      ├── LeadersInArray.cpp (300 tokens)
      ├── Longes.cpp (200 tokens)
      ├── MaxElement.cpp (100 tokens)
      ├── MaxProductSubarray.cpp (200 tokens)
      ├── Max_cons_ones.cpp (200 tokens)
      ├── Merge_Sort.cpp (300 tokens)
      ├── Min.cpp (300 tokens)
      ├── Move_Zero_To_End.cpp (100 tokens)
      ├── NextGreaterElement.cpp (100 tokens)
      ├── QuickSort.cpp (300 tokens)
      ├── Rearrange_Array_By_Sign.cpp (200 tokens)
      ├── Reverse.cpp (100 tokens)
      ├── RotateArray.cpp (300 tokens)
      ├── Second_largest.cpp (300 tokens)
      ├── Sort_0_1_2.cpp (200 tokens)
      ├── Uni.cpp (200 tokens)
      ├── addT.cpp (200 tokens)
      ├── addingSum.cpp (100 tokens)
      ├── array intersection.cpp (100 tokens)
      ├── arraypairsum.cpp (100 tokens)
      ├── create-maximum-number.cpp (700 tokens)
      ├── findTheSmall.cpp (300 tokens)
      ├── linearsearch.cpp (100 tokens)
      ├── majorityelement.cpp (200 tokens)
      ├── median_of_two_sorted_array.cpp (200 tokens)
      ├── merge_two_sorted_arrays.cpp (200 tokens)
      ├── threeSum.cpp (300 tokens)
      ├── twosum.cpp (200 tokens)
   ├── Articulation and Brifge points/
      ├── Articulation_Point_Bridges.sublime-snippet (400 tokens)
   ├── BIn search.cpp (100 tokens)
   ├── BankingSystemUsingClasses.cpp (200 tokens)
   ├── BellmanFord.cpp (200 tokens)
   ├── Best Time to Buy and Sell Stock.cpp (100 tokens)
   ├── Binary Search/
      ├── Aggressive-Cow.cpp (300 tokens)
      ├── Allocate-Minimum-Pages.cpp (300 tokens)
      ├── Arranging-Coins.cpp (300 tokens)
      ├── ArrangingCoin.cpp (100 tokens)
      ├── ArrangingCoin.exe
      ├── Binary Search to Find First Occurrence.cpp (200 tokens)
      ├── Capacity-Ship-Packages-Within-D-Days.cpp (300 tokens)
      ├── Count-Negative-Numbers-in-a-Sorted-Matrix.cpp (100 tokens)
      ├── Find-K-Closest-Elements.cpp (100 tokens)
      ├── FindBadVersion.cpp (100 tokens)
      ├── Iterative Binary Search (Standard Form).cpp (100 tokens)
      ├── Koko-Eating-Bananas.cpp (400 tokens)
      ├── Median of Two Sorted Arrays (200 tokens)
      ├── MedianMatrix.cpp (300 tokens)
      ├── Recursive Binary Search.cpp (100 tokens)
      ├── Search in rotated sorted array (200 tokens)
      ├── exponential_search.cpp (300 tokens)
      ├── kokoEatingBananas.cpp (200 tokens)
      ├── kokoEatingBananas.exe
      ├── min_days_for_m_bouquets.cpp (400 tokens)
      ├── painter_partition.cpp (300 tokens)
      ├── split_array_largest_sum.cpp (200 tokens)
   ├── Binary Trees/
      ├── Catalan_number.cpp (100 tokens)
      ├── ConstructBinarytree.cpp (700 tokens)
      ├── FlatteningBinarySearchTreeCPP (700 tokens)
      ├── Maximum_path_sum.cpp (200 tokens)
      ├── Postorder_traversal.cpp
      ├── Preorder_traversal.cpp
      ├── boundary_traversal.cpp (600 tokens)
      ├── chack_balance.cpp (300 tokens)
      ├── diameter_of_tree.cpp (200 tokens)
      ├── inorder_traversal.cpp
      ├── level_order_traversal.cpp (300 tokens)
      ├── lowest_common_ancestor.cpp (100 tokens)
      ├── max_depth_of_tree.cpp (200 tokens)
      ├── mirror_check_tree.cpp (200 tokens)
      ├── symmetric_check_tree.cpp (200 tokens)
      ├── top_view_tree.cpp (500 tokens)
      ├── vertical_traversal.cpp (300 tokens)
      ├── zigzag_traversal.cpp (500 tokens)
   ├── BinaryGap.cpp (300 tokens)
   ├── BinaryNumberwithAlternatingBits.cpp (200 tokens)
   ├── BinarySearch (200 tokens)
   ├── BinarySearch.c++ (200 tokens)
   ├── BinarySearch.cpp (300 tokens)
   ├── BitwiseANDofNumbersRange.cpp (100 tokens)
   ├── Capacity To Ship Packages Within D Days Implementation.cpp (200 tokens)
   ├── Cheapest Flights Within K Stops.cpp (100 tokens)
   ├── Check_for_anagram.cpp (200 tokens)
   ├── Cherry_Pickup.cpp (400 tokens)
   ├── Classes.cpp (200 tokens)
   ├── Climbing Stairs.cpp (100 tokens)
   ├── Codeforces TLE 1200/
      ├── .cph/
         ├── .01ThreeActivities.cpp_3006c09d1a5b43f51677557e49ecff62.prob (100 tokens)
         ├── .03PlusMinusPermutation.cpp_42532c11987e0b0d2701e361df0a204d.prob (100 tokens)
         ├── .04AssemblyviaMinimums.cpp_abd9dc74f793314437b52e108227f2ec.prob (100 tokens)
         ├── .04VikaandtheBridge.cpp_fd999f5858ce99e014f522e074a3eaff.prob (100 tokens)
         ├── .05ContrastValue.cpp_dfef0bbe4ce0d5666165d353a14a8c6b.prob (100 tokens)
         ├── .06PlayingInACasino.cpp_648ebb0ee86b28dc5b3aee46d088eb40.prob (100 tokens)
         ├── .07DoraandSearch.cpp_b4c0ea13c4bab26b129b5dc8562381a1.prob (100 tokens)
         ├── .08Matryoshkas.cpp_baa28591d90e163fb85fc409d0875f2d.prob (100 tokens)
         ├── .09Scuza.cpp_8f9c72624c74091ec58462453479d908.prob (100 tokens)
         ├── .10RemovingSmallestMultiples.cpp_6f921bdb9f74dc989a0209cb691e3614.prob (100 tokens)
         ├── .11FriendsandtheRestaurant.cpp_dbc633a096d23bc260785440e11e526e.prob (100 tokens)
         ├── .12Virus.cpp_3b90c60dbc5aa9106c4511fa863e8986.prob (100 tokens)
         ├── .13MirrorGrid.cpp_cd0f3956aa608016f8c0c136b8ac5e8f.prob (100 tokens)
         ├── .14BinaryDeque.cpp_c17ea9ea77e7e2d1685da6951403c161.prob (100 tokens)
      ├── 01ThreeActivities.cpp (900 tokens)
      ├── 03PlusMinusPermutation.cpp (900 tokens)
      ├── 04AssemblyviaMinimums.cpp (700 tokens)
      ├── 04VikaandtheBridge.cpp (800 tokens)
      ├── 05ContrastValue.cpp (800 tokens)
      ├── 06PlayingInACasino.cpp (800 tokens)
      ├── 07DoraandSearch.cpp (900 tokens)
      ├── 08Matryoshkas.cpp (800 tokens)
      ├── 09Scuza.cpp (900 tokens)
      ├── 10RemovingSmallestMultiples.cpp (800 tokens)
      ├── 11FriendsandtheRestaurant.cpp (800 tokens)
      ├── 12Virus.cpp (800 tokens)
      ├── 13MirrorGrid.cpp (1100 tokens)
      ├── 14BinaryDeque.cpp (1100 tokens)
   ├── Codeforces TLE 800/
      ├── .cph/
         ├── .19_unit_array.cpp_9eabb51500dbb5ebc61329988ad7707d.prob (100 tokens)
         ├── .20_twin_permutaions.cpp_df6fba90849c1a368f8f7e33e36f243a.prob (100 tokens)
         ├── .21_blank_space.cpp_6e0efb43104ad8e5d35ea5be06ba70eb.prob (100 tokens)
         ├── .22_coins.cpp_164be45384eaca638463f3a369f6180d.prob (100 tokens)
         ├── .23_walking_master.cpp_075d78b561aa28eda7929dc098ec1f7b.prob (100 tokens)
         ├── .24_we_need_the_zero.cpp_9a37d6db3c6bc0822950c6df11f4c726.prob (100 tokens)
         ├── .25_prepend_and_append.cpp_4ac37e4ea4e89e51f00c238319d76647.prob (100 tokens)
         ├── .26_serval_mocha_array.cpp_920798fb85ca1770fd0ae124a1a2f08f.prob (100 tokens)
         ├── .27_one_and_two.cpp_a0539632cc138b8e8e616bf02f025d7f.prob (100 tokens)
         ├── .28_make_it_beautiful.cpp_0cec2e2b6785acad29b36de44302095b.prob (100 tokens)
         ├── .29_everybody_likes_good_array.cpp_8d924c65f2cd0da8b00d507adb981686.prob (100 tokens)
         ├── .30_Extremely_round.cpp_80a392e8962518cba7e223a1f9045d70.prob (100 tokens)
         ├── .31_Two_permutations.cpp_ee441f010ea43eb010a7c194f02f068d.prob (100 tokens)
         ├── .Cover_in_Water.cpp_7f1deaeb5e992af28eb4e8ac52d4412b.prob (100 tokens)
         ├── .Desoring.cpp_98f1bef5890b75931dc3d8b0dfdf6895.prob (100 tokens)
         ├── .Game_with_Integers.cpp_6ab4a9f6e94ffced5c81ea6789de3ac1.prob (100 tokens)
         ├── .HaloumiBoxes.cpp_30ed157241437f6137c400ac4005d395.prob (100 tokens)
         ├── .Line_Trip.cpp_777389520c11e3b11923d50960e47e1b.prob (100 tokens)
         ├── .ambitious_kid.cpp_cb6aceb140bf3294f0be6f35610a46c0.prob (100 tokens)
         ├── .array_coloring.cpp_3c2b0916022ed61731ea129eafd17f86.prob (100 tokens)
         ├── .buttons.cpp_7a28795e9e76177ba8933859b6d22d7f.prob (100 tokens)
         ├── .dont_tru_to_count.cpp_e7d341f6612b8efe9c9a59e5e9e72636.prob (100 tokens)
         ├── .dont_try_to_count.cpp_41ad6b3823afc70e8676140adee7dfd1.prob (100 tokens)
         ├── .doremy_paint.cpp_cf463cce85224ee6b4938bfe4f487160.prob (100 tokens)
         ├── .goals_of_victory.cpp_11a87b94d42dc757c08e015a80d26eba.prob (100 tokens)
         ├── .grashopper_in_line.cpp_f093a9cb5a2e292b26a9f6e7b0654eef.prob (100 tokens)
         ├── .how_much_daytona_cost.cpp_06df88492cd564a670dd274711cece5d.prob (100 tokens)
         ├── .jagged_swap.cpp_e18ca5a4af67bcf90130babad0e275ed.prob (100 tokens)
         ├── .sequence_game.cpp_44f6cd2b1d9fed09a678442b29b42b39.prob (100 tokens)
         ├── .target_practice.cpp_c57586b2119560c68d0f45d03796f288.prob (200 tokens)
         ├── .united_we_stand.cpp_c10ab339b596e360f8aeecc762c3b50a.prob (100 tokens)
      ├── 01_HaloumiBoxes.cpp (300 tokens)
      ├── 02_Line_Trip.cpp (200 tokens)
      ├── 03_Cover_in_Water.cpp (200 tokens)
      ├── 04_Game_with_Integers.cpp (100 tokens)
      ├── 05_jagged_swap.cpp (100 tokens)
      ├── 06_doremy_paint.cpp (200 tokens)
      ├── 07_dont_try_to_count.cpp (100 tokens)
      ├── 08_how_much_daytona_cost.cpp (100 tokens)
      ├── 09_goals_of_victory.cpp (100 tokens)
      ├── 10_target_practice.cpp (200 tokens)
      ├── 11_ambitious_kid.cpp (100 tokens)
      ├── 12_sequence_game.cpp (200 tokens)
      ├── 13_united_we_stand.cpp (200 tokens)
      ├── 14_buttons.cpp (100 tokens)
      ├── 15_array_coloring.cpp (100 tokens)
      ├── 16_desorting.cpp (100 tokens)
      ├── 17_forbidden_integer.cpp (300 tokens)
      ├── 18_grashopper_in_line.cpp (100 tokens)
      ├── 19_unit_array.cpp (200 tokens)
      ├── 20_twin_permutaions.cpp (100 tokens)
      ├── 21_blank_space.cpp (100 tokens)
      ├── 22_coins.cpp (100 tokens)
      ├── 23_walking_master.cpp (100 tokens)
      ├── 24_we_need_the_zero.cpp (100 tokens)
      ├── 25_prepend_and_append.cpp (100 tokens)
      ├── 26_serval_mocha_array.cpp (200 tokens)
      ├── 27_one_and_two.cpp (200 tokens)
      ├── 28_make_it_beautiful.cpp (100 tokens)
      ├── 29_everybody_likes_good_array.cpp (100 tokens)
      ├── 30_Extremely_round.cpp (100 tokens)
      ├── 31_Two_permutations.cpp (100 tokens)
   ├── CodeforcesEducationalRound183Editorial/
      ├── candiesfornephews.cpp (400 tokens)
      ├── deckofcards.cpp (500 tokens)
   ├── Combination Sum.cpp (200 tokens)
   ├── Compute_decimal_representation.cpp (100 tokens)
   ├── Container With Most Water.cpp (100 tokens)
   ├── Container_With_Most_Water.cpp (100 tokens)
   ├── Count Negative Numbers in a Sorted Matrix Implementation.cpp (100 tokens)
   ├── CountTheNumberofConsistentStrings.cpp (300 tokens)
   ├── Count_Islands__with_Total_Value_Divisible_By_K.cpp (300 tokens)
   ├── Counting-Bits.cpp (100 tokens)
   ├── Counting-Sort.cpp (200 tokens)
   ├── Critical Connections in a Network.cpp (200 tokens)
   ├── DIDDY_sort.cpp (800 tokens)
   ├── DSU.cpp (400 tokens)
   ├── DecimaltoBinaryconvertion.cpp (100 tokens)
   ├── DecodeXORedArray.cpp (100 tokens)
   ├── Design Task Manager.cpp (800 tokens)
   ├── Design_MeetingScheduler_System.cpp (900 tokens)
   ├── Detect_Cycle_in_Directed_Graph/
      ├── README.md (500 tokens)
      ├── Solution.cpp
      ├── Solution.java
   ├── Dijkstra's Shortest Path Algorithm.cpp (1400 tokens)
   ├── DivisibleandNon-divisibleSumsDifference.cpp (100 tokens)
   ├── EarliestTimetoFinishOneTask.cpp (100 tokens)
   ├── EditDP.cpp (200 tokens)
   ├── EditDis.cpp (200 tokens)
   ├── Find K Closest Elements Implementation.cpp (200 tokens)
   ├── Find_the_Pivot_Integer.cpp (400 tokens)
   ├── First.cpp
   ├── Flood fill Algo Graph CPP (200 tokens)
   ├── FourSum.cpp (800 tokens)
   ├── Fractional_knapsack (200 tokens)
   ├── Freq.cpp (100 tokens)
   ├── Graph_Dehradun.cpp (400 tokens)
   ├── Graphs/
      ├── Accounts Merge.cpp (900 tokens)
      ├── BellmanFord.cpp (400 tokens)
      ├── Bridges in Graph - Using Tarjan's Algorithm of time in and low time.cpp (600 tokens)
      ├── Course Schedule.cpp (200 tokens)
      ├── DSU.cpp (400 tokens)
      ├── DSU2.cpp (700 tokens)
      ├── Dijkstra.cpp (600 tokens)
      ├── FloydWarshall.cpp (1700 tokens)
      ├── Making a Large Island .cpp (900 tokens)
      ├── Rotting Oranges.cpp (300 tokens)
      ├── Swim in Rising Water.cpp (500 tokens)
      ├── alien_dictionary.cpp (500 tokens)
      ├── course_scheduling.cpp (500 tokens)
      ├── cycle_detection_graoh_directed_BFS.cpp (300 tokens)
      ├── find centre graph.cpp
      ├── flood_fill_leetcode.cpp (400 tokens)
      ├── jump_game_3.cpp (200 tokens)
      ├── kruskals_algorithm.cpp (600 tokens)
      ├── max_area_of_island.cpp (300 tokens)
      ├── maximal_network_Rank.cpp (300 tokens)
      ├── number_of_enclaves.cpp (300 tokens)
      ├── number_of_islands.cpp (500 tokens)
      ├── number_of_provinces.cpp (200 tokens)
      ├── orange_rotting.cpp (500 tokens)
      ├── topological_sort.cpp (800 tokens)
      ├── word_ladder.cpp (300 tokens)
      ├── word_ladder_2.cpp (500 tokens)
   ├── Hard_Palindrome_Reorder.cpp (500 tokens)
   ├── Hashing/
      ├── div.cpp (100 tokens)
      ├── div.exe
      ├── freq.cpp
      ├── has1.cpp (100 tokens)
      ├── has1.exe
      ├── hashing.cpp (100 tokens)
      ├── hashing.exe
      ├── map.cpp (100 tokens)
      ├── map.exe
   ├── Implement_LRU_Cache/
      ├── README.md (500 tokens)
      ├── Solution.cpp
      ├── Solution.java
   ├── Interview/
      ├── 01.cpp (400 tokens)
      ├── 02.cpp (300 tokens)
      ├── 03.cpp (800 tokens)
      ├── 04.cpp (600 tokens)
      ├── 05.cpp (700 tokens)
      ├── 06.cpp (900 tokens)
      ├── 07.cpp (600 tokens)
      ├── 08.cpp (1000 tokens)
      ├── 09.cpp (900 tokens)
      ├── 10.cpp (600 tokens)
      ├── 11.cpp (600 tokens)
      ├── 12.cpp (800 tokens)
      ├── 13.cpp (700 tokens)
      ├── 14.cpp (600 tokens)
      ├── 15.cpp (600 tokens)
      ├── 16.cpp (1400 tokens)
      ├── 17.cpp (500 tokens)
      ├── 18.cpp (600 tokens)
      ├── 19.cpp (700 tokens)
      ├── 20.cpp (600 tokens)
      ├── 21.cpp (500 tokens)
      ├── 22.cpp (600 tokens)
      ├── 23.cpp (800 tokens)
      ├── 24.cpp (500 tokens)
      ├── 25.cpp (100 tokens)
      ├── README.md
   ├── Invert_Binary_tree.cpp (100 tokens)
   ├── Knapsack_problem.cpp (500 tokens)
   ├── KokoEatingBananas.cpp (300 tokens)
   ├── LRU_Cache.cpp (400 tokens)
   ├── Leetcode2273.cpp (200 tokens)
   ├── Leetcode_POTD/
      ├── 13thOct_LC2273.cpp (800 tokens)
      ├── 14thOct_LC3349.cpp (400 tokens)
      ├── 8thOct_LC2300.cpp (300 tokens)
      ├── add2num.cpp (300 tokens)
      ├── reverseoct17.cpp (200 tokens)
      ├── zigzag.cpp (200 tokens)
   ├── Lexicographically Smallest String After Applying Operations.cpp (400 tokens)
   ├── Li -cHAO-Tree.cpp (400 tokens)
   ├── Library_Management_System.cpp (700 tokens)
   ├── Library_Management_System.exe
   ├── Linked Lists/
      ├── Conveyer_Belt.cpp (600 tokens)
      ├── LinkedList_basics/
         ├── 1.cpp (100 tokens)
         ├── 10.insert_tail.cpp (200 tokens)
         ├── 11.insert_position.cpp (300 tokens)
         ├── 12.insert_element.cpp (300 tokens)
         ├── 2.convert_arr_to_ll.cpp (100 tokens)
         ├── 3.traversal_in_ll.cpp (100 tokens)
         ├── 4.search_in_ll.cpp (200 tokens)
         ├── 5.delete_head.cpp (200 tokens)
         ├── 6.delete_tail.cpp (200 tokens)
         ├── 7.delete_kth_element.cpp (300 tokens)
         ├── 8.remove_element.cpp (300 tokens)
         ├── 9.insert_head.cpp (200 tokens)
      ├── add_two_number_digitsinLL.cpp (400 tokens)
      ├── cycle_detection.cpp (200 tokens)
      ├── delete_middle_node.cpp (300 tokens)
      ├── deletenode.cpp (100 tokens)
      ├── detect_loop.cpp (700 tokens)
      ├── find_intersection.cpp (900 tokens)
      ├── removeNthFromEnd.cpp (300 tokens)
      ├── reverse linkedlist.cpp (100 tokens)
      ├── reverse.cpp (100 tokens)
      ├── reverse_LL.cpp (500 tokens)
   ├── LinkedList/
      ├── check_cycle_in_linked_list (100 tokens)
      ├── check_palindrome.cpp (300 tokens)
      ├── cloneLL.cpp (500 tokens)
      ├── merge_two_sorted_linked_lists.cpp (300 tokens)
      ├── middle_of_linked_list.cpp (200 tokens)
      ├── nodes_loop_detection.cpp (300 tokens)
      ├── pair_nodes_sum_k.cpp (300 tokens)
      ├── palindrome_check.cpp (300 tokens)
      ├── remove_duplicate_DLL.cpp (200 tokens)
      ├── reverse_nodes_kTimes.cpp (300 tokens)
      ├── rotate_nodes_kTimes.cpp (200 tokens)
   ├── LockFreeQueue.cpp (400 tokens)
   ├── Longest Palindromic Substring.cpp (300 tokens)
   ├── Longest_Substring_Without_Repeating_Characters.cpp (200 tokens)
   ├── Longest_common_subsequence.cpp (700 tokens)
   ├── Matrixmultiplication.cpp (100 tokens)
   ├── Maximum Number of Distinct Elements After Operations.cpp (200 tokens)
   ├── Maximum Subarray.cpp (100 tokens)
   ├── Median of Two Sorted Arrays.cpp (400 tokens)
   ├── Missing Number.cpp (100 tokens)
   ├── MissingNo.cpp (100 tokens)
   ├── Mo's_algorithm.cpp (400 tokens)
   ├── Network Delay Time.cpp (200 tokens)
   ├── Pacific Atlantic_Water_Flow.cpp (400 tokens)
   ├── Patterns/
      ├── 1.cpp (100 tokens)
      ├── 10.cpp (100 tokens)
      ├── 10.exe
      ├── 11.cpp (100 tokens)
      ├── 11.exe
      ├── 12.cpp (100 tokens)
      ├── 12.exe
      ├── 13.cpp (100 tokens)
      ├── 13.exe
      ├── 14.cpp (100 tokens)
      ├── 14.exe
      ├── 15.cpp (100 tokens)
      ├── 15.exe
      ├── 16.cpp (100 tokens)
      ├── 16.exe
      ├── 17.cpp (100 tokens)
      ├── 17.exe
      ├── 18.cpp (100 tokens)
      ├── 18.exe
      ├── 19.cpp (200 tokens)
      ├── 19.exe
      ├── 2.cpp (100 tokens)
      ├── 2.exe
      ├── 20.cpp (200 tokens)
      ├── 20.exe
      ├── 21.cpp (100 tokens)
      ├── 21.exe
      ├── 22.cpp (100 tokens)
      ├── 22.exe
      ├── 3.cpp (100 tokens)
      ├── 3.exe
      ├── 4.cpp (100 tokens)
      ├── 5.cpp (100 tokens)
      ├── 6.cpp (100 tokens)
      ├── 6.exe
      ├── 7.cpp (100 tokens)
      ├── 7.exe
      ├── 8.cpp (100 tokens)
      ├── 8.exe
      ├── 9.cpp (100 tokens)
      ├── 9.exe
      ├── experimental.cpp (400 tokens)
      ├── experimental.exe
   ├── PizzaWith3nSlices.cpp (600 tokens)
   ├── Prims algo.cpp (200 tokens)
   ├── Prims algo.spp (200 tokens)
   ├── Product of Array Except Self.cpp (100 tokens)
   ├── Psudocode/
      ├── first.cpp
      ├── second.cpp
      ├── second.exe
      ├── third.cpp (100 tokens)
      ├── third.exe
      ├── tut4.cpp
      ├── tut4.exe
   ├── Queue Sort (Ascending Order) (300 tokens)
   ├── Queue_example travel agency.cpp (500 tokens)
   ├── Queues/
      ├── 01Arrayimplementationofqueue.cpp (200 tokens)
      ├── 02vectorImplementationofqueue.cpp (200 tokens)
      ├── 03DesignaDeque.cpp (500 tokens)
      ├── 04DequeSTL.cpp (100 tokens)
      ├── 05DesignCircularQueueLeetcode-622.cpp (400 tokens)
      ├── 06ReversefirstKelementsofaQueue.cpp (100 tokens)
      ├── 07NumberofStudentsUnabletoeatLunch_LC-1700.cpp (400 tokens)
      ├── 08ImplementQueueusingStacks_Leetcode-232.cpp (500 tokens)
      ├── 09RevealCardsinIncreasingOrderLeetcode-950.cpp (200 tokens)
   ├── Quick-Sortt.cpp (200 tokens)
   ├── Rat in a Maze.cpp (300 tokens)
   ├── Reverse Linked List.cpp (200 tokens)
   ├── Reverse_words_in_string.cpp (200 tokens)
   ├── Rotate-String.cpp (300 tokens)
   ├── STLusage.cpp
   ├── Segment Tree/
      ├── Dynamic Range Sum Queries
      ├── Seg.cpp (300 tokens)
      ├── segment-tree-lazy-propogation.cpp (700 tokens)
      ├── segment-tree.cpp (400 tokens)
      ├── segment-tree2D.cpp (800 tokens)
   ├── SegmentTreeLazyPropagation.cpp (2.2k tokens)
   ├── Selection Sort.cpp (200 tokens)
   ├── Simple-Calculator.cpp (200 tokens)
   ├── Smallest Missing Multiple of K/
      ├── Smallest Missing Multiple of K.c++ (100 tokens)
   ├── SmallestNodeAtEachLevelInBinaryTree.cpp (600 tokens)
   ├── SortArray.cpp (200 tokens)
   ├── Square_Root_Decomposition.cpp (200 tokens)
   ├── Stack/
      ├── 01stackprint.cpp (100 tokens)
      ├── 02reversestack.cpp (300 tokens)
      ├── 03ArrayImplementationof_Stack.cpp (200 tokens)
      ├── 04LinkeoListImplementation.cpp (200 tokens)
      ├── 05RemoveConsecutiveDuplicatesinastring.cpp (100 tokens)
      ├── 06Nextgreaterelement.cpp (200 tokens)
      ├── 07Previousgreaterelement.cpp (100 tokens)
      ├── 08Stock_Span_problem.cpp (100 tokens)
      ├── 09infix_string_calculation.cpp (300 tokens)
      ├── 10infix_string_calculationwithBracket.cpp (400 tokens)
      ├── 11InfixtoPrefixConversion.cpp (400 tokens)
      ├── 12InfixtoPostfixConversion.cpp (400 tokens)
      ├── 13PostfixEvaluation.cpp (200 tokens)
      ├── 14PostfixtoInfixConversion.cpp (100 tokens)
      ├── 15PostfixtoPREFIXConversion.cpp (200 tokens)
      ├── 16PrefixEvaluation.cpp (200 tokens)
      ├── 17PrefixtoInfixConversion.cpp (200 tokens)
      ├── 18PrefixtoPostfixConversion.cpp (200 tokens)
   ├── StringtoInteger(atoi).cpp (200 tokens)
   ├── SudokuSolver.cpp (300 tokens)
   ├── Suffix-automation-cpp.cpp (300 tokens)
   ├── SuffixArrayLCP.cpp (2.4k tokens)
   ├── Sum_of_all_subset_XOR_total.cpp (100 tokens)
   ├── Swim_in_Rising_Water.cpp (300 tokens)
   ├── TarjanSCC.cpp (1900 tokens)
   ├── ThreeSum.cpp (700 tokens)
   ├── Trappingrainwater.cpp (100 tokens)
   ├── Two Sum.cpp (100 tokens)
   ├── Two-pointer/
      ├── LongestPalindromingSring.cpp (400 tokens)
      ├── containerwithmostwater.cpp (100 tokens)
      ├── two_pointer_ex1.cpp (100 tokens)
      ├── validpalindrome.cpp (200 tokens)
   ├── Twosum.cpp
   ├── UglyNumber.cpp (100 tokens)
   ├── Ultimate_Value.cpp (200 tokens)
   ├── Valid Parentheses.cpp (100 tokens)
   ├── ValidParenthese.cpp (100 tokens)
   ├── Water Bottles (400 tokens)
   ├── a_star.cpp (300 tokens)
   ├── aggressive_cows.cpp (400 tokens)
   ├── allSTL/
      ├── List.cpp
      ├── Queue.cpp (100 tokens)
      ├── Stack.cpp (100 tokens)
      ├── Vector.cpp (300 tokens)
      ├── pair.cpp (100 tokens)
   ├── array.cpp
   ├── asteroidCollision.cpp (300 tokens)
   ├── avoidFloodInTheCity.cpp (100 tokens)
   ├── bfs.cpp (200 tokens)
   ├── binSearch.cpp (300 tokens)
   ├── binary (100 tokens)
   ├── binary-search-tree-insertion.cpp (900 tokens)
   ├── binary_tree.cpp (200 tokens)
   ├── bit_manipulations_trick.cpp (300 tokens)
   ├── bitwise_operators_explained.cpp (500 tokens)
   ├── book_allocation.cpp (500 tokens)
   ├── bubble (100 tokens)
   ├── bubblesort.cpp (100 tokens)
   ├── calculator.cpp (100 tokens)
   ├── cf1051a.cpp (100 tokens)
   ├── cf1051bDiscounts.cpp (100 tokens)
   ├── cf_2149c.cpp (1000 tokens)
   ├── charTriangle.cpp (100 tokens)
   ├── checkprime
   ├── checkprime.cpp (100 tokens)
   ├── clearBit.java (100 tokens)
   ├── climbing_stairs.cpp (100 tokens)
   ├── codeforcesdiv.2.cpp
   ├── codeforcesdiv.2q2.cpp
   ├── codestudio_reverse-the-array_1262298.cpp (100 tokens)
   ├── coin_change.cpp (100 tokens)
   ├── combinationSum.cpp (200 tokens)
   ├── convex_hull.cpp (200 tokens)
   ├── count_factors.cpp (100 tokens)
   ├── cyclicArrayRotation.cpp (200 tokens)
   ├── dfs.cpp (200 tokens)
   ├── disjoint_set.cpp (200 tokens)
   ├── dsu_rollback.cpp (200 tokens)
   ├── fenwick_tree.cpp (200 tokens)
   ├── fibonacciseries (100 tokens)
   ├── findMedianSortedArrays.cpp (300 tokens)
   ├── findduplicates.cpp (200 tokens)
   ├── first_and_last_occurence.cpp (300 tokens)
   ├── first_and_last_occurrence.cpp (300 tokens)
   ├── first_last_position.cpp (200 tokens)
   ├── friendfunction.cpp (100 tokens)
   ├── gcd (100 tokens)
   ├── gcd.cpp (100 tokens)
   ├── hashmap/
      ├── Subarray.c++ (200 tokens)
   ├── helloworld.cpp (200 tokens)
   ├── hopcroft_karp.cpp (300 tokens)
   ├── house_robber.cpp (200 tokens)
   ├── implicit_treap.cpp (400 tokens)
   ├── insertion (100 tokens)
   ├── isPalindrome.cpp (100 tokens)
   ├── jump_game2.cpp (100 tokens)
   ├── kadane_extended_circular_indices.cpp (500 tokens)
   ├── kmp.cpp (300 tokens)
   ├── kmp_search.cpp (200 tokens)
   ├── knapsack_01_dp_space_opt.cpp (300 tokens)
   ├── kruskal_mst_dsu.cpp (400 tokens)
   ├── kthMaxMinElement.cpp (400 tokens)
   ├── largestSumSubarray.cpp (300 tokens)
   ├── larry'sArray.cpp (100 tokens)
   ├── lcs.cpp (100 tokens)
   ├── leetcodeQ788/
      ├── RotatedDigits.cpp (300 tokens)
   ├── leetcodeSahil/
      ├── 3sum.cpp (200 tokens)
      ├── Search_in_Rotated_Sorted_Array.cpp (200 tokens)
      ├── container_with_mostWater.cpp (100 tokens)
   ├── linear (100 tokens)
   ├── linked-list.cpp (900 tokens)
   ├── linkedlist_basics.cpp (200 tokens)
   ├── linkedlist_detect_cycle.cpp (200 tokens)
   ├── linkedlist_reverse.cpp (200 tokens)
   ├── lockfree_queue.cpp (400 tokens)
   ├── longest_balanced_substring.cpp (200 tokens)
   ├── longest_consecutive_sequence.cpp (200 tokens)
   ├── longest_palindromic_substring.cpp
   ├── lru-cache.cpp (300 tokens)
   ├── manacher.cpp (300 tokens)
   ├── matrix_multiplication.cpp (200 tokens)
   ├── maxSlidingWindow.cpp (200 tokens)
   ├── max_subarray_sum.cpp (100 tokens)
   ├── medianOfTwoSortedArrays.cpp
   ├── median_of_two_sorted_arrays.cpp (400 tokens)
   ├── merge_K_sorted_lists.cpp (400 tokens)
   ├── merge_sort.cpp (200 tokens)
   ├── min_path_sum.cpp (200 tokens)
   ├── minimumEffortPath.cpp (300 tokens)
   ├── minimum_operation_to_make_array_zero.cpp (500 tokens)
   ├── modular_exponentiation.cpp (100 tokens)
   ├── move-zeros.cpp (100 tokens)
   ├── nCrProblem.cpp (100 tokens)
   ├── next permutation.cpp (300 tokens)
   ├── nqueen.cpp (400 tokens)
   ├── output/
      ├── Twosum.exe
      ├── bfs.exe
      ├── dfs.exe
   ├── painter_partition.cpp (300 tokens)
   ├── palindrome_check.cpp (100 tokens)
   ├── pattern.cpp (100 tokens)
   ├── persistent_segment_tree.cpp (400 tokens)
   ├── power_function.cpp
   ├── prefix_sum_3d_array.cpp (400 tokens)
   ├── primeNumber.cpp (100 tokens)
   ├── print_butterfly.cpp (300 tokens)
   ├── ram_setu_bridge_protocol.cpp (400 tokens)
   ├── recursion/
      ├── NQueenPlaceProblemCPP (600 tokens)
      ├── backtrack.cpp (100 tokens)
      ├── backtrack.exe
      ├── check_palindrome.cpp (300 tokens)
      ├── fibo.cpp
      ├── fibo.exe
      ├── frog_jump.cpp (500 tokens)
      ├── functionaal.cpp
      ├── functionaal.exe
      ├── greatest_common_factor.cpp (300 tokens)
      ├── max_arr_num.cpp (100 tokens)
      ├── names.cpp
      ├── names.exe
      ├── palin.cpp (100 tokens)
      ├── palin.exe
      ├── palin1.cpp (100 tokens)
      ├── palin1.exe
      ├── parametrizes.cpp (100 tokens)
      ├── parametrizes.exe
      ├── permutation.cpp (200 tokens)
      ├── printdes.cpp (100 tokens)
      ├── printdes.exe
      ├── printlinear.cpp (100 tokens)
      ├── printlinear.exe
      ├── remove_char.cpp (100 tokens)
      ├── revarr.cpp (100 tokens)
      ├── revarr.exe
      ├── revarr1.cpp (100 tokens)
      ├── revarr1.exe
      ├── subsets.cpp (200 tokens)
      ├── subsets2.cpp (200 tokens)
   ├── regular_expression.cpp (100 tokens)
   ├── relative-ranks.cpp (200 tokens)
   ├── remove-duplicates.cpp (200 tokens)
   ├── reverseInteger.cpp
   ├── reverseString.cpp (100 tokens)
   ├── reverseastring.cpp (100 tokens)
   ├── reversed_linked_list.cpp (100 tokens)
   ├── search_in_rotated_sorted_array.cpp (500 tokens)
   ├── search_in_sorted_array.cpp (300 tokens)
   ├── segment_tree_lazy.cpp (700 tokens)
   ├── sel sort.cpp (100 tokens)
   ├── selection (100 tokens)
   ├── selection_sort.cpp (100 tokens)
   ├── skyline_problem.cpp (200 tokens)
   ├── sorting/
      ├── HeapSort.cpp (200 tokens)
      ├── InsertionSort.cpp (100 tokens)
      ├── InsertionSortCPP (200 tokens)
      ├── Selection sort.cpp (200 tokens)
      ├── bubble_sort.cpp (100 tokens)
      ├── merge_sort.cpp (200 tokens)
      ├── quick_sort.c (100 tokens)
      ├── quick_sort.cpp (200 tokens)
      ├── radixsort (300 tokens)
   ├── splitarray.cpp (200 tokens)
   ├── square_root.cpp (200 tokens)
   ├── square_root_binary_search.cpp (100 tokens)
   ├── squares_of_sorted_array.cpp (200 tokens)
   ├── stringalgo.cpp
   ├── strings/
      ├── check_if_2_strings_Are_anagram.cpp (100 tokens)
      ├── check_if_string_is_palindrome.cpp (100 tokens)
      ├── fine_first_non_repeating_character.cpp (100 tokens)
      ├── longest_substring_without_repeating_characters.cpp (100 tokens)
      ├── reverse_words_in_a_sentence.cpp (100 tokens)
   ├── successful_pair.cpp (200 tokens)
   ├── sudoku.cpp (3.6k tokens)
   ├── suffix_automaton.cpp (300 tokens)
   ├── sum_of_1d_array.cpp (100 tokens)
   ├── tarjan-articulation.cpp (500 tokens)
   ├── ternary_search.cpp (100 tokens)
   ├── topological_sort_kahn_and_dfs.cpp (500 tokens)
   ├── trinetra_algorithm.cpp (500 tokens)
   ├── tut2.cpp
   ├── tut3.cpp (100 tokens)
   ├── tut4.cpp (100 tokens)
   ├── tut5.cpp
   ├── tut6.cpp (100 tokens)
   ├── tut7.cpp (200 tokens)
   ├── tut8.cpp
   ├── tut8.exe
   ├── two_sum.cpp (100 tokens)
   ├── unionIntersectionOf2Arrays.cpp (600 tokens)
   ├── validPalindrome.cpp (200 tokens)
   ├── valid_palindrome.cpp (200 tokens)
   ├── valid_parenthesis.cpp (200 tokens)
   ├── water_bottle.cpp (100 tokens)
├── countEvenOdd.java (100 tokens)
├── cpp/
   ├── cpp/
      ├── dsu/
         ├── dsu.hpp (300 tokens)
├── desktop.ini
├── dsa-code.iml (100 tokens)
├── go/
   ├── A_star.go (500 tokens)
   ├── BFS_algorithm.go (200 tokens)
   ├── Bellman_ford_algorithm.go (300 tokens)
   ├── Bitmask_DP (200 tokens)
   ├── Bubble_sort.go (100 tokens)
   ├── DFS_algorithm.go (100 tokens)
   ├── Floyds_cycle_detection.go (100 tokens)
   ├── IntroSort.go (800 tokens)
   ├── K_frequent_elements.go (200 tokens)
   ├── Linear Search.go (200 tokens)
   ├── Strings.go (100 tokens)
   ├── SuffixArray.go (400 tokens)
   ├── Tarjan_algoritm.go (300 tokens)
   ├── binary_search.go (100 tokens)
   ├── binary_tree_height.go (200 tokens)
   ├── binary_tree_levelorder.go (200 tokens)
   ├── binary_tree_traversal.go (500 tokens)
   ├── counting_sort.go (200 tokens)
   ├── dijkstra_algorithm.go (400 tokens)
   ├── floyd_warshall_algorithm.go (300 tokens)
   ├── greedy_algorithm (200 tokens)
   ├── hello.go
   ├── intro_sort.go (400 tokens)
   ├── kadane_algo.go (100 tokens)
   ├── kadane_algorithm.go (100 tokens)
   ├── kmp_algo.go (200 tokens)
   ├── kruskal_algorithm.go (400 tokens)
   ├── largest_altitude.go (100 tokens)
   ├── longest_substring.go (100 tokens)
   ├── main.go (500 tokens)
   ├── merge_sort.go (200 tokens)
   ├── prims_algorithm.go (300 tokens)
   ├── queue.go (200 tokens)
   ├── quick_sort.go (100 tokens)
├── html/
   ├── Avengers_website_basic.html (4.8k tokens)
   ├── Forms_All_input_types.html (1200 tokens)
   ├── HappyBday.html (2.9k tokens)
   ├── RandomColourGenerator.html (200 tokens)
   ├── RandomQuoteGeneratoor.html (200 tokens)
   ├── RandomQuoteGenerator.html (200 tokens)
   ├── Valentine_project.html (600 tokens)
   ├── ageCalculator.html (3.3k tokens)
   ├── calculator.html (600 tokens)
   ├── catchFallingObject.html (300 tokens)
   ├── catch_the_ball.html (800 tokens)
   ├── counter.html (400 tokens)
   ├── digital_greeting_card.html (1200 tokens)
   ├── max-xor-trie.html (1100 tokens)
   ├── numberguess.html (1600 tokens)
   ├── quizgame.html (1300 tokens)
   ├── simplefarminggmae.html (1300 tokens)
   ├── simplemanufacturingame.html (1800 tokens)
   ├── stack-visualizer.html (3.8k tokens)
   ├── taskManager.html (500 tokens)
   ├── tiktaktoe.html (1800 tokens)
   ├── to_do_list.html (3.7k tokens)
├── ins code (100 tokens)
├── iterative_traversals.py
├── java/
   ├── .DS_Store
   ├── .idea/
      ├── .gitignore
      ├── misc.xml (100 tokens)
      ├── modules.xml (100 tokens)
      ├── vcs.xml
   ├── 0295-find-median-from-data-stream.java (100 tokens)
   ├── 0345-reverse-vowels-of-a-string.java (100 tokens)
   ├── 0380-insert-delete-getrandom-o1.java (200 tokens)
   ├── 1518-Water-Bottles/
      ├── README.md (300 tokens)
      ├── water-bottles.java (100 tokens)
   ├── 2273. Find Resultant Array After Removing Anagrams (200 tokens)
   ├── 2D Array/
      ├── MatrixMultiplication.java (300 tokens)
      ├── Matrix_ColSort.java (300 tokens)
      ├── Matrix_FullSort.java (400 tokens)
      ├── Matrix_RowSort.java (300 tokens)
      ├── SaddlePoint.java (300 tokens)
      ├── SpiralMatrix.java (700 tokens)
      ├── TwoDArraySearch.java (500 tokens)
   ├── 2D-Array/
      ├── RatInMaze.java (500 tokens)
      ├── SpiralMatrix.java (300 tokens)
      ├── TwoDArraySearch.class
      ├── TwoDArraySearch.java (300 tokens)
   ├── 407-traping-rain-water-ii/
      ├── README.md (300 tokens)
      ├── traping-rain-water-ii.java (300 tokens)
   ├── 42-trapping-rain-water/
      ├── README.md (200 tokens)
      ├── trapping-rain-water.java (1300 tokens)
   ├── 778-swim-in-rising-water/
      ├── README.md (500 tokens)
      ├── swim-in-rising-water.java (200 tokens)
   ├── AVLTree.java (900 tokens)
   ├── Account.class
   ├── AllLeadersInTheArray.java (300 tokens)
   ├── AllPathToSource.java (200 tokens)
   ├── AnagramChecker.java (1300 tokens)
   ├── Anagrams.java (200 tokens)
   ├── AreaCalculator.class
   ├── AreaCalculator.java (400 tokens)
   ├── ArmstrongNumberCheck.class
   ├── ArmstrongNumberCheck.java (100 tokens)
   ├── ArrayListDemo.java (100 tokens)
   ├── ArrayOperations.java (400 tokens)
   ├── ArrayPythagorasTriplet.java (200 tokens)
   ├── ArrayUtils.java (300 tokens)
   ├── ArrayUtilsTest.java (300 tokens)
   ├── Arrays/
      ├── Apple_Price.java (400 tokens)
      ├── LongestSubseqwithXOR.java (200 tokens)
      ├── Longest_Consecutive_Sequence_in_an_Array.java (300 tokens)
      ├── MaximumSubarray.java (100 tokens)
      ├── Median_of_Two_Sorted_Arrays.java (300 tokens)
      ├── Min_Product_SubArray.java (100 tokens)
      ├── MoveZeroes.java (100 tokens)
      ├── RearrangeArray.java (200 tokens)
      ├── SortColors.java (100 tokens)
      ├── ThreeeeSum.java (200 tokens)
      ├── TransposeMatrix.java (300 tokens)
      ├── TriangularSumArray.java (100 tokens)
      ├── TwoSum.java (100 tokens)
   ├── BFS.class
   ├── BFS.java (500 tokens)
   ├── BSTDemo.java (900 tokens)
   ├── BackTracking/
      ├── Arrays.class
      ├── Arrays.java (200 tokens)
      ├── FindSubsets.class
      ├── FindSubsets.java (200 tokens)
      ├── GridWays.class
      ├── GridWays.java (100 tokens)
      ├── Permutation.class
      ├── Permutation.java (200 tokens)
      ├── nQueen.class
      ├── nQueen.java (400 tokens)
      ├── nQueen_OneSolution.class
      ├── nQueen_OneSolution.java (500 tokens)
   ├── Bank.class
   ├── BankManagementSystem.class
   ├── BankManagementSystem.java (800 tokens)
   ├── BestTimeToBuySellStock.java (400 tokens)
   ├── BestTimetoBuyandSellStock.java (100 tokens)
   ├── Best_Time_To_Buy_And_Sell_Stocks.java (100 tokens)
   ├── BinarySearchTree$Node.class
   ├── BinarySearchTree.class
   ├── BinarySearchTree.java (500 tokens)
   ├── BinarySearchTreeTest.java (100 tokens)
   ├── BinaryTree$Node.class
   ├── BinaryTree$Pair.class
   ├── BinaryTree.class
   ├── BinaryTree.java (3k tokens)
   ├── BinaryTreeDemo.java (1000 tokens)
   ├── BinaryTreeLevelOrderTraversal.java (300 tokens)
   ├── BubbleSort.java
   ├── BuyAndSellStock2Onwards/
      ├── BestTimeToBuyAndSellStockWithCooldown.java (600 tokens)
      ├── BestTimeToBuyAndSellStockWithTransactionFee.java (600 tokens)
      ├── BuyAndSellStock2.java (600 tokens)
      ├── BuyAndSellStock3.java (500 tokens)
      ├── BuyAndSellStock4.java (500 tokens)
      ├── QuestionLinks (100 tokens)
   ├── Chatbot.class
   ├── Chatbot.java (300 tokens)
   ├── CircularArrayjava.java (100 tokens)
   ├── Circular_array.java (100 tokens)
   ├── ClimbingStairs.java (100 tokens)
   ├── ContainerWithMostWater.java (100 tokens)
   ├── CountSubArrays2962.java (200 tokens)
   ├── CountVowels.java (100 tokens)
   ├── CurrentAccount.class
   ├── Customer.class
   ├── DFS.java (500 tokens)
   ├── DP(Lavi)/
      ├── 01Knapsack.java (300 tokens)
   ├── DecodetheMessage.java (400 tokens)
   ├── DeleteMiddleNode.java (300 tokens)
   ├── DeleteMiddleStack.java (300 tokens)
   ├── DetectCycle.class
   ├── DetectCycle.java (200 tokens)
   ├── DetectCycleInDirectedGraph.class
   ├── DetectCycleInDirectedGraph.java (300 tokens)
   ├── DijkstraAlgorithm$Node.class
   ├── DijkstraAlgorithm.class
   ├── DijkstraAlgorithm.java (500 tokens)
   ├── DisjointSet.java (400 tokens)
   ├── DivideAndConquer/
      ├── MergeSort.class
      ├── MergeSort.java (300 tokens)
      ├── QuickSort.class
      ├── QuickSort.java (300 tokens)
      ├── SortedAndRotatedArray.class
      ├── SortedAndRotatedArray.java (200 tokens)
      ├── SortedAndRotatedArray_Iteration.class
      ├── SortedAndRotatedArray_Iteration.java (200 tokens)
      ├── tempCodeRunnerFile.java
   ├── Driver.java (800 tokens)
   ├── EditDistance.java (200 tokens)
   ├── ExpressionAddOperator.java (900 tokens)
   ├── Factorial.java (100 tokens)
   ├── FactorialExample.class
   ├── FactorialExample.java (100 tokens)
   ├── Fibonacci.java (100 tokens)
   ├── Find Missing Number.java (100 tokens)
   ├── FindMiddleNode.java (200 tokens)
   ├── FloydCycleDetectionLinkedList.java (200 tokens)
   ├── FourSum.java (400 tokens)
   ├── GenerateParentheses.java (300 tokens)
   ├── GreedyAlgorithm/
      ├── ActivitySelection.class
      ├── ActivitySelection.java (500 tokens)
      ├── FractionalKnapSack.class
      ├── FractionalKnapSack.java (200 tokens)
      ├── IndianCoins.class
      ├── IndianCoins.java (200 tokens)
      ├── JobSequencingProblem$Job.class
      ├── JobSequencingProblem.class
      ├── JobSequencingProblem.java (300 tokens)
      ├── MaxLengthChainOfPairs.class
      ├── MaxLengthChainOfPairs.java (200 tokens)
      ├── MinSumAbsoluteDiffPairs.class
      ├── MinSumAbsoluteDiffPairs.java (100 tokens)
   ├── HappyNumber.java (100 tokens)
   ├── HashMap/
      ├── .DS_Store
      ├── Anagram.java (300 tokens)
      ├── Frequency.java (200 tokens)
      ├── Isomorphic.java (200 tokens)
   ├── HashMapDemo.java (200 tokens)
   ├── HashSetDemo.java (100 tokens)
   ├── HeapSort.class
   ├── HeapSort.java (400 tokens)
   ├── Hello.java
   ├── HouseRobber II.java (300 tokens)
   ├── HouseRobber.java (200 tokens)
   ├── HouseRobber/
      ├── houseRobber1.java (500 tokens)
      ├── houseRobber2.java (600 tokens)
   ├── Implement_Trie_(Prefix__Tree).java (300 tokens)
   ├── InsertionSort.java (100 tokens)
   ├── JDBCEx.java (200 tokens)
   ├── JumpGame.java (200 tokens)
   ├── JumpGame1.java (100 tokens)
   ├── JumpGame2.java
   ├── KMPStringSearch.java (300 tokens)
   ├── K_closest_points_to_origin.java (200 tokens)
   ├── Kadanes.java (100 tokens)
   ├── KaprekarNumber.java (200 tokens)
   ├── Koko_Eating_Bananas.java (300 tokens)
   ├── KthLargestElement.java (300 tokens)
   ├── LRUCache$Node.class
   ├── LRUCache.class
   ├── LRUCache.java (800 tokens)
   ├── LargestSubarraySum.java (100 tokens)
   ├── Largest_Rectangle_in_Histogram.java (200 tokens)
   ├── LeadersInArr.class
   ├── LeadersInArr.java (100 tokens)
   ├── Leetcode Solutions/
      ├── 1-two-sum/
         ├── README.md (300 tokens)
         ├── two-sum.java (100 tokens)
      ├── 51-n-queens/
         ├── README.md (300 tokens)
         ├── n-queens.java (700 tokens)
      ├── 69-sqrtx/
         ├── README.md (200 tokens)
         ├── sqrtx.java (100 tokens)
      ├── 7-reverse-integer/
         ├── README.md (200 tokens)
         ├── reverse-integer.java (100 tokens)
      ├── 74-search-a-2d-matrix/
         ├── README.md (300 tokens)
         ├── search-a-2d-matrix.java (100 tokens)
   ├── Leetcode25.class
   ├── Leetcode25.java (400 tokens)
   ├── Levenshtein_distance/
      ├── ReadMe.md (300 tokens)
      ├── edit_distance.java (800 tokens)
   ├── Lexicographically Smallest String After Applying Operations (Java) (300 tokens)
   ├── LinkCutTree.java (1000 tokens)
   ├── LinkedListCycleDetection.java (400 tokens)
   ├── ListNode.class
   ├── Longest Palindromic Subseuence.java (100 tokens)
   ├── LongestCommonPrefix.java (200 tokens)
   ├── LongestCommonSubsequence.java (600 tokens)
   ├── LongestIncreasingSubsequence.java (100 tokens)
   ├── LongestPalindromicSubsequence.java (600 tokens)
   ├── LongestSubstring.class
   ├── LongestSubstring.java (100 tokens)
   ├── Longest_substring_with_distinct_characters.java (200 tokens)
   ├── Main.java (500 tokens)
   ├── MajorityFrequencyCharacters.java (200 tokens)
   ├── MajorityNumber.java (200 tokens)
   ├── MajorityVoting.java (200 tokens)
   ├── Majority_element.java (100 tokens)
   ├── MathUtils.java (100 tokens)
   ├── MathUtilsTest.java (100 tokens)
   ├── Maximum Product Subarray.java (200 tokens)
   ├── MaximumSubarray.java (300 tokens)
   ├── MaximumSubarraySum.java (500 tokens)
   ├── Median of two sorted array.java (200 tokens)
   ├── MergeIntervals.java (100 tokens)
   ├── Merge_K_Sortedlists.java (2000 tokens)
   ├── MergerSort.java (300 tokens)
   ├── MinimumWindowSubstring.java (500 tokens)
   ├── MissingNumber.java (600 tokens)
   ├── MoveAllZeroestoEnd.java (100 tokens)
   ├── MoveZeros copy.java (100 tokens)
   ├── MultiplicationTable.class
   ├── MultiplicationTable.java (100 tokens)
   ├── N-Queens.java (300 tokens)
   ├── NQueens.java (400 tokens)
   ├── NQueens2.java (300 tokens)
   ├── Neon_Number.java (200 tokens)
   ├── NextGreaterElement.class
   ├── NextGreaterElement.java (200 tokens)
   ├── NextSmallerElement.java (100 tokens)
   ├── NonOverlappingIntervals.java (100 tokens)
   ├── OnlineExamSystem.java (600 tokens)
   ├── Palindrome.java (100 tokens)
   ├── PalindromeCheck.class
   ├── PalindromeCheck.java (100 tokens)
   ├── PalindromeNumber.java (100 tokens)
   ├── PascalTriangle.java (100 tokens)
   ├── PasswordSuperStrengthChecker.java (500 tokens)
   ├── PellNumber.java (200 tokens)
   ├── Permutation.java (200 tokens)
   ├── Permutations.java (100 tokens)
   ├── Postorder_Traversal_on_tree.java (100 tokens)
   ├── Prime.java (100 tokens)
   ├── PrintingSpiral.java (400 tokens)
   ├── ProductOfArrayExceptSelf.java (100 tokens)
   ├── QueueDemo.java (100 tokens)
   ├── QuickSort.java (600 tokens)
   ├── Recursion(Lavi)/
      ├── ConvertStringToInteger.class
      ├── ConvertStringToInteger.java (600 tokens)
      ├── CountPaths.class
      ├── CountPaths.java (300 tokens)
      ├── GenerateParenthesis.class
      ├── GenerateParenthesis.java (300 tokens)
      ├── HumanPyramid.class
      ├── HumanPyramid.java (800 tokens)
      ├── NQueens.class
      ├── NQueens.java (400 tokens)
      ├── SearchMatrix.class
      ├── SearchMatrix.java (400 tokens)
      ├── SubSequences.class
      ├── SubSequences.java (500 tokens)
      ├── ValidParenthesis.class
      ├── ValidParenthesis.java (400 tokens)
      ├── checkstyle-11.0.0-all.jar
   ├── RestoreFinishingOrder.java (200 tokens)
   ├── Reverse a Linked List.java (200 tokens)
   ├── ReverseArray.java (100 tokens)
   ├── ReverseInteger.java (300 tokens)
   ├── Reverse_string.java (100 tokens)
   ├── RotateImg.java (300 tokens)
   ├── Rotate_Image.class
   ├── Rotate_array.java (300 tokens)
   ├── RowColumnSearchInMatrix.java (200 tokens)
   ├── SavingsAccount.class
   ├── SearchInStrings.java (300 tokens)
   ├── SelectionSort.java (100 tokens)
   ├── Shotestpath.java (300 tokens)
   ├── SieveofEratosthenes.java (100 tokens)
   ├── Sliding_Window_Maximum.java (200 tokens)
   ├── Solution.class
   ├── Sort0S_1S_2S.java (300 tokens)
   ├── SortArrayList.class
   ├── SortArrayList.java (300 tokens)
   ├── SortArrayListint.java (200 tokens)
   ├── Sort_Ascending_Order.java (200 tokens)
   ├── Sorting/
      ├── BinarySearch.java (200 tokens)
      ├── BubbleSort.java (100 tokens)
      ├── BuiltInSort.java
      ├── CyclicSort.class
      ├── CyclicSort.java (100 tokens)
      ├── InsertionSort.java (100 tokens)
      ├── MergeSort.java (200 tokens)
      ├── QuickSort.java (200 tokens)
      ├── SelectionSort.java (100 tokens)
      ├── heapSort.class
      ├── nextGreatestLetter.java (200 tokens)
   ├── Spiral Matrix.java (200 tokens)
   ├── SpiralMatrix.java (300 tokens)
   ├── SpiralMatrix2.java (200 tokens)
   ├── Spreadsheet.java (200 tokens)
   ├── Stack.class
   ├── Stack.java (300 tokens)
   ├── Stack/
      ├── NextGreaterElement.class
      ├── NextGreaterElement.java (200 tokens)
      ├── ValidParentheses.class
      ├── ValidParentheses.java (200 tokens)
   ├── Starpattern.java (100 tokens)
   ├── StreamDemo.java (400 tokens)
   ├── StringUtils.java (300 tokens)
   ├── StringUtilsTest.java (200 tokens)
   ├── Substring_without_Repeat.class
   ├── Substring_without_Repeat.java (200 tokens)
   ├── SuccessfulPairsOfSpellsAndPotions.java (100 tokens)
   ├── Sunny_Number.java (200 tokens)
   ├── SwappingNodesInLinkedList.java (200 tokens)
   ├── TappingRainWater.java (200 tokens)
   ├── TappingRainWaterII.java (300 tokens)
   ├── TarjanBridgesArticulation.java (900 tokens)
   ├── ThreeSum.java (200 tokens)
   ├── ThreeeeSum.java (200 tokens)
   ├── TopKFrequent.java (300 tokens)
   ├── TopologicalSort.java (300 tokens)
   ├── Tower_Of_Hanoi.java (300 tokens)
   ├── TransposeOfMatrix.java (300 tokens)
   ├── TrappingRainWater.java (100 tokens)
   ├── Trapping_Rain_Water_II.java (500 tokens)
   ├── TraverseSpirally.class
   ├── TraverseSpirally.java (200 tokens)
   ├── TwoPointer.java (200 tokens)
   ├── TwoSum.java (100 tokens)
   ├── TwoSum1.java (200 tokens)
   ├── TwoSumArray.java (200 tokens)
   ├── Two_sum.java (200 tokens)
   ├── UniquePaths.java (100 tokens)
   ├── UniquePaths2.java (200 tokens)
   ├── Valid Parentheses.java (100 tokens)
   ├── WaterBottles.java (100 tokens)
   ├── WaterBottlesII.java (200 tokens)
   ├── Waterbottles2.java (100 tokens)
   ├── WeatherClothingAdvisor.java (300 tokens)
   ├── WordPattern.java (300 tokens)
   ├── ash/
      ├── one.java (100 tokens)
      ├── three.java (100 tokens)
      ├── two.java (300 tokens)
   ├── bellman_ford.java (400 tokens)
   ├── bfsTraversal.java (300 tokens)
   ├── binarySearch.java (200 tokens)
   ├── characterReplacement.java (200 tokens)
   ├── clearBit.java (100 tokens)
   ├── countDigitOne.java (200 tokens)
   ├── dsa-code.iml (100 tokens)
   ├── dynamic_programming/
      ├── CoinChange.java (2.4k tokens)
      ├── FrogJump.class
      ├── FrogJump1.class
      ├── FrogJump1.java (400 tokens)
      ├── PaintHouse/
         ├── paintHouse1.java (800 tokens)
         ├── paintHouse2.java (700 tokens)
      ├── UniquePathsii.class
      ├── UniquePathsii.java (500 tokens)
      ├── smallestNumberOfNeighbour.class
      ├── smallestNumberOfNeighbour.java (500 tokens)
   ├── encapsulation.java (200 tokens)
   ├── factorial_number.class
   ├── factorial_number.java (100 tokens)
   ├── getBit.java (100 tokens)
   ├── isPowerOfTwo.java (100 tokens)
   ├── javac ExecutorServiceDemo.java (200 tokens)
   ├── largest.java (100 tokens)
   ├── leetcode.java (200 tokens)
   ├── leetcode_contest/
      ├── weekly_472/
         ├── q1.java (100 tokens)
   ├── linear.java (100 tokens)
   ├── linkedlistsum.java (300 tokens)
   ├── lowest_common_ancestor.java (300 tokens)
   ├── mergeSort.java
   ├── mergeSort1.java (700 tokens)
   ├── mergeTwoLists.java (600 tokens)
   ├── moveZeros.java (100 tokens)
   ├── movierenting.java (600 tokens)
   ├── numberguess.java (200 tokens)
   ├── oddReven.java (100 tokens)
   ├── out/
      ├── production/
         ├── dsa-code/
            ├── .idea/
               ├── .gitignore
               ├── misc.xml (100 tokens)
               ├── modules.xml (100 tokens)
               ├── vcs.xml
            ├── 1518-Water-Bottles/
               ├── README.md (300 tokens)
            ├── 407-traping-rain-water-ii/
               ├── README.md (300 tokens)
            ├── 42-trapping-rain-water/
               ├── README.md (200 tokens)
            ├── BuyAndSellStock2Onwards/
               ├── QuestionLinks (100 tokens)
            ├── Levenshtein_distance/
               ├── ReadMe.md (300 tokens)
            ├── dsa-code.iml (100 tokens)
   ├── primenumber.java (200 tokens)
   ├── rapRainWaterII.java (500 tokens)
   ├── rotateImage.java (300 tokens)
   ├── setBit.java (100 tokens)
   ├── string.java (100 tokens)
   ├── strings/
      ├── AnagramString.java (100 tokens)
      ├── FirstNonRepeatedChar.java (500 tokens)
      ├── KMPAlgorithm.java (400 tokens)
      ├── LongestUniqueSubstring.java (1600 tokens)
      ├── Longestpalindrome.java (300 tokens)
      ├── RabinKarp.java (300 tokens)
      ├── Reverse_words.java (100 tokens)
      ├── STRSTR.java (100 tokens)
      ├── StringReverse.java (200 tokens)
      ├── StringToInteger.java (200 tokens)
   ├── th3Sum.java (200 tokens)
   ├── topKelements.java (200 tokens)
   ├── trappingRainwater2.java (600 tokens)
   ├── unionByRank.java (300 tokens)
   ├── unionBySize.java (300 tokens)
   ├── uniqueNumOccurrences.java (200 tokens)
   ├── updateBit.java (200 tokens)
   ├── valid_sudoku.java (300 tokens)
   ├── wildcard.java (500 tokens)
├── javascript/
   ├── 75-Dsa-Problems/
      ├── remove-zeros-in-decimal-representation.js
   ├── A_star.js (500 tokens)
   ├── BinarySearch.js (200 tokens)
   ├── BinarySearchTree.js (1700 tokens)
   ├── BloomFilter.js (1300 tokens)
   ├── Bubblesort.js
   ├── ClimbingStairs.js
   ├── Container_with_most_water.js (100 tokens)
   ├── Fenwick.js (100 tokens)
   ├── LRUcache.js (1500 tokens)
   ├── MaximumSubarray.js (100 tokens)
   ├── Stack.js (2.5k tokens)
   ├── Trie.js (1900 tokens)
   ├── TwoSum.js (100 tokens)
   ├── ValidParentheses.js (100 tokens)
   ├── addno.js
   ├── ageCalculator.js (100 tokens)
   ├── arrayOfObjects.js (400 tokens)
   ├── async_await.js (100 tokens)
   ├── bfs.js (300 tokens)
   ├── calculator.js (700 tokens)
   ├── countdowntimer.js
   ├── developer-arnab/
      ├── README.md (200 tokens)
      ├── code.js (100 tokens)
   ├── dfs.js (300 tokens)
   ├── dijkstra.js (600 tokens)
   ├── disjoint_set_union.js (500 tokens)
   ├── evenoroddcheck.js
   ├── fibonnacci.js
   ├── findmax.js
   ├── githubUsernameValidator.js
   ├── graphs/
      ├── Numberofislands.js (200 tokens)
      ├── clonegraph.js (200 tokens)
      ├── maxareaofislands.js (300 tokens)
   ├── guess.js (200 tokens)
   ├── helloWorld.js
   ├── largenoinarray.js
   ├── largestNumber.js
   ├── lengthOfLongestSubstring.js (100 tokens)
   ├── longestValidParentheses.js (200 tokens)
   ├── maxProfit.js (100 tokens)
   ├── mergeSortAlgo.js (200 tokens)
   ├── mergeTwoLists.js (100 tokens)
   ├── nonzero.js (100 tokens)
   ├── oneDArray.js (300 tokens)
   ├── palindrome.js (100 tokens)
   ├── passwordChecker.js (100 tokens)
   ├── perfectSquare.js (200 tokens)
   ├── predecessor.js (200 tokens)
   ├── prime.js
   ├── productExceptSelf.js (100 tokens)
   ├── promises.js (200 tokens)
   ├── quickSort.js (100 tokens)
   ├── reverseString.js (100 tokens)
   ├── reverse_string.js
   ├── rhombusPattern.js (100 tokens)
   ├── singleNumber.js (100 tokens)
   ├── smallestNumber.js
   ├── spiral_matrix.js (400 tokens)
   ├── sum.js (300 tokens)
   ├── topKFrequent.js (100 tokens)
   ├── upperLeftTriangle.js
   ├── upperRightTriangle.js
   ├── warshallsAlgo.js (100 tokens)
   ├── zigzagpattern.js (100 tokens)
├── jspwTest.cpp
├── jspwTest.exe
├── kotlin/
   ├── BinarySearch.kt (100 tokens)
   ├── BubbleSort.kt (400 tokens)
   ├── Graph_BFS_DFS.kt (200 tokens)
   ├── HelloConfetti.kt (400 tokens)
   ├── IntroSort.kt (900 tokens)
   ├── LockFreeQueue.kt (200 tokens)
   ├── MergeSort.kt (500 tokens)
   ├── QuickSort.kt (100 tokens)
   ├── binary_search.kt (200 tokens)
   ├── counting_sort.kt (200 tokens)
   ├── ddays.kt (200 tokens)
   ├── helloworld.kt
   ├── linked_list.kt (300 tokens)
   ├── selection_sort.kt (200 tokens)
├── leetcode_778.cpp (600 tokens)
├── out/
   ├── production/
      ├── DSA-Project/
         ├── Main.class
         ├── Task.class
         ├── TodoList.class
├── pandas/
   ├── Average Salary of Each Department.py (100 tokens)
   ├── Customers Who Never Ordered.py (100 tokens)
   ├── Department Highest Salary.py (100 tokens)
   ├── Employees Earning More Than Their Managers.py (100 tokens)
   ├── Second Highest Salary.py
├── php/
   ├── LinearSearch.php (100 tokens)
   ├── TaskQueue.php (300 tokens)
   ├── WordSearch.php (300 tokens)
   ├── bellman_ford.php (200 tokens)
   ├── even.php (100 tokens)
   ├── fibonacci.php (100 tokens)
   ├── helloworld.php
   ├── kruskal's_algo.php (400 tokens)
   ├── palindrome.php
   ├── prime.php (200 tokens)
   ├── radix_sort.php (200 tokens)
├── python/
   ├── .cph/
      ├── .4Sum.py_81a46a9b4f1da7fec8a8af3a074ab705.prob (100 tokens)
   ├── 10_Regular_Expression_Matching.py (300 tokens)
   ├── 27_lc_remove_element.py (100 tokens)
   ├── 3Sum.py (200 tokens)
   ├── 3sumleetcode.py (200 tokens)
   ├── 4Sum.py (500 tokens)
   ├── ARRAY_twosum.py (100 tokens)
   ├── A_Skibidus_and_Amog_u.py
   ├── A_star.py (600 tokens)
   ├── Activity_Day.py (1100 tokens)
   ├── Ancient_Library.py (300 tokens)
   ├── AvoidFloodInTheCity.py (100 tokens)
   ├── Bellman-FordAlgorithm.py (300 tokens)
   ├── BestTimeToBuyandSellStock.py (100 tokens)
   ├── BinarySearch.py (100 tokens)
   ├── Binary_Search_Implementation.py (100 tokens)
   ├── Binary_tree_Paths.py (100 tokens)
   ├── Binarytreetraversal.py (100 tokens)
   ├── Circularqueue.py (300 tokens)
   ├── Coin_Change2.py
   ├── Container_With_Most_Water.py (100 tokens)
   ├── ContainsDuplicate.py
   ├── Custom HashMap.py (300 tokens)
   ├── DNA_Finder.py (500 tokens)
   ├── D_Fixed_Password.py
   ├── Dijikta's algo.py (100 tokens)
   ├── Dijkstra's_code.py (100 tokens)
   ├── Dijkstra’sAlgorithm.py (100 tokens)
   ├── Dijkstra’s_Algo.py (100 tokens)
   ├── Double_endedcircularqueue.py (1400 tokens)
   ├── Dsa-code.py (200 tokens)
   ├── Dynamic Programming patterns/
      ├── complex_pattern (300 tokens)
   ├── DynamicProgramming/
      ├── Climbing_Stairs/
         ├── 1_recursiveSolution.py (200 tokens)
         ├── 2_memmoization.py (200 tokens)
         ├── 3_tabulation.py (200 tokens)
         ├── 4_spaceOptimized.py (200 tokens)
         ├── readme.md (600 tokens)
      ├── CoinChange.py (300 tokens)
      ├── Frog_Jump/
         ├── 1_recursiveSolution.py (100 tokens)
         ├── 2_memoization.py (100 tokens)
         ├── 3_tabulation.py (100 tokens)
         ├── 4_space_optimized.py (100 tokens)
         ├── readme.md (200 tokens)
      ├── Knapsack01.py (400 tokens)
      ├── LongestCommonSubsequence.py (300 tokens)
      ├── LongestPalindromicSubsequence.py (200 tokens)
      ├── n_queens.py (300 tokens)
   ├── EmailValidation.py (100 tokens)
   ├── Expense_Tracker.py (800 tokens)
   ├── FileSystem_Organizer.py (700 tokens)
   ├── FindMinimumInRotatedSortedArray.py
   ├── Findtheminimumamountoftimetobrewpotions.py (100 tokens)
   ├── Graphs/
      ├── __init__.py
      ├── a_star.py (900 tokens)
      ├── ant_colony_optimization_algorithms.py (1600 tokens)
      ├── articulation_points.py (300 tokens)
      ├── basic_graphs.py (2.1k tokens)
      ├── bellman_ford.py (500 tokens)
      ├── bi_directional_dijkstra.py (700 tokens)
      ├── bidirectional_a_star.py (1600 tokens)
      ├── bidirectional_breadth_first_search.py (1200 tokens)
      ├── bidirectional_search.py (1100 tokens)
      ├── boruvka.py (1300 tokens)
      ├── breadth_first_search.py (500 tokens)
      ├── breadth_first_search_2.py (500 tokens)
      ├── breadth_first_search_shortest_path.py (600 tokens)
      ├── breadth_first_search_shortest_path_2.py (700 tokens)
      ├── breadth_first_search_zero_one_shortest_path.py (900 tokens)
      ├── check_bipatrite.py (1100 tokens)
      ├── check_cycle.py (300 tokens)
      ├── connected_components.py (300 tokens)
      ├── deep_clone_graph.py (300 tokens)
      ├── depth_first_search.py (300 tokens)
      ├── depth_first_search_2.py (700 tokens)
      ├── dijkstra.py (600 tokens)
      ├── dijkstra_2.py (300 tokens)
      ├── dijkstra_algorithm.py (2.9k tokens)
      ├── dijkstra_alternate.py (600 tokens)
      ├── dijkstra_binary_grid.py (600 tokens)
      ├── dinic.py (600 tokens)
      ├── directed_and_undirected_weighted_graph.py (3.1k tokens)
      ├── edmonds_karp_multiple_source_and_sink.py (1300 tokens)
      ├── eulerian_path_and_circuit_for_undirected_graph.py (400 tokens)
      ├── even_tree.py (300 tokens)
      ├── finding_bridges.py (600 tokens)
      ├── frequent_pattern_graph_miner.py (1500 tokens)
      ├── g_topological_sort.py (200 tokens)
      ├── gale_shapley_bigraph.py (400 tokens)
      ├── graph_adjacency_list.py (4.3k tokens)
      ├── graph_adjacency_matrix.py (4.4k tokens)
      ├── graph_list.py (1300 tokens)
      ├── graphs_floyd_warshall.py (600 tokens)
      ├── greedy_best_first.py (1100 tokens)
      ├── greedy_min_vertex_cover.py (500 tokens)
      ├── kahns_algorithm_long.py (200 tokens)
      ├── kahns_algorithm_topo.py (400 tokens)
      ├── karger.py (500 tokens)
      ├── lanczos_eigenvectors.py (1600 tokens)
      ├── markov_chain.py (400 tokens)
      ├── matching_min_vertex_cover.py (400 tokens)
      ├── minimum_path_sum.py (300 tokens)
      ├── minimum_spanning_tree_boruvka.py (1200 tokens)
      ├── minimum_spanning_tree_kruskal.py (300 tokens)
      ├── minimum_spanning_tree_kruskal2.py (800 tokens)
      ├── minimum_spanning_tree_prims.py (1000 tokens)
      ├── minimum_spanning_tree_prims2.py (1800 tokens)
      ├── multi_heuristic_astar.py (1700 tokens)
      ├── page_rank.py (300 tokens)
      ├── prim.py (700 tokens)
      ├── random_graph_generator.py (400 tokens)
      ├── scc_kosaraju.py (300 tokens)
      ├── strongly_connected_components.py (500 tokens)
      ├── tarjans_scc.py (700 tokens)
   ├── Graphs_BFS_Tranversal.py (100 tokens)
   ├── Greedy Algorithm/
      ├── Serialize-and-Deserialize-Binary-Tree.py (500 tokens)
      ├── Spiral-Matrix-II .py (400 tokens)
      ├── Symmetric-Tree.py (300 tokens)
      ├── assignCookies.py (500 tokens)
      ├── lemonadeChange.py (600 tokens)
      ├── rearranging_fruits.py (200 tokens)
   ├── Group_Anagrams.py (100 tokens)
   ├── Guess_the_number.py (100 tokens)
   ├── Histogram.py (200 tokens)
   ├── House_Robber.py (100 tokens)
   ├── LengthOfLastWord.py
   ├── LinearSearch.py (100 tokens)
   ├── LinkList_sum.py
   ├── Linked_list_insert.py (200 tokens)
   ├── Linked_list_insert_at_end.py (200 tokens)
   ├── Linked_list_insert_at_kth_index.py (400 tokens)
   ├── Linked_list_insert_at_start.py (100 tokens)
   ├── Linked_list_pop_first.py (300 tokens)
   ├── LongestPalindromicSubstring.py (100 tokens)
   ├── Longest_Common_Subsequence.py
   ├── Longest_Cons_Seq.py (200 tokens)
   ├── Longest_Increasing_Subsequence.py
   ├── Longeststringchain.py (100 tokens)
   ├── Maximum_Subarray_Sum.py (100 tokens)
   ├── Median_of_Two_Sorted_Arrays.py (700 tokens)
   ├── Middle of Single Linked List.py (100 tokens)
   ├── Middle_Element _of_LinkList.py (100 tokens)
   ├── Minimum_arrows_to_burst_ballons.py (200 tokens)
   ├── Missing_Number.py
   ├── MovieRecommendation.py (600 tokens)
   ├── N-Queens.py (200 tokens)
   ├── NumberOfIslands.py (100 tokens)
   ├── Palindrome_Check.py
   ├── Prime Number.py
   ├── ProductOfArrayExceptSelf.py (100 tokens)
   ├── Range_Sum_Queries.py (100 tokens)
   ├── RemoveDuplicate.py
   ├── Reverse_String.py
   ├── Reverse_of_Linklist.py (100 tokens)
   ├── STRING.py (100 tokens)
   ├── Save_People.py
   ├── Search in rotated array.py (100 tokens)
   ├── SearchInRotatedSortedArray.py
   ├── SetMatrixZeros.py (100 tokens)
   ├── Shortest Distance to a Character (100 tokens)
   ├── Singly Linked List(Music playlist Simulation).py (300 tokens)
   ├── SpaceBlasterX.py (700 tokens)
   ├── Spiral_Matrix.py (100 tokens)
   ├── Stack-valid_parantheses.py (100 tokens)
   ├── Stack.py (100 tokens)
   ├── Successfulpairofspellsandpotions.py (200 tokens)
   ├── Sudoku Solver using Backtracking.py (400 tokens)
   ├── Sum_of_Even_Fibonacci_numbers.py (100 tokens)
   ├── Swiminrisingwater.py (300 tokens)
   ├── TaskMeta.py (300 tokens)
   ├── Trie.py (900 tokens)
   ├── Two_Pointers_technique.py (100 tokens)
   ├── Two_Sum.py
   ├── UniquePath_Backtracking.py (600 tokens)
   ├── Unique_Paths.py
   ├── __pycache__/
      ├── palindrome_pattern.cpython-313.pyc (omitted)
   ├── add_and_subtract_nodes_in_linked_list.py (200 tokens)
   ├── addtwonumbers.py
   ├── advanced_binary_search_tree.py (3.6k tokens)
   ├── advanced_sorting.py (1600 tokens)
   ├── areaoftraingle.py (100 tokens)
   ├── arr_to_ll.py (100 tokens)
   ├── avl_tree.py (1300 tokens)
   ├── bellman_ford.py (200 tokens)
   ├── bfs.py (100 tokens)
   ├── binary_search.py (100 tokens)
   ├── binary_search1.py (100 tokens)
   ├── binary_search_tree.py (200 tokens)
   ├── binary_tree.py (100 tokens)
   ├── binary_tree_serialize_deserialize.py (200 tokens)
   ├── binary_tree_traversal.py (100 tokens)
   ├── bubble_sort.py (100 tokens)
   ├── bubblesort.py (100 tokens)
   ├── bulls_and_cows.py (100 tokens)
   ├── calcu.py (200 tokens)
   ├── calendar-module.py (100 tokens)
   ├── chatbot.py (100 tokens)
   ├── check prime.py (100 tokens)
   ├── circular_subarray_palindrome_check.py (100 tokens)
   ├── coin_change.py (100 tokens)
   ├── container_with_water.py (100 tokens)
   ├── convert_sorted_array_to_binary_search_tree.py (100 tokens)
   ├── counting_sort.py (1200 tokens)
   ├── cycle_detection.py (300 tokens)
   ├── decode.py (100 tokens)
   ├── detect_cycle_undirected.py (100 tokens)
   ├── dfs.py (100 tokens)
   ├── dfs_bfs_algo.py (600 tokens)
   ├── dice_roller.py (100 tokens)
   ├── dijkstra's_algorithm.py (200 tokens)
   ├── dijkstra.py (300 tokens)
   ├── disjoint_set.py (200 tokens)
   ├── disjoint_set_union.py (600 tokens)
   ├── distinct_subsequences.py
   ├── dynamic_programming.py (1800 tokens)
   ├── edit_distance.py (100 tokens)
   ├── exampledictionary.py (300 tokens)
   ├── factorial of a number.py (100 tokens)
   ├── factorial_recursion.py
   ├── fibonacci-new.py (100 tokens)
   ├── fibonacci.py (200 tokens)
   ├── fibonacci_dp.py (100 tokens)
   ├── fibonacci_recursion.py
   ├── find_index.py (100 tokens)
   ├── find_leaders.py (100 tokens)
   ├── first_missing_positive.py
   ├── fizzbuzz.py
   ├── fourth_from_first.py (100 tokens)
   ├── github_username_validator.py (100 tokens)
   ├── grading system based on marks.py (100 tokens)
   ├── graph2.py (200 tokens)
   ├── graph_adjacency_list.py (100 tokens)
   ├── graph_algorithms.py (1800 tokens)
   ├── graph_bfs.py (100 tokens)
   ├── graph_dfs.py (100 tokens)
   ├── half_linklist.py (100 tokens)
   ├── hash_count.py (100 tokens)
   ├── heap_operations.py (1300 tokens)
   ├── hello_world.py
   ├── helloworld.py
   ├── infix to postfix conversion using stack.py (200 tokens)
   ├── insertion_sort.py (100 tokens)
   ├── interleaving-string.py (200 tokens)
   ├── interleaving_string.py
   ├── intersection_of_two_array.py
   ├── josephus_problem(using deque).py (300 tokens)
   ├── kadanes_algo.py (200 tokens)
   ├── kmp_search.py (200 tokens)
   ├── knapsack_01.py (100 tokens)
   ├── knapsak.py (100 tokens)
   ├── knapsnack.py (100 tokens)
   ├── kruskals_algorithm.py (300 tokens)
   ├── kth_largest.py (200 tokens)
   ├── lc_66_plusone.py
   ├── leetcode_contest/
      ├── weekly_472.1.py (100 tokens)
   ├── lengthOflongestsubstring.py (100 tokens)
   ├── letterCombinationsOfPhoneNumber.py (300 tokens)
   ├── levelorder_bfs.py (100 tokens)
   ├── linear_search.py
   ├── linkedlist.py (100 tokens)
   ├── longest.py (100 tokens)
   ├── longest_balanced_substring.py
   ├── longest_palindromic_substring.py (200 tokens)
   ├── lowest_common_ancestor.py (200 tokens)
   ├── lru_cache.py (200 tokens)
   ├── m
   ├── manacher’s_Algorithm.py (200 tokens)
   ├── mathprob.py (100 tokens)
   ├── matrix_chain.py (200 tokens)
   ├── max_depth_binarytree.py (100 tokens)
   ├── max_subarray.py (100 tokens)
   ├── maximum_depth_of_binary_tree.py (100 tokens)
   ├── maximum_product_Subarray.py (100 tokens)
   ├── maximumprodsubarray.py (100 tokens)
   ├── maxof.py
   ├── maxprouct.py (100 tokens)
   ├── maze_solver.py (200 tokens)
   ├── merge_sort.py (400 tokens)
   ├── merge_soted_array.py (100 tokens)
   ├── min_number.py (100 tokens)
   ├── min_parentheses.py (200 tokens)
   ├── min_time_brew_potions.py (100 tokens)
   ├── minimum_steps_to_equalize_towers.py
   ├── minimum_window_substring.py (100 tokens)
   ├── multiplystrings.py (100 tokens)
   ├── n_queens_problem.py (200 tokens)
   ├── numprime.py (100 tokens)
   ├── pacificAtlanticWaterFlow.py (200 tokens)
   ├── palindrome.py (200 tokens)
   ├── palindrome_checker.py
   ├── palindrome_number.py
   ├── palindrome_numer.py (100 tokens)
   ├── palindrome_pattern.py (300 tokens)
   ├── pancake_sort.py (200 tokens)
   ├── partitionlist.py (100 tokens)
   ├── power.py
   ├── prefix_sum.py (100 tokens)
   ├── prims_algorithm.py (200 tokens)
   ├── print_circular_array.py (100 tokens)
   ├── python password_generator.py (100 tokens)
   ├── python_hashmap.py
   ├── queue_implementation.py (300 tokens)
   ├── queue_using_stack.py (100 tokens)
   ├── quick_sort.py (700 tokens)
   ├── red_black_tree.py (2.5k tokens)
   ├── reverse.py
   ├── reverseString.py
   ├── reverse_linked_list.py (300 tokens)
   ├── rk.py (100 tokens)
   ├── scramble_string.py
   ├── search_in_rotated_sorted_array.py (200 tokens)
   ├── segment.py (300 tokens)
   ├── segment_tree.py (800 tokens)
   ├── selection_sort.py (100 tokens)
   ├── sleep_sort.py (200 tokens)
   ├── sliding_window.py (100 tokens)
   ├── snake_water_gun.py (600 tokens)
   ├── squareroot.py (100 tokens)
   ├── stack(finding greater number).py (100 tokens)
   ├── stack_implementation.py (300 tokens)
   ├── static_method_implementation.py (300 tokens)
   ├── subsets.py (100 tokens)
   ├── subsets_78_lc.py (100 tokens)
   ├── substring_with_concatenation_of_all_words.py
   ├── subtree_of_another_tree.py (300 tokens)
   ├── sudoku_solver.py (300 tokens)
   ├── sum_of_1d_array.py (200 tokens)
   ├── sum_of_2D_array.py
   ├── sumof2darray.py (100 tokens)
   ├── sumof3darray.py
   ├── taking_maximum_energy.py (100 tokens)
   ├── tempCodeRunnerFile.py
   ├── text-wrap.py (100 tokens)
   ├── todo_list.py (200 tokens)
   ├── topological_sort.py (200 tokens)
   ├── towerofhanoi.py (100 tokens)
   ├── tree_height.py (100 tokens)
   ├── trie_implementation.py (1600 tokens)
   ├── tuples_value_replace.py (100 tokens)
   ├── twoosum.py
   ├── twosum (100 tokens)
   ├── undirected_graph_dfs.py (100 tokens)
   ├── unfolding_matrix_vishrutha.py (100 tokens)
   ├── uniquePerms.py (200 tokens)
   ├── waterjug.py (300 tokens)
   ├── wildcard.py
   ├── word_ladder.py (100 tokens)
   ├── wordsearch.py (100 tokens)
├── quote.py (200 tokens)
├── realworld-dsa/
   ├── README.md
   ├── maze_shortest_path.cpp
   ├── priority_task_scheduler.cpp
   ├── trie_autocomplete.cpp
├── roadmap/
   ├── DSA Road Map Basic to Advance.md (500 tokens)
   ├── GRAPH.py (200 tokens)
├── ruby/
   ├── BFS.rb (100 tokens)
   ├── IntroSort.rb (800 tokens)
   ├── JobRegistry.rb (500 tokens)
   ├── binary_search.rb (200 tokens)
   ├── dfs.rb
   ├── fenwick_Tree.rb (100 tokens)
   ├── heap_sort.rb (100 tokens)
   ├── hellowworld.rb
   ├── k-th_smallest_path.rb (1000 tokens)
   ├── merge_sort.rb (100 tokens)
   ├── optimal_network_restoration.rb (500 tokens)
   ├── search_range.rb (200 tokens)
   ├── shippack.rb (100 tokens)
   ├── shortest_safe_path_in grid.rb (400 tokens)
   ├── the_whispering_graph.rb (200 tokens)
   ├── topological_sort.rb (100 tokens)
   ├── warshsall_algo.rb (200 tokens)
├── rust/
   ├── A_star.rs (700 tokens)
   ├── Stack.rs (1100 tokens)
   ├── Task.rs (200 tokens)
   ├── bellman_ford_algo.rs (400 tokens)
   ├── bfs.rs (100 tokens)
   ├── binary_search.rs (100 tokens)
   ├── bubble_sort.rs (100 tokens)
   ├── decision_tree.rs (800 tokens)
   ├── dfs.rs (100 tokens)
   ├── dijkstra_algorithm.rs (400 tokens)
   ├── fruitsharvest.rs (200 tokens)
   ├── helloworld.rs
   ├── introsort.rs (900 tokens)
   ├── merge_sort.rs (200 tokens)
   ├── min_max_array.rs (100 tokens)
   ├── priority_queue.rs (100 tokens)
   ├── quick_sort.rs (200 tokens)
   ├── rabin_karp.rs (300 tokens)
   ├── reverse_array.rs
   ├── rotate_array.rs
   ├── ship.rs (200 tokens)
   ├── ternary_search.rs (200 tokens)
├── swift/
   ├── z_algorithm
   ├── z_algorithm.swift (200 tokens)
├── swimInWater.cpp (200 tokens)
├── tests/
   ├── JAVA/
      ├── CycleSortTest.java (200 tokens)
      ├── Test.java
├── typescript/
   ├── add.ts
   ├── apiResponseHandler.ts (300 tokens)
   ├── bfs.ts (300 tokens)
   ├── binarySearch.ts (100 tokens)
   ├── deep_object.ts (100 tokens)
   ├── dfss.ts (100 tokens)
   ├── djikstraAlgorithm.ts (200 tokens)
   ├── heap.ts (100 tokens)
   ├── helloWorld.ts
   ├── kadane_algori.ts (100 tokens)
   ├── linearSearch.ts (300 tokens)
   ├── mergeSort.ts (300 tokens)
   ├── mst.ts (200 tokens)
   ├── safe_event.ts (200 tokens)
   ├── slidingwindow.ts (100 tokens)
   ├── twoosum.ts (100 tokens)
├── visual-algorithm/
   ├── README.md
   ├── graph/
      ├── bfs_visual.cpp
   ├── sorting/
      ├── quicksort_visual.cpp
```


## /.gitignore

```gitignore path="/.gitignore" 
*.exe
".DS_Store" 
.DS_Store 
.DS_Store 
.DS_Store 

```

## /.history/java/Chatbot_20251011133817.java

```java path="/.history/java/Chatbot_20251011133817.java" 
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class Chatbot {
	
	private static final HashMap<String, String> Siri=new HashMap<>();
		static {
			 Siri.put("good evening", "good evening , Hope all is well!!");
			 Siri.put("hello", "Hello! I am a simple rule-based bot. How can I help you today?");
		     Siri.put("hi", "Hello there! Ask me about our operating hours or services.");
		     Siri.put("hours", "Our operating hours are Monday to Friday, 9:00 AM to 5:00 PM.");
		     Siri.put("service", "We offer customer support, technical assistance, and product demos.");
		     Siri.put("bye", "Goodbye! Have a great day.");
		     Siri.put("thank", "You're welcome! Feel free to ask anything else.");
		}
	private static String preprocessInput(String  In) {
		return In.toLowerCase().trim();
	}
	private static String getResponse(String Cli) {
		Set<String> key=Siri.keySet();
		for(String keys: key) {
			if(Cli.contains(keys)) {
				return Siri.get(keys);
			}
		}
		return "I'm sorry, I don't understand that. Could you please rephrase your question?";
	}
	public static void main(String[] args) {
		System.out.println("Siri Initialized");
		Scanner sc=new Scanner(System.in);
		String UsI;
		while(true) {
			System.out.print("You :  ");
			UsI = sc.nextLine();
			if(UsI.equalsIgnoreCase("bye")) {
				String farewell= getResponse(preprocessInput(UsI));
				System.out.println("Bot: "+ farewell);
				break;
			}
			String cleanedInput=preprocessInput(UsI);
			String botResponse=getResponse(cleanedInput);
			System.out.println("Bot: " + botResponse);
		}
		sc.close();
		System.out.println("Siri session ended.");
	}
}

```

## /.history/java/Chatbot_20251011135524.java

```java path="/.history/java/Chatbot_20251011135524.java" 
import java.util.HashMap;
import java.util.Scanner;
import java.util.Set;

public class Chatbot {

	private static final HashMap<String, String> Siri = new HashMap<>();
	static {
		Siri.put("good evening", "good evening , Hope all is well!!");
		Siri.put("hello", "Hello! I am a simple rule-based bot. How can I help you today?");
		Siri.put("hi", "Hello there! Ask me about our operating hours or services.");
		Siri.put("hours", "Our operating hours are Monday to Friday, 9:00 AM to 5:00 PM.");
		Siri.put("service", "We offer customer support, technical assistance, and product demos.");
		Siri.put("bye", "Goodbye! Have a great day.");
		Siri.put("thank", "You're welcome! Feel free to ask anything else.");
	}

	private static String preprocessInput(String In) {
		return In.toLowerCase().trim();
	}

	private static String getResponse(String Cli) {
		Set<String> key = Siri.keySet();
		for (String keys : key) {
			if (Cli.contains(keys)) {
				return Siri.get(keys);
			}
		}
		return "I'm sorry, I don't understand that. Could you please rephrase your question?";
	}

	public static void main(String[] args) {
		System.out.println("Siri Initialized");
		Scanner sc = new Scanner(System.in);
		String UsI;
		while (true) {
			System.out.print("You :  ");
			UsI = sc.nextLine();
			if (UsI.equalsIgnoreCase("bye")) {
				String farewell = getResponse(preprocessInput(UsI));
				System.out.println("Bot: " + farewell);
				break;
			}
			String cleanedInput = preprocessInput(UsI);
			String botResponse = getResponse(cleanedInput);
			System.out.println("Bot: " + botResponse);
		}
		sc.close();
		System.out.println("Siri session ended.");
	}
}

```

## /.history/java/HeapSort_20251011141215.java

```java path="/.history/java/HeapSort_20251011141215.java" 

```

## /.history/java/HeapSort_20251011141222.java

```java path="/.history/java/HeapSort_20251011141222.java" 
public class HeapSort {

}

```

## /.history/java/HeapSort_20251011141235.java

```java path="/.history/java/HeapSort_20251011141235.java" 
public class HeapSort {
    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/LeadersInArr_20251011135825.java

```java path="/.history/java/LeadersInArr_20251011135825.java" 

```

## /.history/java/LeadersInArr_20251011135904.java

```java path="/.history/java/LeadersInArr_20251011135904.java" 
import java.util.*;

public class LeadersInArr {

    public static void main(String[] args) {
        int[] arr = { 16, 17, 4, 3, 5, 2 };
        int n = arr.length;
        List<Integer> leaders = new ArrayList<>();

        int maxFromRight = arr[n - 1];
        leaders.add(maxFromRight);

        for (int i = n - 2; i >= 0; i--) {
            if (arr[i] >= maxFromRight) {
                maxFromRight = arr[i];
                leaders.add(maxFromRight);
            }
        }

        // Reverse to get leaders in correct order
        Collections.reverse(leaders);
        System.out.println(leaders);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140107.java

```java path="/.history/java/Sorting/HeapSort_20251011140107.java" 

```

## /.history/java/Sorting/HeapSort_20251011140130.java

```java path="/.history/java/Sorting/HeapSort_20251011140130.java" 
package Sorting;

public class HeapSort {

    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140206.java

```java path="/.history/java/Sorting/HeapSort_20251011140206.java" 
package Sorting;

public class HeapSort {

    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void HeapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140225.java

```java path="/.history/java/Sorting/HeapSort_20251011140225.java" 
package Sorting;

public class HeapSort {

    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void HeapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        HeapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140327.java

```java path="/.history/java/Sorting/HeapSort_20251011140327.java" 
package Sorting;

public class HeapSort {

    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140402.java

```java path="/.history/java/Sorting/HeapSort_20251011140402.java" 
package Sorting;

public class heapSort {

    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140409.java

```java path="/.history/java/Sorting/HeapSort_20251011140409.java" 
package Sorting;

public class heapSort {

    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140505.java

```java path="/.history/java/Sorting/HeapSort_20251011140505.java" 
package Sorting;

public class HeapSort {

}

```

## /.history/java/Sorting/HeapSort_20251011140530.java

```java path="/.history/java/Sorting/HeapSort_20251011140530.java" 
package Sorting;

public class heapSort {

}

```

## /.history/java/Sorting/HeapSort_20251011140554.java

```java path="/.history/java/Sorting/HeapSort_20251011140554.java" 
package Sorting;

public class heapSort {
    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140931.java

```java path="/.history/java/Sorting/HeapSort_20251011140931.java" 
package Sorting;

public class HeapSort {
    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.history/java/Sorting/HeapSort_20251011140956.java

```java path="/.history/java/Sorting/HeapSort_20251011140956.java" 
package Sorting;

public class HeapSort {
    // Function to heapify a subtree rooted with node i
    static void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int left = 2 * i + 1; // left child index
        int right = 2 * i + 2; // right child index

        // If left child is larger than root
        if (left < n && arr[left] > arr[largest])
            largest = left;

        // If right child is larger than largest so far
        if (right < n && arr[right] > arr[largest])
            largest = right;

        // If largest is not root
        if (largest != i) {
            int temp = arr[i];
            arr[i] = arr[largest];
            arr[largest] = temp;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Main function to perform heap sort
    static void heapSort(int arr[]) {
        int n = arr.length;

        // Step 1: Build max heap
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // Step 2: Extract elements one by one
        for (int i = n - 1; i >= 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // Call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };
        System.out.println("Original array:");
        printArray(arr);

        heapSort(arr);

        System.out.println("Sorted array:");
        printArray(arr);
    }
}

```

## /.idea/.gitignore

```gitignore path="/.idea/.gitignore" 
# Default ignored files
/shelf/
/workspace.xml
# Environment-dependent path to Maven home directory
/mavenHomeManager.xml
.DS_Store
```

## /.idea/misc.xml

```xml path="/.idea/misc.xml" 
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectRootManager" version="2" languageLevel="JDK_24" default="true" project-jdk-name="openjdk-24" project-jdk-type="JavaSDK">
    <output url="file://$PROJECT_DIR$/out" />
  </component>
</project>
```

## /.idea/modules.xml

```xml path="/.idea/modules.xml" 
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectModuleManager">
    <modules>
      <module fileurl="file://$PROJECT_DIR$/DSA-Project/DSA-Project.iml" filepath="$PROJECT_DIR$/DSA-Project/DSA-Project.iml" />
      <module fileurl="file://$PROJECT_DIR$/dsa-code.iml" filepath="$PROJECT_DIR$/dsa-code.iml" />
    </modules>
  </component>
</project>
```

## /.idea/vcs.xml

```xml path="/.idea/vcs.xml" 
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VcsDirectoryMappings">
    <mapping directory="" vcs="Git" />
  </component>
</project>
```

## /.vscode/c_cpp_properties.json

```json path="/.vscode/c_cpp_properties.json" 
{
  "configurations": [
    {
      "name": "windows-gcc-x64",
      "includePath": [
        "${workspaceFolder}/**"
      ],
      "defines": [
        "_DEBUG",
        "UNICODE",
        "_UNICODE"
      ],
      "compilerPath": "C:/MinGW/mingw32/bin/gcc.exe",
      "cStandard": "${default}",
      "cppStandard": "${default}",
      "intelliSenseMode": "windows-gcc-x64"
    }
  ],
  "version": 4
}
```

## /.vscode/launch.json

```json path="/.vscode/launch.json" 
{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "java",
      "name": "JobScheduling1",
      "request": "launch",
      "mainClass": "JobScheduling1",
      "projectName": "dsa-code_163e7579"
    },
    {
      "type": "java",
      "name": "JobScheduling",
      "request": "launch",
      "mainClass": "JobScheduling",
      "projectName": "dsa-code_163e7579"
      "name": "CountVowels",
      "request": "launch",
      "mainClass": "CountVowels",
      "projectName": "dsa-code_26e89efe"
    },
    {
      "type": "java",
      "name": "Permutations",
      "request": "launch",
      "mainClass": "Permutations",
      "projectName": "dsa-code_26e89efe"
    },
    {
      "type": "java",
      "name": "LongestSubstring",
      "request": "launch",
      "mainClass": "LongestSubstring",
      "projectName": "dsa-code_26e89efe"
    },
    {
      "type": "java",
      "name": "MaximumSubarray",
      "request": "launch",
      "mainClass": "MaximumSubarray",
      "projectName": "dsa-code_26e89efe"
    },
    {
      "type": "java",
      "name": "mergeTwoLists",
      "request": "launch",
      "mainClass": "mergeTwoLists",
      "projectName": "dsa-code_26e89efe"
    },
    {
      "type": "java",
      "name": "Main",
      "request": "launch",
      "mainClass": "Main",
      "projectName": "dsa-code_26e89efe"
    },
    {
      "name": "Java",
      "type": "java",
      "request": "launch",
      "stopOnEntry": true,
      "jdkPath": "${env:JAVA_HOME}/bin",
      "cwd": "${fileDirname}",
      "startupClass": "${fileBasenameNoExtension}",
      "classpath": [
        ".",
        "${fileDirname}"
      ]
    },
    {
      "name": "Java Console App",
      "type": "java",
      "request": "launch",
      "stopOnEntry": true,
      "jdkPath": "${env:JAVA_HOME}/bin",
      "cwd": "${fileDirname}",
      "startupClass": "${fileBasenameNoExtension}",
      "classpath": [
        ".",
        "${fileDirname}"
      ],
      "externalConsole": true
    },
    {
      "type": "java",
      "name": "Current File",
      "request": "launch",
      "mainClass": "${file}"
    },
    {
      "type": "java",
      "name": "RotateImage",
      "request": "launch",
      "mainClass": "RotateImage",
      "projectName": "dsa-code_cb401e8"
    },
    {
      "type": "java",
      "name": "Secondlargest",
      "request": "launch",
      "mainClass": "Secondlargest",
      "projectName": "dsa-code_cb401e8"
    },
    {
      "type": "java",
      "name": "Sort_Ascending_Order",
      "request": "launch",
      "mainClass": "Sort_Ascending_Order",
      "projectName": "dsa-code_cb401e8"
    },
    {
      "type": "java",
      "name": "hellowordl",
      "request": "launch",
      "mainClass": "hellowordl",
      "projectName": "dsa-code_cb401e8"
    },
    {
      "name": "C/C++ Runner: Debug Session",
      "type": "cppdbg",
      "request": "launch",
      "args": [],
      "stopAtEntry": false,
      "externalConsole": true,
      "cwd": "c:/Users/ujesh/OneDrive/Documents/blockparty/dsa-code",
      "program": "c:/Users/ujesh/OneDrive/Documents/blockparty/dsa-code/build/Debug/outDebug",
      "MIMode": "gdb",
      "miDebuggerPath": "gdb",
      "setupCommands": [
        {
          "description": "Enable pretty-printing for gdb",
          "text": "-enable-pretty-printing",
          "ignoreFailures": true
        }
      ]
    }
  ]
}
```

## /.vscode/settings.json

```json path="/.vscode/settings.json" 
{
  "C_Cpp.errorSquiggles": "disabled",
  "C_Cpp_Runner.cCompilerPath": "gcc",
  "C_Cpp_Runner.cppCompilerPath": "g++",
  "C_Cpp_Runner.debuggerPath": "gdb",
  "C_Cpp_Runner.cStandard": "",
  "C_Cpp_Runner.cppStandard": "",
  "C_Cpp_Runner.msvcBatchPath": "C:/Program Files/Microsoft Visual Studio/VR_NR/Community/VC/Auxiliary/Build/vcvarsall.bat",
  "C_Cpp_Runner.useMsvc": false,
  "C_Cpp_Runner.warnings": [
    "-Wall",
    "-Wextra",
    "-Wpedantic",
    "-Wshadow",
    "-Wformat=2",
    "-Wcast-align",
    "-Wconversion",
    "-Wsign-conversion",
    "-Wnull-dereference"
  ],
  "C_Cpp_Runner.msvcWarnings": [
    "/W4",
    "/permissive-",
    "/w14242",
    "/w14287",
    "/w14296",
    "/w14311",
    "/w14826",
    "/w44062",
    "/w44242",
    "/w14905",
    "/w14906",
    "/w14263",
    "/w44265",
    "/w14928"
  ],
  "C_Cpp_Runner.enableWarnings": true,
  "C_Cpp_Runner.warningsAsError": false,
  "C_Cpp_Runner.compilerArgs": [],
  "C_Cpp_Runner.linkerArgs": [],
  "C_Cpp_Runner.includePaths": [],
  "C_Cpp_Runner.includeSearch": ["*", "**/*"],
  "C_Cpp_Runner.excludeSearch": [
    "**/build",
    "**/build/**",
    "**/.*",
    "**/.*/**",
    "**/.vscode",
    "**/.vscode/**"
  ],
  "C_Cpp_Runner.useAddressSanitizer": false,
  "C_Cpp_Runner.useUndefinedSanitizer": false,
  "C_Cpp_Runner.useLeakSanitizer": false,
  "C_Cpp_Runner.showCompilationTime": false,
  "C_Cpp_Runner.useLinkTimeOptimization": false,
  "C_Cpp_Runner.msvcSecureNoWarnings": false,
  "java.debug.settings.onBuildFailureProceed": true,
  "files.associations": {
    "ostream": "cpp"
  }
}

```

## /.vscode/tasks.json

```json path="/.vscode/tasks.json" 
{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\\MinGW\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}
```

## /75-Dsa-Problems/Binary-Search/Arranging_coins.cpp

```cpp path="/75-Dsa-Problems/Binary-Search/Arranging_coins.cpp" 
class Solution {
    public int arrangeCoins(int n) {
        int level = 0, coin = 1;
        while (n >= coin) {
            n -= coin;
            coin++;
            level++;
        }
        return level;
    }
}
```

## /75-Dsa-Problems/Binary-Search/FindMinRotatedArray.cpp

```cpp path="/75-Dsa-Problems/Binary-Search/FindMinRotatedArray.cpp" 
// 153. Find Minimum in Rotated Sorted Array -- leetcode

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
  int findPivot(vector<int> &nums, int l, int r)
  {
    while (l < r && nums[l] == nums[l + 1])
      l++;
    while (l < r && nums[r] == nums[r - 1])
      r--;
    while (l < r)
    {
      int mid = l + (r - l) / 2;
      if (nums[mid] > nums[r])
        l = mid + 1;
      else
        r = mid;
    }
    return l;
  }

  bool binarySearch(vector<int> &nums, int l, int r, int target)
  {
    while (l <= r)
    {
      int mid = l + (r - l) / 2;
      if (nums[mid] == target)
        return true;
      else if (nums[mid] < target)
        l = mid + 1;
      else
        r = mid - 1;
    }
    return false;
  }

  bool search(vector<int> &nums, int target)
  {
    int n = nums.size();
    if (n == 0)
      return false;
    int pivot = findPivot(nums, 0, n - 1);
    if (binarySearch(nums, 0, pivot - 1, target))
      return true;
    return binarySearch(nums, pivot, n - 1, target);
  }
};

int main()
{
  Solution s;
  vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
  int target = 0;
  cout << (s.search(nums, target) ? "Found" : "Not Found") << endl;
}

```

## /75-Dsa-Problems/Binary-Search/FindPeak.cpp

```cpp path="/75-Dsa-Problems/Binary-Search/FindPeak.cpp" 
// 162. Find Peak Element -- leetcode

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
  int findPeakElement(vector<int> &nums)
  {
    int l = 0;
    int r = nums.size() - 1;
    while (l < r)
    {
      int mid = (l + r) / 2;
      if (nums[mid] < nums[mid + 1])
      {
        l = mid + 1;
      }
      else
      {
        r = mid;
      }
    }
    return r;
  }
};

int main()
{
  Solution s;
  vector<int> nums = {1, 2, 3, 1};
  cout << "Peak element index: " << s.findPeakElement(nums) << endl;
}

```

## /75-Dsa-Problems/Binary-Search/graph/NumberOfIslands.cpp

```cpp path="/75-Dsa-Problems/Binary-Search/graph/NumberOfIslands.cpp" 
// LeetCode 200: Number of Islands
// Issue #1063
// Solved using Depth First Search (DFS)
// Time Complexity: O(m * n)

#include <iostream>
#include <vector>

using namespace std;

class Solution {
private:
    /**
     * @brief Helper function to perform DFS on the grid.
     * This function will "sink" an island by turning all '1's to '0's.
     * @param grid The 2D grid of land and water.
     * @param r The current row index.
     * @param c The current column index.
     */
    void dfs(vector<vector<char>>& grid, int r, int c) {
        int numRows = grid.size();
        int numCols = grid[0].size();

        // Base cases (check for out-of-bounds or if it's water)
        if (r < 0 || c < 0 || r >= numRows || c >= numCols || grid[r][c] == '0') {
            return;
        }

        // Mark the current cell as visited (sink it)
        grid[r][c] = '0';

        // Recursively call DFS on all 4 neighbors
        dfs(grid, r + 1, c); // down
        dfs(grid, r - 1, c); // up
        dfs(grid, r, c + 1); // right
        dfs(grid, r, c - 1); // left
    }

public:
    /**
     * @brief Counts the number of islands in a 2D grid.
     * @param grid The 2D grid of '1's (land) and '0's (water).
     * @return The total number of islands.
     */
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty() || grid[0].empty()) {
            return 0;
        }

        int numRows = grid.size();
        int numCols = grid[0].size();
        int islandCount = 0;

        // Iterate through every cell in the grid
        for (int i = 0; i < numRows; ++i) {
            for (int j = 0; j < numCols; ++j) {
                // If we find land ('1'), it's a new island
                if (grid[i][j] == '1') {
                    islandCount++;
                    // Use DFS to sink the entire island so we don't count it again
                    dfs(grid, i, j);
                }
            }
        }

        return islandCount;
    }
};

// Main function to test the code
int main() {
    Solution sol;

    // Test Case 1
    vector<vector<char>> grid1 = {
        {'1', '1', '1', '1', '0'},
        {'1', '1', '0', '1', '0'},
        {'1', '1', '0', '0', '0'},
        {'0', '0', '0', '0', '0'}
    };
    cout << "Test Case 1: Number of Islands = " << sol.numIslands(grid1) << endl; // Expected: 1

    // Test Case 2 (Create a copy as numIslands modifies the grid)
    vector<vector<char>> grid2 = {
        {'1', '1', '0', '0', '0'},
        {'1', '1', '0', '0', '0'},
        {'0', '0', '1', '0', '0'},
        {'0', '0', '0', '1', '1'}
    };
    cout << "Test Case 2: Number of Islands = " << sol.numIslands(grid2) << endl; // Expected: 3

    return 0;
}
```

## /75-Dsa-Problems/Binary-Search/kokoEating.cpp

```cpp path="/75-Dsa-Problems/Binary-Search/kokoEating.cpp" 
// 875. Koko Eating Bananas

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
  bool canEatAll(vector<int> &piles, int mid, int h)
  {
    long long totalHours = 0;
    for (int x : piles)
    {
      totalHours += x / mid;
      if (x % mid != 0)
        totalHours++;
    }
    return totalHours <= h;
  }

  int minEatingSpeed(vector<int> &piles, int h)
  {
    int l = 1;
    int r = *max_element(piles.begin(), piles.end());

    while (l < r)
    {
      int mid = l + (r - l) / 2;
      if (canEatAll(piles, mid, h))
      {
        r = mid;
      }
      else
      {
        l = mid + 1;
      }
    }
    return l;
  }
};

int main()
{
  Solution s;
  vector<int> piles = {3, 6, 7, 11};
  int h = 8;

  cout << "Minimum eating speed: " << s.minEatingSpeed(piles, h) << endl;
}

```

## /75-Dsa-Problems/Binary-Search/searchRotatedArray.cpp

```cpp path="/75-Dsa-Problems/Binary-Search/searchRotatedArray.cpp" 
// 81. Search in Rotated Sorted Array II -- leetcode

#include <bits/stdc++.h>
using namespace std;

class Solution
{
public:
  
  int findPivot(vector<int> &nums, int l, int r)
  {
  
    while (l < r && nums[l] == nums[l + 1])
      l++;
    while (l < r && nums[r] == nums[r - 1])
      r--;

    
    while (l < r)
    {
      int mid = l + (r - l) / 2;
      if (nums[mid] > nums[r])
      {
        l = mid + 1; 
      }
      else
      {
        r = mid; 
      }
    }
    return l; 
  }


  bool binarySearch(vector<int> &nums, int l, int r, int target)
  {
    while (l <= r)
    {
      int mid = l + (r - l) / 2;
      if (nums[mid] == target)
        return true;
      else if (nums[mid] < target)
        l = mid + 1;
      else
        r = mid - 1;
    }
    return false;
  }

  
  bool search(vector<int> &nums, int target)
  {
    int n = nums.size();
    if (n == 0)
      return false;

    int pivot = findPivot(nums, 0, n - 1);

    
    if (binarySearch(nums, 0, pivot - 1, target))
      return true;
    return binarySearch(nums, pivot, n - 1, target);
  }
};

int main()
{
  Solution s;
  vector<int> nums = {4, 5, 6, 7, 0, 1, 2};
  int target = 0;

  cout << (s.search(nums, target) ? "Found" : "Not Found") << endl;
}

```

## /Add Code Here/.DS_Store

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/Add Code Here/.DS_Store

## /Add Code Here/JAVA/AnagramChecker.java

```java path="/Add Code Here/JAVA/AnagramChecker.java" 
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * Anagram Checker - Multiple approaches to verify if two strings are anagrams
 * 
 * An anagram is a word formed by rearranging letters of another word,
 * using all original letters exactly once.
 * 
 * Example: "listen" and "silent" are anagrams
 * 
 * @author Prince Yadav
 * @version 2.0
 * @since October 2025
 */
public class AnagramChecker {
    
    /**
     * Checks if two strings are anagrams using HashMap (case-insensitive)
     * Ignores non-alphabetic characters and whitespace
     * 
     * Time Complexity: O(n + m) where n, m are lengths of strings
     * Space Complexity: O(k) where k is number of unique characters
     * 
     * @param word1 First string to compare
     * @param word2 Second string to compare
     * @return true if strings are anagrams, false otherwise
     */
    public static boolean isAnagram(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return false;
        }
        
        // Remove non-alpha characters and convert to lowercase
        word1 = word1.replaceAll("[^a-zA-Z]", "").toLowerCase();
        word2 = word2.replaceAll("[^a-zA-Z]", "").toLowerCase();
        
        // Quick length check
        if (word1.length() != word2.length()) {
            return false;
        }
        
        // Count character frequencies
        Map<Character, Integer> charCount = new HashMap<>();
        
        for (char c : word1.toCharArray()) {
            charCount.put(c, charCount.getOrDefault(c, 0) + 1);
        }
        
        for (char c : word2.toCharArray()) {
            if (!charCount.containsKey(c)) {
                return false;
            }
            
            int count = charCount.get(c) - 1;
            if (count == 0) {
                charCount.remove(c);
            } else {
                charCount.put(c, count);
            }
        }
        
        return charCount.isEmpty();
    }
    
    /**
     * Alternative approach using sorting (simpler but slightly less efficient)
     * 
     * Time Complexity: O(n log n)
     * Space Complexity: O(n) for character arrays
     * 
     * @param word1 First string
     * @param word2 Second string
     * @return true if anagrams
     */
    public static boolean isAnagramSorting(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return false;
        }
        
        word1 = word1.replaceAll("[^a-zA-Z]", "").toLowerCase();
        word2 = word2.replaceAll("[^a-zA-Z]", "").toLowerCase();
        
        if (word1.length() != word2.length()) {
            return false;
        }
        
        char[] arr1 = word1.toCharArray();
        char[] arr2 = word2.toCharArray();
        
        Arrays.sort(arr1);
        Arrays.sort(arr2);
        
        return Arrays.equals(arr1, arr2);
    }
    
    /**
     * Optimized approach using character frequency array (for lowercase letters only)
     * Most efficient for simple anagram checking
     * 
     * Time Complexity: O(n)
     * Space Complexity: O(1) - fixed 26 character array
     * 
     * @param word1 First string
     * @param word2 Second string
     * @return true if anagrams
     */
    public static boolean isAnagramOptimized(String word1, String word2) {
        if (word1 == null || word2 == null) {
            return false;
        }
        
        word1 = word1.replaceAll("[^a-zA-Z]", "").toLowerCase();
        word2 = word2.replaceAll("[^a-zA-Z]", "").toLowerCase();
        
        if (word1.length() != word2.length()) {
            return false;
        }
        
        int[] charFreq = new int[26]; // For 'a' to 'z'
        
        for (int i = 0; i < word1.length(); i++) {
            charFreq[word1.charAt(i) - 'a']++;
            charFreq[word2.charAt(i) - 'a']--;
        }
        
        for (int count : charFreq) {
            if (count != 0) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * Prints test result in formatted manner
     */
    private static void testAnagram(String word1, String word2) {
        boolean result1 = isAnagram(word1, word2);
        boolean result2 = isAnagramSorting(word1, word2);
        boolean result3 = isAnagramOptimized(word1, word2);
        
        System.out.printf("%-20s | %-20s | HashMap: %-5s | Sorting: %-5s | Optimized: %-5s%n",
                         "\"" + word1 + "\"", "\"" + word2 + "\"", 
                         result1, result2, result3);
    }
    
    public static void main(String[] args) {
        System.out.println("=== Anagram Checker Test Cases ===\n");
        System.out.printf("%-20s | %-20s | %-14s | %-14s | %-14s%n",
                         "Word 1", "Word 2", "HashMap", "Sorting", "Optimized");
        System.out.println("-".repeat(95));
        
        // Basic anagrams
        testAnagram("evil", "vile");
        testAnagram("angel", "glean");
        testAnagram("listen", "silent");
        
        // With spaces and punctuation
        testAnagram("school master", "the classroom");
        testAnagram("conversation", "voices rant on");
        
        // Not anagrams
        testAnagram("listen", "hearing");
        testAnagram("hello", "world");
        
        // Edge cases
        testAnagram("", "");
        testAnagram("a", "a");
        testAnagram("abc", "def");
        
        System.out.println("\n=== Performance Comparison ===\n");
        
        String str1 = "astronomer";
        String str2 = "moon starer";
        
        // Benchmark HashMap approach
        long start = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            isAnagram(str1, str2);
        }
        long hashMapTime = System.nanoTime() - start;
        
        // Benchmark Sorting approach
        start = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            isAnagramSorting(str1, str2);
        }
        long sortingTime = System.nanoTime() - start;
        
        // Benchmark Optimized approach
        start = System.nanoTime();
        for (int i = 0; i < 100000; i++) {
            isAnagramOptimized(str1, str2);
        }
        long optimizedTime = System.nanoTime() - start;
        
        System.out.printf("HashMap approach:   %d ms%n", hashMapTime / 1_000_000);
        System.out.printf("Sorting approach:   %d ms%n", sortingTime / 1_000_000);
        System.out.printf("Optimized approach: %d ms%n", optimizedTime / 1_000_000);
        
        System.out.println("\nRecommendation:");
        System.out.println("- Use Optimized (array) for simple lowercase anagrams");
        System.out.println("- Use HashMap for Unicode/multilingual support");
        System.out.println("- Use Sorting for simplicity and readability");
    }
}
```

## /Add Code Here/JAVA/BinarySearch.java

```java path="/Add Code Here/JAVA/BinarySearch.java" 
// Program: Binary Search in Java
// Purpose: To find whether a given number exists in a sorted array using Binary Search technique

import java.util.Scanner; // Import Scanner class for user input

public class Binary_Search
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in); // Create a Scanner object for input

        int i = 0, flag = 0; // 'flag' variable will be used to indicate if element is found or not

        // Step 1: Initialize a sorted array (Binary Search works only on sorted arrays)
        int a[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
        
        // Step 2: Display the array elements
        System.out.println("Array elements are:");
        for(i = 0; i < 10; i++)
        {
            System.out.println(a[i]);
        }
        
        // Step 3: Ask the user to enter the number to search
        System.out.println("Enter a number to search:");
        int num = sc.nextInt();
        
        // Step 4: Initialize variables for binary search
        int f = 0;   // 'f' represents the first index
        int l = 9;   // 'l' represents the last index
        int m = 0;   // 'm' represents the middle index

        // Step 5: Perform Binary Search using while loop
        while(f <= l)
        {
            m = (f + l) / 2; // Calculate middle index

            // Case 1: Element found at mid position
            if(num == a[m])
            {
                flag = 1; // Mark flag as found
                break;    // Exit loop
            }

            // Case 2: If element is smaller than middle value, search in left half
            else if(num < a[m])
            {
                l = m - 1;
            }

            // Case 3: If element is greater than middle value, search in right half
            else
            {
                f = m + 1;
            }
        }

        // Step 6: Display result based on flag value
        if(flag == 0)
        {
            System.out.println("Search element not found");
        }
        else
        {
            System.out.println("Search element found at cell number " + (m + 1));
        }

        sc.close(); // Close Scanner object to prevent memory leak
    }
}

```

## /Add Code Here/JAVA/BubbleSort_ascending.java

```java path="/Add Code Here/JAVA/BubbleSort_ascending.java" 
import java.util.Scanner;

public class BubbleSort_ascending
{
    public static void main(String args[])
    {
        
        Scanner sc = new Scanner(System.in);   // Create Scanner object for user input
        int i = 0, j = 0, temp = 0;            // Declare loop variables and temporary variable for swapping
        int a[] = new int[5];                  // Declare an integer array of size 5

        // Take input from the user
        System.out.println("Enter 5 numbers: ");
        for(i = 0; i < 5; i++)
        {
            a[i] = sc.nextInt();               // Read each number and store in array
        }

        // Display array before sorting
        System.out.println("Array before sorting: ");
        for(i = 0; i < 5; i++)
        {
            System.out.print(a[i] + ",");      // Print each element separated by a comma
        }

```

## /Add Code Here/JAVA/CycleSort.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/Add Code Here/JAVA/CycleSort.class

## /Add Code Here/JAVA/CycleSort.java

```java path="/Add Code Here/JAVA/CycleSort.java" 
import java.util.Scanner;
import java.util.Arrays;

/**
 * 🚀 Cycle Sort Implementation
 * 
 * Sorts an array of distinct integers (1 to n) using Cycle Sort.
 * Validates input and handles errors gracefully.
 * 
 * Time Complexity: O(n)
 * Space Complexity: O(1)
 * 
 * Example:
 * Input: 3 1 5 4 2
 * Output: 1 2 3 4 5
 * 
 * Author: Prince Yadav
 * Version: 2.0
 */
public class CycleSort {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.println("Enter number of elements (distinct numbers 1 to n):");
        int n = sc.nextInt();
        if (n <= 0) {
            System.out.println("Error: Number of elements must be positive.");
            sc.close();
            return;
        }

        int[] arr = new int[n];
        System.out.println("Enter elements in the array:");
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
            if (arr[i] < 1 || arr[i] > n) {
                System.out.println("Error: Elements must be distinct numbers from 1 to " + n);
                sc.close();
                return;
            }
        }

        cycleSort(arr);

        System.out.println("Sorted array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();

        sc.close();
    }

    /**
     * Cycle Sort algorithm
     * Sorts an array of distinct integers 1 to n
     * @param arr Input array
     */
    public static void cycleSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            while (arr[i] != i + 1) {
                int correct = arr[i] - 1;
                if (arr[correct] == arr[i]) break; // Prevent infinite loop
                int temp = arr[i];
                arr[i] = arr[correct];
                arr[correct] = temp;
            }
        }
    }

    /**
     * Utility method for testing
     * @param arr input array
     * @return sorted array (copy)
     */
    public static int[] sortArray(int[] arr) {
        int[] copy = Arrays.copyOf(arr, arr.length);
        cycleSort(copy);
        return copy;
    }
}

```

## /Add Code Here/JAVA/EvenOddChecker.java

```java path="/Add Code Here/JAVA/EvenOddChecker.java" 
/*
 * Program: Even or Odd Checker
 * Author: Akshat Patil
 * Date: October 27, 2025
 * Description: 
 * This program takes an integer input from the user
 * and checks whether it is even or odd using the modulus operator.
 */

import java.util.Scanner;

public class EvenOddChecker {
    public static void main(String[] args) {

        // Create Scanner object to take input from user
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter a number: ");
        int number = scanner.nextInt(); // Input from user

        // Check whether the number is even or odd
        if (number % 2 == 0) {
            System.out.println(number + " is an Even number.");
        } else {
            System.out.println(number + " is an Odd number.");
        }

        // Close the scanner to prevent resource leaks
        scanner.close();
    }
}

```

## /Add Code Here/JAVA/FibonacciMemoization.java

```java path="/Add Code Here/JAVA/FibonacciMemoization.java" 
/**
 * Fibonacci Number Calculator using Dynamic Programming (Memoization)
 * 
 * Problem: Calculate nth Fibonacci number efficiently
 * Approach: Top-down DP with memoization to avoid recalculation
 * 
 * Time Complexity: O(n)
 * Space Complexity: O(n)
 * 
 * @author Prince Yadav
 * @version 1.0
 * @since October 2025
 */
public class FibonacciMemoization {
    
    // Cache array to store computed Fibonacci numbers
    private static long[] memo;
    
    /**
     * Calculates nth Fibonacci number using memoization
     * Formula: F(n) = F(n-1) + F(n-2)
     * Base cases: F(0) = 0, F(1) = 1
     * 
     * @param n The position in Fibonacci sequence (0-indexed)
     * @return The nth Fibonacci number
     * @throws IllegalArgumentException if n is negative
     */
    public static long fibonacci(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("n must be non-negative");
        }
        
        // Base cases
        if (n <= 1) {
            return n;
        }
        
        // Return cached value if already computed
        if (memo[n] != 0) {
            return memo[n];
        }
        
        // Compute and cache the result
        long fibNumber = fibonacci(n - 1) + fibonacci(n - 2);
        memo[n] = fibNumber;
        
        return fibNumber;
    }
    
    /**
     * Alternative iterative approach (more efficient)
     * Time: O(n), Space: O(1)
     * 
     * @param n Position in sequence
     * @return nth Fibonacci number
     */
    public static long fibonacciIterative(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("n must be non-negative");
        }
        
        if (n <= 1) {
            return n;
        }
        
        long prev2 = 0;
        long prev1 = 1;
        long current = 0;
        
        for (int i = 2; i <= n; i++) {
            current = prev1 + prev2;
            prev2 = prev1;
            prev1 = current;
        }
        
        return current;
    }
    
    /**
     * Initializes memoization array
     * 
     * @param size Size of memo array (n+1)
     */
    private static void initializeMemo(int size) {
        memo = new long[size + 1];
    }
    
    /**
     * Prints the entire Fibonacci sequence up to n
     * 
     * @param n Upper limit
     */
    public static void printFibonacciSequence(int n) {
        System.out.println("Fibonacci Sequence up to F(" + n + "):");
        for (int i = 0; i <= n; i++) {
            System.out.printf("F(%d) = %d%n", i, memo[i]);
        }
    }
    
    /**
     * Main method demonstrating usage with multiple test cases
     */
    public static void main(String[] args) {
        // Test Case 1: Basic calculation
        System.out.println("=== Test Case 1: Calculate F(50) ===");
        int n = 50;
        initializeMemo(n);
        
        long result = fibonacci(n);
        System.out.println("F(" + n + ") = " + result);
        System.out.println();
        
        // Test Case 2: Print first 15 Fibonacci numbers
        System.out.println("=== Test Case 2: First 15 Numbers ===");
        initializeMemo(15);
        for (int i = 0; i <= 15; i++) {
            System.out.printf("F(%2d) = %d%n", i, fibonacci(i));
        }
        System.out.println();
        
        // Test Case 3: Compare both approaches
        System.out.println("=== Test Case 3: Compare Approaches ===");
        int testN = 40;
        initializeMemo(testN);
        
        long startTime = System.nanoTime();
        long memoResult = fibonacci(testN);
        long memoTime = System.nanoTime() - startTime;
        
        startTime = System.nanoTime();
        long iterResult = fibonacciIterative(testN);
        long iterTime = System.nanoTime() - startTime;
        
        System.out.println("Memoization: F(" + testN + ") = " + memoResult + 
                         " (Time: " + memoTime/1000 + " μs)");
        System.out.println("Iterative:   F(" + testN + ") = " + iterResult + 
                         " (Time: " + iterTime/1000 + " μs)");
        System.out.println();
        
        // Test Case 4: Edge cases
        System.out.println("=== Test Case 4: Edge Cases ===");
        System.out.println("F(0) = " + fibonacciIterative(0)); // Expected: 0
        System.out.println("F(1) = " + fibonacciIterative(1)); // Expected: 1
        System.out.println("F(2) = " + fibonacciIterative(2)); // Expected: 1
    }
}
```

## /Add Code Here/JAVA/MergeSort.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/Add Code Here/JAVA/MergeSort.class

## /Add Code Here/JAVA/MergeSort.java

```java path="/Add Code Here/JAVA/MergeSort.java" 
public class MergeSort {

    public static void mergeInPlace(int arr[], int start, int mid, int end) {
        int start2 = mid + 1;
        if (arr[mid] <= arr[start2]) return;

        while (start <= mid && start2 <= end) {
            if (arr[start] <= arr[start2]) {
                start++;
            } else {
                int value = arr[start2];
                int index = start2;

                while (index != start) {
                    arr[index] = arr[index - 1];
                    index--;
                }
                arr[start] = value;

                start++;
                mid++;
                start2++;
            }
        }
    }

    public static void mergeSort(int arr[], int l, int r) {
        if (l >= r) return;

        int m = l + (r - l) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        mergeInPlace(arr, l, m, r);
    }

    public static void main(String[] args) {
        int arr[] = {6, 3, 9, 5, 2, 8};
        int n = arr.length;

        mergeSort(arr, 0, n - 1);

        System.out.println("Sorted array:");
        for (int num : arr) {
            System.out.print(num + " ");
        }
        System.out.println();
    }
}

```

## /Add Code Here/JAVA/ReverseArray.java

```java path="/Add Code Here/JAVA/ReverseArray.java" 
// Author: Sohum Seth
// Problem: Reverse an Array
// Language: Java

import java.util.*;

public class ReverseArray {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of elements: ");
        int n = sc.nextInt();
        int[] arr = new int[n];

        System.out.println("Enter elements:");
        for (int i = 0; i < n; i++) arr[i] = sc.nextInt();

        System.out.print("Reversed array: ");
        for (int i = n - 1; i >= 0; i--) System.out.print(arr[i] + " ");
    }
}

```

## /Algorithms/dijkstra.py

```py path="/Algorithms/dijkstra.py" 
import heapq

def dijkstra(graph, start):
    """
    Dijkstra's algorithm to find shortest paths from start node to all other nodes.

    Parameters:
    graph : dict - adjacency list {node: [(neighbor, weight), ...]}
    start : starting node

    Returns:
    distances : dict - shortest distance from start to each node
    """

    distances = {node: float('inf') for node in graph}
    distances[start] = 0

    priority_queue = [(0, start)]  # (distance, node)

    while priority_queue:
        current_distance, current_node = heapq.heappop(priority_queue)

        if current_distance > distances[current_node]:
            continue

        for neighbor, weight in graph[current_node]:
            distance = current_distance + weight

            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(priority_queue, (distance, neighbor))

    return distances

# Example usage:
if __name__ == "__main__":
    graph = {
        'A': [('B', 1), ('C', 4)],
        'B': [('A', 1), ('C', 2), ('D', 5)],
        'C': [('A', 4), ('B', 2), ('D', 1)],
        'D': [('B', 5), ('C', 1)]
    }
    start_node = 'A'
    print("Shortest distances:", dijkstra(graph, start_node))

```

## /AreaCalculator.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/AreaCalculator.class

## /AreaCalculator.java

```java path="/AreaCalculator.java" 
import java.util.Scanner;

public class AreaCalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\n--- Area Calculator ---");
            System.out.println("1. Circle");
            System.out.println("2. Rectangle");
            System.out.println("3. Triangle");
            System.out.println("4. Exit");
            System.out.print("Enter your choice: ");
            choice = sc.nextInt();

            switch (choice) {
                case 1:
                    System.out.print("Enter radius of circle: ");
                    double radius = sc.nextDouble();
                    double circleArea = 3.14159 * radius * radius;
                    System.out.println("Area of Circle = " + circleArea);
                    break;

                case 2:
                    System.out.print("Enter length of rectangle: ");
                    double length = sc.nextDouble();
                    System.out.print("Enter width of rectangle: ");
                    double width = sc.nextDouble();
                    double rectArea = length * width;
                    System.out.println("Area of Rectangle = " + rectArea);
                    break;

                case 3:
                    System.out.print("Enter base of triangle: ");
                    double base = sc.nextDouble();
                    System.out.print("Enter height of triangle: ");
                    double height = sc.nextDouble();
                    double triArea = 0.5 * base * height;
                    System.out.println("Area of Triangle = " + triArea);
                    break;

                case 4:
                    System.out.println("Exiting program. Goodbye!");
                    break;

                default:
                    System.out.println("Invalid choice! Please try again.");
            }

        } while (choice != 4);

        sc.close();
    }
}

```

## /Best Time to Buy and Sell Stock.cpp

```cpp path="/Best Time to Buy and Sell Stock.cpp" 
 class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty()) return 0; 
        int minPrice = prices[0]; 
        int maxProfit = 0;         
        for(int i=1; i<prices.size(); i++){
            maxProfit = max(maxProfit, prices[i] - minPrice); // max check which is maximum between the two value
            minPrice = min(minPrice, prices[i]); 
        }
        return maxProfit;
    }
};

```

## /BinarySearchTree.py

```py path="/BinarySearchTree.py" 
class Node:
    """
    Represents a single node in the Binary Search Tree.
    """
    def __init__(self, value):
        self.value = value  # The node's data
        self.left = None    # Pointer to the left child node
        self.right = None   # Pointer to the right child node

    def __str__(self):
        # Helper for printing
        return f"Node({self.value})"


class BinarySearchTree:
    """
    The main class that manages the BST operations.
    """
    def __init__(self):
        self.root = None  # The tree is initially empty

    def insert(self, value):
        """
        Public method to insert a new value into the tree.
        """
        if self.root is None:
            # If the tree is empty, the new node is the root
            self.root = Node(value)
        else:
            # Otherwise, find the correct spot starting from the root
            self._insert_recursive(self.root, value)

    def _insert_recursive(self, current_node, value):
        """
        Private recursive helper method to find where to insert.
        """
        if value < current_node.value:
            # --- Go Left ---
            if current_node.left is None:
                # If there's no left child, insert here
                current_node.left = Node(value)
            else:
                # Otherwise, keep going down the left subtree
                self._insert_recursive(current_node.left, value)
                
        elif value > current_node.value:
            # --- Go Right ---
            if current_node.right is None:
                # If there's no right child, insert here
                current_node.right = Node(value)
            else:
                # Otherwise, keep going down the right subtree
                self._insert_recursive(current_node.right, value)
        
        # else: value == current_node.value
        # This implementation ignores duplicates. You could also
        # choose to place them on the right.

    def search(self, value):
        """
        Public method to search for a value. Returns True or False.
        """
        return self._search_recursive(self.root, value)

    def _search_recursive(self, current_node, value):
        """
        Private recursive helper method to find a value.
        """
        # Base Cases:
        # 1. We reached the end of a branch (node is None)
        # 2. We found the value
        if current_node is None:
            return False
        if current_node.value == value:
            return True

        # Recursive Steps:
        if value < current_node.value:
            # Search the left subtree
            return self._search_recursive(current_node.left, value)
        else: # value > current_node.value
            # Search the right subtree
            return self._search_recursive(current_node.right, value)

    def inorder_traversal(self):
        """
        Prints the tree's values in sorted order (Left, Root, Right).
        """
        print("In-order traversal:")
        self._inorder_helper(self.root)
        print() # Add a newline at the end

    def _inorder_helper(self, node):
        """
        Private recursive helper for in-order traversal.
        """
        if node:
            self._inorder_helper(node.left)
            print(node.value, end=' ')
            self._inorder_helper(node.right)


# --- Example Usage ---
if __name__ == "__main__":
    
    # 1. Create a new BST
    bst = BinarySearchTree()
    
    # 2. Insert values
    # The root will be 50
    values = [50, 30, 70, 20, 40, 60, 80]
    for val in values:
        bst.insert(val)

    # 3. Print the sorted values
    # An in-order traversal of a BST always yields a sorted list.
    bst.inorder_traversal()
    
    # 4. Search for values
    print("Is 40 in the tree?", bst.search(40))
    print("Is 99 in the tree?", bst.search(99))

```

## /C/1d_array_sum.c

```c path="/C/1d_array_sum.c" 
#include <stdio.h>

int main() {
    int n, sum = 0;

    // Ask user for number of elements
    printf("Enter the number of elements in the array: ");
    scanf("%d", &n);

    int arr[n]; // Declare array of size n

    // Input array elements
    printf("Enter the elements of the array:\n");
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
        sum += arr[i]; // Add each element to sum
    }

    // Display the sum
    printf("The sum of the elements is: %d\n", sum);

    return 0;
}

```

## /C/Binary_Search_Tree.c

```c path="/C/Binary_Search_Tree.c" 
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* left;
    struct Node* right;
} Node;

// Create a new node
Node* createNode(int data) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->left = node->right = NULL;
    return node;
}

// Insert a node
Node* insert(Node* root, int data) {
    if (root == NULL) return createNode(data);
    if (data < root->data) root->left = insert(root->left, data);
    else if (data > root->data) root->right = insert(root->right, data);
    return root;
}

// Inorder traversal
void inorder(Node* root) {
    if (root) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

int main() {
    Node* root = NULL;
    root = insert(root, 50);
    insert(root, 30);
    insert(root, 70);
    insert(root, 20);
    insert(root, 40);
    insert(root, 60);
    insert(root, 80);

    printf("Inorder traversal: ");
    inorder(root);
    return 0;
}

```

## /C/Bubble Sort - C

``` path="/C/Bubble Sort - C" 
#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;
    int swapped;

    // Outer loop for passes
    for (i = 0; i < n - 1; i++) {
        swapped = 0;

        // Inner loop for comparisons
        for (j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                // Swap the elements
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = 1;
            }
        }

        // If no swaps happened, array is already sorted
        if (swapped == 0)
            break;
    }
}

int main() {
    int arr[] = {5, 3, 8, 4, 2};
    int n = sizeof(arr) / sizeof(arr[0]);

    bubbleSort(arr, n);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

```

## /C/Bubble_Sort.c

```c path="/C/Bubble_Sort.c" 
#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);

    bubbleSort(arr, n);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

```

## /C/Climbing_Stairs.c

```c path="/C/Climbing_Stairs.c" 
#include<stdio.h>
#include<stdlib.h>


// -----------------------MEMORIZATION----------------------
// int countWays(int n, int dp[]){
//     if(n == 0) return 1;  // Fixed: == instead of =
//     if(n == 1) return 1;
//     if(dp[n] != -1) return dp[n];
//     return dp[n] = countWays(n-1, dp) + countWays(n-2, dp);
// }

// int climbStairs(int n) {
//     // Handle edge case
//     if(n < 0) return 0;
    
//     int* dp = (int*) malloc((n+1) * sizeof(int));
//     if(dp == NULL) {
//         printf("Memory allocation failed!\n");
//         return -1;
//     }
    
//     for(int i = 0; i <= n; i++){
//         dp[i] = -1;
//     }
    
//     int result = countWays(n, dp);
//     free(dp);  // Free allocated memory
//     return result;
// }

// -----------------------TABULATION----------------------

// int climbStairs(int n) {
//     // Handle edge case
//     if(n < 0) return 0;
    
//     int* dp = (int*) malloc((n+1) * sizeof(int));
    
//     dp[0] = 1;
//     dp[1] = 1;
//     for(int i = 2; i<n+1;i++){
//         dp[i] = dp[i-1] + dp[i - 2];
//     }
//     return dp[n];
// }

// -----------------------OPTIMIZING MEMORY----------------------

int climbStairs(int n) {
    // Handle edge case
    if(n < 0) return 0;
    
    int prev2= 1;
    int prev1 = 1;
    for(int i = 2; i<n+1;i++){
        int curr = prev1 + prev2;
        prev2 = prev1;
        prev1 = curr;
    }
    return prev1;
}
int main(){
    printf("Enter the number of stairs: ");
    int n;
    scanf("%d", &n);
    
    int ways = climbStairs(n);
    if(ways >= 0) {
        printf("Number of ways to climb %d stairs: %d\n", n, ways);
    }
    
    return 0;
}
```

## /C/Factorial_using_recursion.c

```c path="/C/Factorial_using_recursion.c" 
#include <stdio.h>

// Recursive function to calculate factorial
int factorial(int n) {
    if (n == 0) return 1;   // Base case
    return n * factorial(n - 1); // Recursive step
}

int main() {
    int num = 5;
    printf("Factorial of %d = %d\n", num, factorial(num));
    return 0;
}

```

## /C/FrogJump.c

```c path="/C/FrogJump.c" 
// Given an integer array height[] where height[i] represents the height of the i-th stair,
// a frog starts from the first stair and wants to reach the top. From any stair i, the frog has two options: 
// it can either jump to the (i+1)th stair or the (i+2)th stair. The cost of a jump is the absolute difference in height between the two stairs. 
// Determine the minimum total cost required for the frog to reach the top.

// Example:

// Input: heights[] = [20, 30, 40, 20] 
// Output: 20
// Explanation:  Minimum cost is incurred when the frog jumps from stair 0 to 1 then 1 to 3:
// jump from stair 0 to 1: cost = |30 - 20| = 10
// jump from stair 1 to 3: cost = |20-30|  = 10
// Total Cost = 10 + 10 = 20
// Input: heights[] = [30, 20, 50, 10, 40]
// Output: 30
// Explanation: Minimum cost will be incurred when frog jumps from stair 0 to 2 then 2 to 4:
// jump from stair 0 to 2: cost = |50 - 30| = 20
// jump from stair 2 to 4: cost = |40-50|  = 10
// Total Cost = 20 + 10 = 30
// Constraints:

// 1 <= height.size() <= 105
// 0 <= height[i]<=104


#include<stdio.h>
#include<stdlib.h>
int min(int a, int b){
    return a>b? b:a;
}
//-------------------------------------------------------MEMORIZATION
//int findMinCost(int heights[],int idx,int dp[]){
//     if(idx == 0) return 0;
//     if(idx == 1) return abs(heights[1] - heights[0]);
//     if(dp[idx] != -1) return dp[idx];
//     dp[idx] = min(findMinCost(heights,idx-1,dp) + abs(heights[idx] - heights[idx-1]), 
//                     findMinCost(heights,idx-2,dp) + abs(heights[idx] - heights[idx-2]));
//     return dp[idx];
// }


// int minCost(int heights[],int size){
//     int *dp = (int*) malloc(size*sizeof(int));
//     for(int i=0; i<size;i++){
//         dp[i] = -1;
//     }
//    int ans = findMinCost(heights,size-1,dp);
//    free(dp);
//    return ans;
// }
//------------------------------------------------------------TABULATION
/*
int minCost(int heights[],int size){
    int *dp = (int*) malloc(size*sizeof(int));
    dp[0] = 0;
    if (size > 1)
    dp[1] = abs(heights[1] - heights[0]);

    for(int i = 2; i<size;i++){
        dp[i] = min(dp[i-1] + abs(heights[i]-heights[i-1]), dp[i-2] + abs(heights[i] - heights[i-2]));
    }
    return dp[size-1];
}*/
//------------------------------------------------------------------OPTIMIZED

int minCost(int heights[],int size){
    
    int prev2 = 0;
    int prev1 = 0;
    if (size > 1)
        prev1 = abs(heights[1] - heights[0]);
    
    // You need to implement the rest of the logic using prev1 and prev2, or remove this function if not needed.
    // The current code below references 'dp', which is not declared in this function.
    // For a space-optimized solution, you can use prev1 and prev2 as follows:

    for(int i = 2; i < size; i++){
        int curr = min(prev1 + abs(heights[i] - heights[i-1]), prev2 + abs(heights[i] - heights[i-2]));
        prev2 = prev1;
        prev1 = curr;
    }
    return (size == 1) ? 0 : prev1;
}

int main(){
    int heights[] = {20,30,40,20};
    printf("Min Cost is %d\n",minCost(heights,4));

}
```

## /C/Insertion.c

```c path="/C/Insertion.c" 
/*
 * C program to insert an element in a specified position in a given array
 */
 
#include <stdio.h>
void main()
{
    int array[100];
    int i, n, x, pos;
 
    printf("Enter the number of elements in the array \n");
    scanf("%d", &n);
    printf("Enter the elements \n");
 
    for (i = 0; i < n; i++)
    {
        scanf("%d", &array[i]);
    }
 
    printf("Input array elements are: \n");
    for (i = 0; i < n; i++)
    {
        printf("%d ", array[i]);
    }
    printf("\nEnter the new element to be inserted: ");
    scanf("%d", &x);
    printf("Enter the position where element is to be inserted: ");
    scanf("%d", &pos);
 
    //shift all elements 1 position forward from the place
    //where element needs to be inserted
    n=n+1;
    for(i = n-1; i >= pos; i--)
        array[i]=array[i-1];
 
    array[pos-1]=x; //Insert the element x on the specified position
 
    //print the new array
    for (i = 0; i < n; i++)
    {
        printf("%d ", array[i]);
    }
}

```

## /C/List-Flattening.c

```c path="/C/List-Flattening.c" 
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
    struct Node* prev;
    struct Node* child;
} Node;

void append(Node* child, Node** tail) {
    Node* curNode;

    (*tail)->next = child;
    child->prev = *tail;

    for (curNode = child; curNode->next != NULL; curNode = curNode->next)
        ;

    *tail = curNode;
}

void flattenList(Node* head, Node** tail) {
    Node* curNode = head;

    while (curNode != NULL) {
        if (curNode->child) {
            append(curNode->child, tail);

            curNode->child = NULL;
        }
        curNode = curNode->next;
    }
}

Node* findTail(Node* head) {
    Node* tail = head;
    while (tail->next != NULL) {
        tail = tail->next;
    }
    return tail;
}

void printList(Node* head) {
    Node* cur = head;
    while (cur != NULL) {
        printf("%d ", cur->data);
        cur = cur->next;
    }
    printf("\n");
}

Node* createNode(int data) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    newNode->data = data;
    newNode->next = NULL;
    newNode->prev = NULL;
    newNode->child = NULL;
    return newNode;
}

int main() {
    Node* head = createNode(1);
    head->next = createNode(2);
    head->next->prev = head;
    head->next->next = createNode(3);
    head->next->next->prev = head->next;

    // Create child list for node 1
    head->child = createNode(4);
    head->child->next = createNode(5);
    head->child->next->prev = head->child;

    // Create child list for node 3
    head->next->next->child = createNode(6);

    // Create child list for node 4
    head->child->child = createNode(7);

    // Find initial tail of top level list
    Node* tail = findTail(head);

    flattenList(head, &tail);

    printList(head);

    return 0;
}

/*

Input:

1 <-> 2 <-> 3
|           |
4 <-> 5     6
|
7


Output :

1 2 3 4 5 6 7

*/


```

## /C/Merge_Sort.c

```c path="/C/Merge_Sort.c" 
#include <stdio.h>
#include <stdlib.h>

void merge(int arr[], int l, int m, int r) {
    int n1 = m - l + 1;
    int n2 = r - m;
    int L[n1], R[n2];

    for (int i = 0; i < n1; i++) L[i] = arr[l + i];
    for (int j = 0; j < n2; j++) R[j] = arr[m + 1 + j];

    int i = 0, j = 0, k = l;
    while (i < n1 && j < n2) {
        if (L[i] <= R[j]) arr[k++] = L[i++];
        else arr[k++] = R[j++];
    }
    while (i < n1) arr[k++] = L[i++];
    while (j < n2) arr[k++] = R[j++];
}

void mergeSort(int arr[], int l, int r) {
    if (l < r) {
        int m = l + (r - l) / 2;
        mergeSort(arr, l, m);
        mergeSort(arr, m + 1, r);
        merge(arr, l, m, r);
    }
}

int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(arr)/sizeof(arr[0]);

    mergeSort(arr, 0, n - 1);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

```

## /C/Queue.c

```c path="/C/Queue.c" 
//circular queue implementation in C using array

#include <stdio.h>
#define MAX 100

typedef struct Queue {
    int arr[MAX];
    int front, rear;
} Queue;

void initQueue(Queue* q) { q->front = q->rear = -1; }

int isEmpty(Queue* q) { return q->front == -1; }
int isFull(Queue* q) { return (q->rear + 1) % MAX == q->front; }

void enqueue(Queue* q, int val) {
    if (isFull(q)) {
        printf("Queue Overflow\n");
        return;
    }
    if (isEmpty(q)) q->front = q->rear = 0;
    else q->rear = (q->rear + 1) % MAX;
    q->arr[q->rear] = val;
}

int dequeue(Queue* q) {
    if (isEmpty(q)) {
        printf("Queue Underflow\n");
        return -1;
    }
    int val = q->arr[q->front];
    if (q->front == q->rear) q->front = q->rear = -1;
    else q->front = (q->front + 1) % MAX;
    return val;
}

int main() {
    Queue q;
    initQueue(&q);

    enqueue(&q, 10);
    enqueue(&q, 20);
    enqueue(&q, 30);

    printf("Dequeued: %d\n", dequeue(&q));
    printf("Dequeued: %d\n", dequeue(&q));

    return 0;
}

```

## /C/Queue_implementation_using_array.c

```c path="/C/Queue_implementation_using_array.c" 
#include <stdio.h>
#define MAX 5

int queue[MAX], front = -1, rear = -1;

// Insert element into queue
void enqueue(int val) {
    if (rear == MAX - 1)
        printf("Queue Overflow\n");
    else {
        if (front == -1) front = 0; // First element
        queue[++rear] = val;
    }
}

// Remove element from queue
int dequeue() {
    if (front == -1 || front > rear) {
        printf("Queue Underflow\n");
        return -1;
    }
    return queue[front++];
}

// Display queue contents
void display() {
    if (front == -1 || front > rear) printf("Queue is empty\n");
    else {
        printf("Queue elements: ");
        for (int i = front; i <= rear; i++)
            printf("%d ", queue[i]);
        printf("\n");
    }
}

int main() {
    enqueue(5);
    enqueue(10);
    enqueue(15);
    display();
    printf("Dequeued: %d\n", dequeue());
    display();
    return 0;
}

```

## /C/Quick_Sort.c

```c path="/C/Quick_Sort.c" 
#include <stdio.h>

void swap(int* a, int* b) {
    int t = *a;
    *a = *b;
    *b = t;
}

int partition(int arr[], int low, int high) {
    int pivot = arr[high]; // pivot
    int i = low - 1;

    for (int j = low; j < high; j++) {
        if (arr[j] <= pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return i + 1;
}

void quickSort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

int main() {
    int arr[] = {10, 7, 8, 9, 1, 5};
    int n = sizeof(arr)/sizeof(arr[0]);

    quickSort(arr, 0, n - 1);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

```

## /C/Recursive_Quick_Sort.c

```c path="/C/Recursive_Quick_Sort.c" 

#include <stdio.h>
void swap(int* a, int* b) 
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
int partition(int arr[], int low, int high)
{
    int pivot = arr[low];
    int i = low;
    int j = high;
    while (i < j) 
    {
        while (arr[i] <= pivot && i <= high - 1) 
		{
            i++;
        }
        while (arr[j] > pivot && j >= low + 1) 
		{
            j--;
        }
        if (i < j)
		{
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[low], &arr[j]);
    return j;
}
void quickSort(int arr[], int low, int high) 
{
	int partitionIndex;
	if (low < high)
	{
		partitionIndex = partition(arr, low, high);
       	quickSort(arr, low, partitionIndex - 1);
       	quickSort(arr, partitionIndex + 1, high);
	}
}
int main() 
{
    int arr[10],i,n;
 	printf("\nEnter How Many Elements You Want?\n");
	scanf("%d",&n);
	printf("\nEnter Array Elements\n");
	for (i = 0; i < n; i++) 
    {
        scanf("%d ", &arr[i]);
    }  
    printf("Original array: ");
    for (i = 0; i < n; i++) 
    {
        printf("%d ", arr[i]);
    }
    quickSort(arr, 0, n - 1);
    printf("\nSorted array: ");
    for (i = 0; i < n; i++) 
    {
        printf("%d ", arr[i]);
    }
    return 0;
}
```

## /C/Reverse_Array.c

```c path="/C/Reverse_Array.c" 
#include <stdio.h>

// Function to reverse array elements in place
void reverseArray(int arr[], int n) {
    int start = 0, end = n - 1, temp;
    while (start < end) {
        // Swap elements at start and end
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    reverseArray(arr, n);

    printf("Reversed Array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}

```

## /C/Sieve_of_Eratosthene.c

```c path="/C/Sieve_of_Eratosthene.c" 
#include <stdio.h>
#include <stdbool.h>

void sieveOfEratosthenes(int n)
{
    bool prime[n + 1]; // Create a boolean array to mark prime numbers
    for (int i = 0; i <= n; i++)
    {
        prime[i] = true; // Initialize all entries as true
    }

    // marking non-prime numbers from 2 to n 
    for (int p = 2; p * p <= n; p++)
    {
        if (prime[p] == true)
        { // If prime[p] is still true, it's a prime number
            for (int i = p * p; i <= n; i += p)
            {
                prime[i] = false; // Mark all multiples of p as non-prime
            }
        }
    }

    // Print all prime numbers
    printf("Prime numbers up to %d are: ", n);
    for (int p = 2; p <= n; p++)
    {
        if (prime[p] == true)
        {
            printf("%d ", p);
        }
    }
    printf("\n");
}

int main()
{
    int n;
    printf("prime to the n: ");
    scanf("%d", &n);

    sieveOfEratosthenes(n);

    return 0;
}
```

## /C/Singly_Linked_List.c

```c path="/C/Singly_Linked_List.c" 
#include <stdio.h>
#include <stdlib.h>

typedef struct Node {
    int data;
    struct Node* next;
} Node;

Node* createNode(int data) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = data;
    node->next = NULL;
    return node;
}

void insertAtEnd(Node** head, int data) {
    Node* node = createNode(data);
    if (*head == NULL) {
        *head = node;
        return;
    }
    Node* temp = *head;
    while (temp->next) temp = temp->next;
    temp->next = node;
}

void display(Node* head) {
    while (head) {
        printf("%d -> ", head->data);
        head = head->next;
    }
    printf("NULL\n");
}

int main() {
    Node* head = NULL;
    insertAtEnd(&head, 10);
    insertAtEnd(&head, 20);
    insertAtEnd(&head, 30);

    display(head);
    return 0;
}

```

## /C/Stack.c

```c path="/C/Stack.c" 
//stack implementation using array in C
#include <stdio.h>
#define MAX 100

typedef struct Stack {
    int arr[MAX];
    int top;
} Stack;

void init(Stack* s) { s->top = -1; }

int isEmpty(Stack* s) { return s->top == -1; }
int isFull(Stack* s) { return s->top == MAX - 1; }

void push(Stack* s, int val) {
    if (isFull(s)) {
        printf("Stack Overflow\n");
        return;
    }
    s->arr[++s->top] = val;
}

int pop(Stack* s) {
    if (isEmpty(s)) {
        printf("Stack Underflow\n");
        return -1;
    }
    return s->arr[s->top--];
}

int peek(Stack* s) {
    if (!isEmpty(s)) return s->arr[s->top];
    return -1;
}

int main() {
    Stack s;
    init(&s);

    push(&s, 10);
    push(&s, 20);
    push(&s, 30);

    printf("Top element: %d\n", peek(&s));
    printf("Popped: %d\n", pop(&s));
    printf("Popped: %d\n", pop(&s));

    return 0;
}

```

## /C/Stack_implementation_Using_array.c

```c path="/C/Stack_implementation_Using_array.c" 
#include <stdio.h>
#define MAX 5

int stack[MAX], top = -1;

// Push element onto stack
void push(int val) {
    if (top == MAX - 1)
        printf("Stack Overflow\n");
    else
        stack[++top] = val;
}

// Pop element from stack
int pop() {
    if (top == -1) {
        printf("Stack Underflow\n");
        return -1;
    }
    return stack[top--];
}

// Display stack contents
void display() {
    if (top == -1) printf("Stack is empty\n");
    else {
        printf("Stack elements: ");
        for (int i = top; i >= 0; i--)
            printf("%d ", stack[i]);
        printf("\n");
    }
}

int main() {
    push(10);
    push(20);
    push(30);
    display();
    printf("Popped: %d\n", pop());
    display();
    return 0;
}

```

## /C/Two sum questions

``` path="/C/Two sum questions" 
#include <stdio.h>

void twoSum(int nums[], int n, int target) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; j < n; j++) {
            if (nums[i] + nums[j] == target) {
                printf("Indices: [%d, %d]\n", i, j);
                return; // Exit after finding the pair
            }
        }
    }
    printf("No solution found.\n");
}

int main() {
    int nums[] = {2, 7, 11, 15};
    int target = 9;
    int n = sizeof(nums) / sizeof(nums[0]);

    twoSum(nums, n, target);
    return 0;
}

```

## /C/array_deletion.c

```c path="/C/array_deletion.c" 
/*
 * [Algorithm] : Array Deletion
 * [Author]    : tanshen-kun (Modified & documented by ChatGPT)
 *
 * Hacktoberfest2025
 */

#include <stdio.h>

// Function to delete element at given position
void array_delete(int arr[], int *size, int pos) {
    // Shift elements left from the position
    for (int i = pos; i < *size - 1; i++) {
        arr[i] = arr[i + 1];
    }
    (*size)--; // Decrease array size
}

// Function to print the array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {1, 2, 3, 4, 4, 5, 6, 7};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("Original Array: ");
    printArray(arr, size);

    int pos;
    printf("Enter position to delete (0 - %d): ", size - 1);
    scanf("%d", &pos);

    // Validate position
    if (pos < 0 || pos >= size) {
        printf("Invalid position! Please enter a value between 0 and %d.\n", size - 1);
        return 1; // Exit program with error
    }

    // Perform deletion
    array_delete(arr, &size, pos);

    printf("Array After Deletion: ");
    printArray(arr, size);

    return 0;
}

```

## /C/array_insertion.c

```c path="/C/array_insertion.c" 
/*
 *
 * [Algorithm] : Array Insertion
 * [Author]    : tanshen-kun (Improved and documented by ChatGPT)
 *
 * Hacktoberfest2025
 */

#include <stdio.h>

// Function to insert an element into the array
void array_insert(int arr[], int *size, int value, int pos) {
    // Shift elements to the right
    for (int i = *size; i > pos; i--) {
        arr[i] = arr[i - 1];
    }

    arr[pos] = value; // Insert new element
    (*size)++;         // Increase size
}

// Function to print array elements
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[50] = {1, 3, 4, 5, 6, 7, 8, 9}; // Initial array
    int size = 8;

    printf("Original Array: ");
    printArray(arr, size);

    int pos, value;

    printf("Enter the position to insert (0 to %d): ", size);
    scanf("%d", &pos);

    // Validate position
    if (pos < 0 || pos > size) {
        printf("Invalid position! Please enter a value between 0 and %d.\n", size);
        return 1;
    }

    printf("Enter the value to insert: ");
    scanf("%d", &value);

    array_insert(arr, &size, value, pos);

    printf("Array After Insertion: ");
    printArray(arr, size);

    return 0;
}

```

## /C/array_manipulation.c

```c path="/C/array_manipulation.c" 
#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

// Function prototypes
void displayArray(int arr[], int size);
int insertElement(int arr[], int size, int element, int position);
int deleteElement(int arr[], int size, int position);
int searchElement(int arr[], int size, int element);
void updateElement(int arr[], int size, int position, int newValue);
void displayMenu();

// Function to display the array
void displayArray(int arr[], int size) {
    if (size == 0) {
        printf("Array is empty.\n");
        return;
    }
    
    printf("Array elements: ");
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

// Function to insert an element at a specific position
int insertElement(int arr[], int size, int element, int position) {
    if (size >= MAX_SIZE) {
        printf("Error: Array is full. Cannot insert element.\n");
        return size;
    }
    
    if (position < 0 || position > size) {
        printf("Error: Invalid position. Position should be between 0 and %d.\n", size);
        return size;
    }
    
    // Shift elements to the right
    for (int i = size; i > position; i--) {
        arr[i] = arr[i - 1];
    }
    
    // Insert the new element
    arr[position] = element;
    size++;
    
    printf("Element %d inserted at position %d successfully.\n", element, position);
    return size;
}

// Function to delete an element at a specific position
int deleteElement(int arr[], int size, int position) {
    if (size == 0) {
        printf("Error: Array is empty. Cannot delete element.\n");
        return size;
    }
    
    if (position < 0 || position >= size) {
        printf("Error: Invalid position. Position should be between 0 and %d.\n", size - 1);
        return size;
    }
    
    int deletedElement = arr[position];
    
    // Shift elements to the left
    for (int i = position; i < size - 1; i++) {
        arr[i] = arr[i + 1];
    }
    
    size--;
    printf("Element %d deleted from position %d successfully.\n", deletedElement, position);
    return size;
}

// Function to search for an element in the array
int searchElement(int arr[], int size, int element) {
    for (int i = 0; i < size; i++) {
        if (arr[i] == element) {
            return i; // Return the index if element is found
        }
    }
    return -1; // Return -1 if element is not found
}

// Function to update an element at a specific position
void updateElement(int arr[], int size, int position, int newValue) {
    if (size == 0) {
        printf("Error: Array is empty. Cannot update element.\n");
        return;
    }
    
    if (position < 0 || position >= size) {
        printf("Error: Invalid position. Position should be between 0 and %d.\n", size - 1);
        return;
    }
    
    int oldValue = arr[position];
    arr[position] = newValue;
    printf("Element at position %d updated from %d to %d successfully.\n", position, oldValue, newValue);
}

// Function to display the menu
void displayMenu() {
    printf("\n=== Array Manipulation Menu ===\n");
    printf("1. Display Array (Traversal)\n");
    printf("2. Insert Element\n");
    printf("3. Delete Element\n");
    printf("4. Search Element\n");
    printf("5. Update Element\n");
    printf("6. Exit\n");
    printf("Enter your choice: ");
}

int main() {
    int arr[MAX_SIZE];
    int size = 0;
    int choice, element, position, newValue, searchResult;
    
    printf("=== Array Manipulation Program in C ===\n");
    printf("Maximum array size: %d\n", MAX_SIZE);
    
    // Initialize array with some sample data (optional)
    printf("\nDo you want to initialize the array with sample data? (1 for Yes, 0 for No): ");
    int initChoice;
    scanf("%d", &initChoice);
    
    if (initChoice == 1) {
        int sampleData[] = {10, 20, 30, 40, 50};
        int sampleSize = sizeof(sampleData) / sizeof(sampleData[0]);
        
        for (int i = 0; i < sampleSize; i++) {
            arr[i] = sampleData[i];
        }
        size = sampleSize;
        printf("Array initialized with sample data.\n");
        displayArray(arr, size);
    }
    
    while (1) {
        displayMenu();
        scanf("%d", &choice);
        
        switch (choice) {
            case 1: // Traversal - Display Array
                printf("\n--- Array Traversal ---\n");
                displayArray(arr, size);
                break;
                
            case 2: // Insertion
                printf("\n--- Insert Element ---\n");
                printf("Enter element to insert: ");
                scanf("%d", &element);
                printf("Enter position (0 to %d): ", size);
                scanf("%d", &position);
                size = insertElement(arr, size, element, position);
                break;
                
            case 3: // Deletion
                printf("\n--- Delete Element ---\n");
                if (size == 0) {
                    printf("Array is empty. Nothing to delete.\n");
                } else {
                    displayArray(arr, size);
                    printf("Enter position to delete (0 to %d): ", size - 1);
                    scanf("%d", &position);
                    size = deleteElement(arr, size, position);
                }
                break;
                
            case 4: // Searching
                printf("\n--- Search Element ---\n");
                if (size == 0) {
                    printf("Array is empty. Nothing to search.\n");
                } else {
                    printf("Enter element to search: ");
                    scanf("%d", &element);
                    searchResult = searchElement(arr, size, element);
                    
                    if (searchResult != -1) {
                        printf("Element %d found at position %d.\n", element, searchResult);
                    } else {
                        printf("Element %d not found in the array.\n", element);
                    }
                }
                break;
                
            case 5: // Update
                printf("\n--- Update Element ---\n");
                if (size == 0) {
                    printf("Array is empty. Nothing to update.\n");
                } else {
                    displayArray(arr, size);
                    printf("Enter position to update (0 to %d): ", size - 1);
                    scanf("%d", &position);
                    printf("Enter new value: ");
                    scanf("%d", &newValue);
                    updateElement(arr, size, position, newValue);
                }
                break;
                
            case 6: // Exit
                printf("\nThank you for using Array Manipulation Program!\n");
                printf("Goodbye!\n");
                exit(0);
                
            default:
                printf("Invalid choice! Please enter a number between 1 and 6.\n");
        }
        
        printf("\nPress Enter to continue...");
        getchar(); // Clear the input buffer
        getchar(); // Wait for Enter key
    }
    
    return 0;
}

```

## /C/array_searching.c

```c path="/C/array_searching.c" 
/*
 *
 * [Algorithm]: Array Searching
 * [author]: tanshen-kun
 *
 * Hacktoberfest2025
 */
#include <stdio.h>

int array_search(int arr[], int size, int key) {
  for (int i = 0; i < size; i++) {
    if (arr[i] == key) {
      return i;
    }
  }
  // if not found
  return -1;
}

void printArray(int arr[], int size) {
  for (int i = 0; i < size; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
}

int main() {
  int arr[] = {12, 1, 42, 12, 34, 12, 56, 2, 1};
  int size = sizeof(arr) / sizeof(arr[0]);

  printf("Array : ");
  printArray(arr, size);

  int key;
  printf("Enter the key to search : ");
  scanf("%d", &key);

  int index = array_search(arr, size, key);
  if (index != -1) {
    printf("Element found at index %d\n", index);
  } else {
    printf("Element not found!\n");
  }

  return 0;
}

```

## /C/array_traversal.c

```c path="/C/array_traversal.c" 
/*
 *
 * [Algorithm]: Array Traversal
 * [author]: tanshen-kun
 *
 * Hacktoberfest2025
 */
#include <stdio.h>

void array_traversal(int arr[], int size) {
  printf("Array Elements : ");
  for (int i = 0; i < size; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
}

int main() {
  int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  int size = sizeof(arr) / sizeof(arr[0]);

  array_traversal(arr, size);

  return 0;
}

```

## /C/array_update.c

```c path="/C/array_update.c" 
/*
 * [Algorithm]: Array Update
 * [author]: tanshen-kun
 *
 * Hacktoberfest2025
 */
#include <stdio.h>

void array_update(int arr[], int pos, int value) { 
	arr[pos] = value; 
}

void printArray(int arr[], int size) {
  for (int i = 0; i < size; i++) {
    printf("%d ", arr[i]);
  }
  printf("\n");
}

int main() {
  int arr[] = {1, 2, 3, 4, 4, 6, 7, 8};
  int size = sizeof(arr) / sizeof(arr[0]);

  printArray(arr, size);

  int pos;
  printf("Enter the postion to update(0-%d) : ", size - 1);
  scanf("%d", &pos);

  int value;
  printf("Enter the value to update : ");
  scanf("%d", &value);

  array_update(arr, pos, value);

  printf("Array After update : ");
  printArray(arr, size);

  return 0;
}

```

## /C/binarysearch.c

```c path="/C/binarysearch.c" 
#include <stdio.h>

int binary(int low,int high,int target,int arr[])
{
    int mid = (low+high)/2;
    if (low>high)
    return -1;
    if (arr[mid]==target)
    return mid;
    else if (arr[mid]<target)
    return binary(mid+1,high,target,arr);
    else
    return binary(low,mid-1,target,arr);
}

int main()
{
    int n;
    int target;
    int result;
    printf("Enter the length of array\n");
    scanf("%d",&n);
    int arr[n];
    printf("Enter the elements of array\n");
    for (int i=0;i<n;i++)
    scanf("%d",&arr[i]);
    
    for (int i=0;i<n-1;i++)
    {
        for (int j=0;j<n-i-1;j++)
        {
            if (arr[j]>arr[j+1])
            {
                int temp=arr[j];
                arr[j]=arr[j+1];
                arr[j+1]=temp;
            }
        }
    }
    
    for (int i=0;i<n;i++)
    printf("%d ",arr[i]);
    
    printf("\n");
    printf ("Enter which element to search\n");
    scanf("%d",&target);

    result = binary(0,n-1,target,arr);

    if(result==-1)
    printf("The element is not found in the array\n");

    else 
    printf("The element is found in the array at the index %d\n",result);
}
```

## /C/bubble_sorting.c

```c path="/C/bubble_sorting.c" 
#include <stdio.h>

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

int main() {
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);

    bubbleSort(arr, n);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    return 0;
}

```

## /C/bubblesort.c

```c path="/C/bubblesort.c" 
#include <stdio.h>

// Created a Function to sort array using Bubble sort
void bubbleSort(int arr[], int n) {
    int temp;
    for (int i = 0; i < n-1; i++) { 
        for (int j = 0; j < n-i-1; j++) {  // Last i elements are already sorted

            // If the cur element is greater than the next performing swap

            if (arr[j] > arr[j+1]) {
                // Swapping using a temp
                temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
}

// Created a function to print an array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {64, 25, 12, 22, 11};
    int n = sizeof(arr)/sizeof(arr[0]);

    printf("Unsorted array: \n");
    printArray(arr, n);

    bubbleSort(arr, n);

    printf("Sorted array: \n");
    printArray(arr, n);

    return 0;
}

```

## /C/circular_queue.c

```c path="/C/circular_queue.c" 

```

## /C/count_set_bits.c

```c path="/C/count_set_bits.c" 
// Count number of set bits in an integer - Nithin
#include <stdio.h>

int countSetBits(int n) {
    int count = 0;
    while (n) {
        n &= (n - 1); // Removes the last set bit
        count++;
    }
    return count;
}

int main() {
    int num = 29; // binary 11101 → 4 set bits
    printf("Number of set bits in %d: %d\n", num, countSetBits(num));
    return 0;
}

```

## /C/deadlock_avoidance.c

```c path="/C/deadlock_avoidance.c" 
#include <stdio.h>
#include <stdbool.h>

#define P 5 
#define R 3 


bool isSafe(int processes[], int avail[], int max[][R], int allot[][R]) {
    int need[P][R];
    for (int i = 0; i < P; i++)
        for (int j = 0; j < R; j++)
            need[i][j] = max[i][j] - allot[i][j];

    bool finish[P] = {0};
    int safeSeq[P];
    int work[R];
    for (int i = 0; i < R; i++)
        work[i] = avail[i];

    int count = 0;
    while (count < P) {
        bool found = false;
        for (int p = 0; p < P; p++) {
            if (!finish[p]) {
                int j;
                for (j = 0; j < R; j++)
                    if (need[p][j] > work[j])
                        break;

                if (j == R) {
                    for (int k = 0; k < R; k++)
                        work[k] += allot[p][k];
                    safeSeq[count++] = p;
                    finish[p] = true;
                    found = true;
                }
            }
        }
        if (!found) {
            printf("System is not in safe state\n");
            return false;
        }
    }
    printf("System is in safe state.\nSafe sequence is: ");
    for (int i = 0; i < P; i++)
        printf("%d ", safeSeq[i]);
    printf("\n");
    return true;
}


int main() {
    int processes[] = {0, 1, 2, 3, 4};

    int avail[] = {3, 3, 2}; 

    int max[][R] = {{7, 5, 3},
                    {3, 2, 2},
                    {9, 0, 2},
                    {2, 2, 2},
                    {4, 3, 3}};

    int allot[][R] = {{0, 1, 0},
                      {2, 0, 0},
                      {3, 0, 2},
                      {2, 1, 1},
                      {0, 0, 2}};

    isSafe(processes, avail, max, allot);

    return 0;
}

```

## /C/fibonacci.c

```c path="/C/fibonacci.c" 
#include <stdio.h>

int fib(int n)
{
    if (n <= 2)
    return 1;
    return fib(n-1)+fib(n-2);
}

int main()
{
    int n;
    printf ("Enter which term of fibonacci series\n");
    scanf("%d",&n);
    printf("%d\n",fib (n));
}
```

## /C/file_handling_with_linear_search.c

```c path="/C/file_handling_with_linear_search.c" 
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct student
{
    char name[20];
    char class[10];
}record;
record std[100];
int read_file(record *a)
{
    int i=0;
    FILE *fp;
    if((fp=fopen("student.txt","r"))!=NULL)
    {
        while(!feof(fp))
        {
            fscanf(fp,"%s%s",a[i].name,a[i].class);
            i++;
        }
    }
    return (i-1);
}
void l_search(record *a,int n,char name[20])
{
    int i;
    for(i=0;i<n;i++)
    {
        if(strcmp(a[i].name,name)==0)
        {
            printf("\nName=%s\nClass=%s\n",a[i].name,a[i].class);
            break;
        }
    }
    if(i==n)
        printf("\nStudent %s is not in the list\n",name);
}
int main()
{
    char name[20];
    int n;
    n=read_file(std);
    printf("\nEnter Student name\n");
    gets(name);//sacnf("%s",name);
    l_search(std,n,name);
    return 0;
}
```

## /C/floyd_warshall.c

```c path="/C/floyd_warshall.c" 
#include <stdio.h>
#define V 4
#define INF 99999  // A large number representing infinity

// Floyd-Warshall algorithm to find shortest paths between all pairs
void floydWarshall(int graph[V][V]) {
    int dist[V][V];

    // Initialize distance matrix same as input graph
    for (int i = 0; i < V; i++)
        for (int j = 0; j < V; j++)
            dist[i][j] = graph[i][j];

    // Update distances using intermediate vertices
    for (int k = 0; k < V; k++) {
        for (int i = 0; i < V; i++) {
            for (int j = 0; j < V; j++) {
                // If path i → k → j is shorter than i → j, update it
                if (dist[i][k] + dist[k][j] < dist[i][j])
                    dist[i][j] = dist[i][k] + dist[k][j];
            }
        }
    }

    // Print the final distance matrix
    printf("Shortest distances between every pair of vertices:\n");
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < V; j++) {
            if (dist[i][j] == INF)
                printf("%7s", "INF");
            else
                printf("%7d", dist[i][j]);
        }
        printf("\n");
    }
}

int main() {
    // Example graph represented as adjacency matrix
    int graph[V][V] = {
        {0,   5,  INF, 10},
        {INF, 0,   3, INF},
        {INF, INF, 0,   1},
        {INF, INF, INF, 0}
    };

    floydWarshall(graph);
    return 0;
}

```

## /C/gcd.c

```c path="/C/gcd.c" 
#include <stdio.h>

int gcd(int a , int b)
{
    if (a%b==0)
    return b;
    else 
    return gcd(b,a%b);
}
int main()
{
    int a,b;
    printf("Enter two numbers\n");
    scanf("%d %d",&a,&b);
    if (b>a)
    {
        a=a+b;
        b=a-b;
        a=a-b;
    }
    printf("The gcd of %d and %d is %d\n",a,b,gcd(a,b));
}
```

## /C/graphs/graph_bfs

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/C/graphs/graph_bfs

## /C/graphs/graph_bfs.c

```c path="/C/graphs/graph_bfs.c" 
#include <stdio.h>
#define MAX 10

int queue[MAX], front = -1, rear = -1;
int visited[MAX];

// Enqueue function
void enqueue(int v) {
    if (rear == MAX - 1)
        printf("Queue overflow\n");
    else {
        if (front == -1)
            front = 0;
        queue[++rear] = v;
    }
}

// Dequeue function
int dequeue() {
    if (front == -1 || front > rear)
        return -1;
    return queue[front++];
}

// BFS function
void bfs(int adj[MAX][MAX], int n, int start) {
    int i, node;
    for (i = 0; i < n; i++)
        visited[i] = 0;

    enqueue(start);
    visited[start] = 1;

    printf("BFS Traversal: ");

    while ((node = dequeue()) != -1) {
        printf("%d ", node);

        for (i = 0; i < n; i++) {
            if (adj[node][i] == 1 && visited[i] == 0) {
                enqueue(i);
                visited[i] = 1;
            }
        }
    }
    printf("\n");
}

// Main function
int main() {
    int n, i, j, start;
    int adj[MAX][MAX];

    printf("Enter number of vertices: ");
    scanf("%d", &n);

    printf("Enter adjacency matrix:\n");
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++)
            scanf("%d", &adj[i][j]);

    printf("Enter starting vertex (0 - %d): ", n - 1);
    scanf("%d", &start);

    bfs(adj, n, start);

    return 0;
}

```

## /C/helloworld.c

```c path="/C/helloworld.c" 
#include <stdio.h>

int main() {
    printf("Hello, World!\n");
    return 0;
}

```

## /C/insertion_sort_using_rand_function.c

```c path="/C/insertion_sort_using_rand_function.c" 
#include<stdio.h>
#include<stdlib.h>

void generate(int a[], int n)
{
	int i;
	for (i=0; i<n; i++)
		a[i]=rand()%100;
}

void display(int a[], int n)
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("%d\t",a[i]);
	}
	printf("\n");
}

void insertionsort(int a[], int n)
{
	int i, temp, j;
	for(i=1;i<=n-1;i++)
	{
		temp=a[i];
		j=i-1;
		while(temp<a[j] && j>=0)
		{
			a[j+1]=a[j];
			j--;
		}
		a[j+1]=temp;
	}
}
int main()
{
	int size, arr[10];
	printf("\nEnter How Many Elements You Want?\n");
	scanf("%d",&size);
	generate(arr, size);
	printf("\nGiven Array Before Sort\n");
	display(arr,size);
	insertionsort(arr,size);
	printf("\nGiven Array After Sort\n");
	display(arr,size);
	return(0);
}
```

## /C/kadane.c

```c path="/C/kadane.c" 
/*Problem Statement:
                 We are given with an array and we need to find the largest contiguous subarray sum,
                 which can be done using Kadane’s algorithm efficiently.

Key Points:
           Kadane’s Algorithm works by iterating through the array once (O(n) time complexity), which makes it efficient.
          The algorithm maintains a running sum (current_sum) and updates the maximum sum (max_sum) when a larger subarray sum is found.               
*/
#include <stdio.h>
#include <limits.h>

int main()
{
    int n;
    scanf("%d", &n);

    int arr[n];

    for (int i = 0; i < n; i++)
        scanf("%d", &arr[i]);

    int max_sum = INT_MIN, current_sum = 0;

    for (int i = 0; i < n; i++)
    {

        current_sum += arr[i];

        if (max_sum < current_sum)
            max_sum = current_sum;

        if (current_sum < 0)
            current_sum = 0;
    }

    printf("%d ", max_sum);

    return 0;
}
```

## /C/leastCommonSubsequence.c

```c path="/C/leastCommonSubsequence.c" 
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int max(int a, int b){
    return a > b ? a : b ;
}
/*
int findLCS(char *s1, char *s2, int i, int j){
    if(i <0 || j <0) return 0;

    if(s1[i] == s2[j]){
        return 1 + findLCS(s1,s2,i-1,j-1);
    }
    return max(findLCS(s1,s2,i-1,j),findLCS(s1,s2,i,j-1));
}

int longestCommonSubsequence(char* text1, char* text2) {
    int i = strlen(text1);
    int j = strlen(text2);

    return findLCS(text1,text2,i-1,j-1);
}
*/


/*-------------MEMOIZATION----------------*/
/*
int findLCS(char*s1,char*s2,int i,int j,int**dp){
    if(i < 0 || j < 0) return 0;
    if(dp[i][j] != -1) return dp[i][j];

    if(s1[i] == s2[i]){
        return dp[i][j] = 1 + findLCS(s1,s2,i-1,j-1,dp);
    }
    return dp[i][j] = max(findLCS(s1,s2,i-1,j,dp),findLCS(s1,s2,i,j-1,dp));
}

int longestCommonSubsequence(char* text1, char* text2){
    int m = strlen(text1);
    int n = strlen(text2);

    int **dp = (int**) malloc(m*sizeof(int*));

    for(int i = 0; i<m;i++){
        dp[i] = (int*) malloc(n*sizeof(int));

        for(int j = 0; j<n;j++){
            dp[i][j] = -1;
        }
    }
    return findLCS(text1,text2,m-1,n-1,dp);
}*/

/*----------Tabulation----------*/
// int longestCommonSubsequence(char* text1, char* text2){
//     int m = strlen(text1);
//     int n = strlen(text2);

//     int **dp = (int**) malloc((m+1)*sizeof(int*));

//     for(int i = 0; i<m+1;i++){
//         dp[i] = (int*) malloc((n+1)*sizeof(int));
//     }
//     for(int i = 0; i<m+1;i++) dp[i][0] = 0;
//     for(int j = 0; j<n+1;j++) dp[0][j] = 0;
    
//     for(int i = 1; i<m+1; i++){
//         for(int j = 1; j<n+1;j++){
//             if(text1[i] == text2[j]) dp[i][j] = 1 + dp[i-1][j-1];
//             else dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
//         }
//     }
//     return dp[m][n];
// }



//optimized

int longestCommonSubsequence(char *s, char *t) {
    int n = strlen(s);
    int m = strlen(t);

    // allocate memory for two 1D arrays
    int *prev = (int*) calloc(m + 1, sizeof(int));
    int *cur  = (int*) calloc(m + 1, sizeof(int));

    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= m; j++) {
            if (s[i - 1] == t[j - 1])
                cur[j] = 1 + prev[j - 1];
            else
                cur[j] = max(prev[j], cur[j - 1]);
        }

        // copy cur into prev
        for (int j = 0; j <= m; j++) {
            prev[j] = cur[j];
        }
    }

    int result = prev[m];

    // free allocated memory
    free(prev);
    free(cur);

    return result;
}

int main(){
    char s1[] = "abcde";
    char s2[] = "ace";
    printf("%d",longestCommonSubsequence(s1,s2));

}
```

## /C/linear_search_with_rand_function.c

```c path="/C/linear_search_with_rand_function.c" 

#include<stdio.h>
#include<stdlib.h>
void generate(int *a, int n)
{
	int i;
	for (i=0; i<n; i++)
		a[i]=rand()%100;
}
void display(int *a, int n)
{
	int i;
	for(i=0;i<n;i++)
	{
		printf("%d\t",a[i]);
	}
	printf("\n");
}
void linear_search(int *a, int n, int key)
{
	int i, flag=0;
	for(i=0;i<n;i++)
	{
		if(a[i]==key)
		{
			flag=1;
			break;
		}
	}
	if(flag==1)
	{
		printf("\nSearch is success! and %d is found at %d position\n",key,i+1);
	}
	else
	{
		printf("%d is not found!\n",key);
	}
}
int main()
{
	int size, arr[10], key;
	printf("\nHow Many Elements You Want?\n");
	scanf("%d",&size);
	generate(arr, size);
	printf("\nGiven Array Is::\n");
	display(arr, size);
	printf("\nEnter The Element To Search!\n");
	scanf("%d",&key);
	linear_search(arr, size, key);
	return(0);
}
```

## /C/longest_word_length.c

```c path="/C/longest_word_length.c" 
#include <stdio.h>
#include <string.h>
int length(char str[])
{
    int maxlen=0;
    int curr=0;

    int len = strlen(str);
    if (str[len-1] == '\n') 
    str[len-1] = '\0';

    for (int i=0;str[i]!='\0';i++)
    {
        if (str[i]!=' ')
        curr++;
        else
        {
            if(curr>maxlen)
            maxlen=curr;
            curr=0;
        }
        if (curr > maxlen)
        maxlen = curr;
    }
    return maxlen;
}

int main()
{
    char str[100];
    printf("Enter the string\n");
    fgets(str,sizeof(str),stdin);
    printf("%d\n",length(str));
}
```

## /C/majority_element.c

```c path="/C/majority_element.c" 
// majority_element.c
// Find the majority element in an array using Boyer-Moore Voting Algorithm
#include <stdio.h>

int findMajorityElement(int arr[], int n) {
    int count = 0, candidate = -1;
    for (int i = 0; i < n; i++) {
        if (count == 0) {
            candidate = arr[i];
            count = 1;
        } else if (arr[i] == candidate) {
            count++;
        } else {
            count--;
        }
    }
    // Verify candidate
    count = 0;
    for (int i = 0; i < n; i++) {
        if (arr[i] == candidate) count++;
    }
    if (count > n / 2) return candidate;
    return -1;
}

int main() {
    int arr[] = {2, 2, 1, 1, 2, 2, 2};
    int n = sizeof(arr) / sizeof(arr[0]);
    int result = findMajorityElement(arr, n);
    if (result != -1)
        printf("Majority element is %d\n", result);
    else
        printf("No majority element found.\n");
    return 0;
}

```

## /C/matrix_multiplication.c

```c path="/C/matrix_multiplication.c" 
#include <stdio.h>

#define R1 2 // Row of first matrix
#define C1 3 // Column of first matrix (must match R2)
#define R2 3 // Row of second matrix
#define C2 2 // Column of second matrix

void multiply_matrices(int mat1[R1][C1], int mat2[R2][C2], int res[R1][C2]) {
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            res[i][j] = 0;
            for (int k = 0; k < C1; k++) {
                res[i][j] += mat1[i][k] * mat2[k][j];
            }
        }
    }
}

void print_matrix(int mat[R1][C2]) {
    for (int i = 0; i < R1; i++) {
        for (int j = 0; j < C2; j++) {
            printf("%d\t", mat[i][j]);
        }
        printf("\n");
    }
}

// Example
int main() {
    int A[R1][C1] = { {1, 2, 3}, {4, 5, 6} };
    int B[R2][C2] = { {7, 8}, {9, 10}, {11, 12} };
    int C[R1][C2];

    multiply_matrices(A, B, C);
    
    printf("Resultant Matrix (C):\n");
    print_matrix(C);

    return 0;
}
```

## /C/mini_http_cache_server.c

```c path="/C/mini_http_cache_server.c" 
/* mini_http_cache_server.c
 *
 * Single-file complex C program:
 * - Non-blocking TCP accept + poll() event loop
 * - Thread pool (fixed worker threads)
 * - Simple HTTP/1.0 GET handling
 * - In-memory LRU cache for file contents (configurable max bytes)
 * - Tiny memory arena for per-request allocations
 * - Minimal MIME type detection
 *
 * Compile:
 *   gcc -O2 -pthread mini_http_cache_server.c -o mini_http_cache_server
 *
 * Run:
 *   ./mini_http_cache_server <port> <www-root> <cache-bytes>
 *
 * Example:
 *   ./mini_http_cache_server 8080 ./www 50_000_000
 */

#define _GNU_SOURCE
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <unistd.h>

/*** Configuration ***/
#define MAX_EVENTS 1024
#define BACKLOG 128
#define WORKER_THREADS 8
#define REQ_BUF_SIZE 8192
#define CACHE_BUCKETS 4096

/*** Utilities ***/
static void die(const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);
    exit(EXIT_FAILURE);
}

static int set_nonblocking(int fd) {
    int flags = fcntl(fd, F_GETFL, 0);
    if (flags == -1) return -1;
    return fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

static char *now_str() {
    static __thread char buf[64];
    time_t t = time(NULL);
    struct tm tm;
    localtime_r(&t, &tm);
    strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &tm);
    return buf;
}

static void log_info(const char *fmt, ...) {
    va_list ap; va_start(ap, fmt);
    fprintf(stderr, "[%s] INFO: ", now_str());
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    va_end(ap);
}

static void log_err(const char *fmt, ...) {
    va_list ap; va_start(ap, fmt);
    fprintf(stderr, "[%s] ERROR: ", now_str());
    vfprintf(stderr, fmt, ap);
    fprintf(stderr, "\n");
    va_end(ap);
}

/*** Simple memory arena for per-request allocations ***/
typedef struct {
    char *buf;
    size_t cap;
    size_t used;
} arena_t;

static void arena_init(arena_t *a, size_t cap) {
    a->buf = malloc(cap);
    a->cap = cap;
    a->used = 0;
}

static void arena_free(arena_t *a) {
    free(a->buf);
    a->buf = NULL;
    a->cap = 0;
    a->used = 0;
}

static void *arena_alloc(arena_t *a, size_t n) {
    if (a->used + n > a->cap) return NULL;
    void *p = a->buf + a->used;
    a->used += n;
    return p;
}

/*** LRU cache implementation for file contents ***/

typedef struct cache_entry {
    // key -> filepath strdup'ed
    char *key;
    void *data;
    size_t size;
    // doubly-linked list pointers for LRU
    struct cache_entry *prev, *next;
    struct cache_entry *hash_next; // chaining in hash bucket
    uint64_t last_access; // monotonic counter
} cache_entry_t;

typedef struct {
    cache_entry_t **buckets;
    size_t nbuckets;
    cache_entry_t *head; // most recently used
    cache_entry_t *tail; // least recently used
    size_t total_bytes;
    size_t max_bytes;
    pthread_mutex_t lock;
    uint64_t tick;
} cache_t;

static uint64_t hash_fn(const char *s) {
    // simple FNV-1a 64-bit
    uint64_t h = 1469598103934665603ULL;
    while (*s) {
        h ^= (unsigned char)*s++;
        h *= 1099511628211ULL;
    }
    return h;
}

static cache_t *cache_create(size_t nbuckets, size_t max_bytes) {
    cache_t *c = calloc(1, sizeof(cache_t));
    c->buckets = calloc(nbuckets, sizeof(cache_entry_t *));
    c->nbuckets = nbuckets;
    c->max_bytes = max_bytes;
    pthread_mutex_init(&c->lock, NULL);
    c->head = c->tail = NULL;
    c->total_bytes = 0;
    c->tick = 1;
    return c;
}

static void cache_evict_one(cache_t *c) {
    // Remove tail (least recently used)
    if (!c->tail) return;
    cache_entry_t *e = c->tail;
    // unlink from LRU list
    if (e->prev) e->prev->next = NULL;
    c->tail = e->prev;
    if (!c->tail) c->head = NULL;
    // remove from hash bucket
    uint64_t h = hash_fn(e->key) % c->nbuckets;
    cache_entry_t *cur = c->buckets[h], *prev = NULL;
    while (cur) {
        if (cur == e) {
            if (prev) prev->hash_next = cur->hash_next;
            else c->buckets[h] = cur->hash_next;
            break;
        }
        prev = cur;
        cur = cur->hash_next;
    }
    c->total_bytes -= e->size;
    free(e->data);
    free(e->key);
    free(e);
}

static void cache_touch(cache_t *c, cache_entry_t *e) {
    // move to head (most recently used)
    if (c->head == e) return;
    // unlink
    if (e->prev) e->prev->next = e->next;
    if (e->next) e->next->prev = e->prev;
    if (c->tail == e) c->tail = e->prev;
    // put at head
    e->prev = NULL;
    e->next = c->head;
    if (c->head) c->head->prev = e;
    c->head = e;
    if (!c->tail) c->tail = e;
    e->last_access = ++c->tick;
}

static cache_entry_t *cache_lookup_locked(cache_t *c, const char *key) {
    uint64_t h = hash_fn(key) % c->nbuckets;
    cache_entry_t *e = c->buckets[h];
    while (e) {
        if (strcmp(e->key, key) == 0) {
            cache_touch(c, e);
            return e;
        }
        e = e->hash_next;
    }
    return NULL;
}

static void cache_put_locked(cache_t *c, const char *key, void *data, size_t size) {
    if (size > c->max_bytes) {
        // Too big to cache
        free(data);
        return;
    }
    // evict until there's room
    while (c->total_bytes + size > c->max_bytes) {
        cache_evict_one(c);
    }
    cache_entry_t *e = malloc(sizeof(cache_entry_t));
    e->key = strdup(key);
    e->data = data;
    e->size = size;
    e->prev = NULL; e->next = c->head;
    e->hash_next = NULL;
    e->last_access = ++c->tick;
    if (c->head) c->head->prev = e;
    c->head = e;
    if (!c->tail) c->tail = e;
    // insert into hash bucket
    uint64_t h = hash_fn(key) % c->nbuckets;
    e->hash_next = c->buckets[h];
    c->buckets[h] = e;
    c->total_bytes += size;
}

static void cache_get(cache_t *c, const char *key, void **out_data, size_t *out_size) {
    pthread_mutex_lock(&c->lock);
    cache_entry_t *e = cache_lookup_locked(c, key);
    if (e) {
        *out_data = e->data;
        *out_size = e->size;
    } else {
        *out_data = NULL;
        *out_size = 0;
    }
    pthread_mutex_unlock(&c->lock);
}

static void cache_put(cache_t *c, const char *key, void *data, size_t size) {
    pthread_mutex_lock(&c->lock);
    cache_put_locked(c, key, data, size);
    pthread_mutex_unlock(&c->lock);
}

/*** Simple thread pool + connection dispatch ***/
typedef struct conn_task {
    int fd;
    struct conn_task *next;
} conn_task_t;

typedef struct {
    conn_task_t *head, *tail;
    pthread_mutex_t lock;
    pthread_cond_t cond;
    bool stopping;
} task_queue_t;

static void task_queue_init(task_queue_t *q) {
    q->head = q->tail = NULL;
    pthread_mutex_init(&q->lock, NULL);
    pthread_cond_init(&q->cond, NULL);
    q->stopping = false;
}

static void task_queue_push(task_queue_t *q, int fd) {
    conn_task_t *t = malloc(sizeof(conn_task_t));
    t->fd = fd; t->next = NULL;
    pthread_mutex_lock(&q->lock);
    if (q->tail) q->tail->next = t;
    else q->head = t;
    q->tail = t;
    pthread_cond_signal(&q->cond);
    pthread_mutex_unlock(&q->lock);
}

static int task_queue_pop(task_queue_t *q) {
    pthread_mutex_lock(&q->lock);
    while (!q->head && !q->stopping) {
        pthread_cond_wait(&q->cond, &q->lock);
    }
    if (q->stopping && !q->head) {
        pthread_mutex_unlock(&q->lock);
        return -1;
    }
    conn_task_t *t = q->head;
    q->head = t->next;
    if (!q->head) q->tail = NULL;
    int fd = t->fd;
    free(t);
    pthread_mutex_unlock(&q->lock);
    return fd;
}

static void task_queue_stop(task_queue_t *q) {
    pthread_mutex_lock(&q->lock);
    q->stopping = true;
    pthread_cond_broadcast(&q->cond);
    pthread_mutex_unlock(&q->lock);
}

/*** Minimal HTTP handling ***/

typedef struct {
    int fd;
    char method[8];
    char path[1024];
    char version[32];
} http_req_t;

static int http_parse_request(const char *buf, http_req_t *req) {
    // Very minimal parsing: METHOD SP PATH SP VERSION CRLF
    // e.g. "GET /index.html HTTP/1.1\r\n"
    const char *p = buf;
    if (sscanf(p, "%7s %1023s %31s", req->method, req->path, req->version) < 2) return -1;
    return 0;
}

static const char *guess_mime(const char *path) {
    const char *ext = strrchr(path, '.');
    if (!ext) return "application/octet-stream";
    if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) return "text/html";
    if (strcmp(ext, ".css") == 0) return "text/css";
    if (strcmp(ext, ".js") == 0) return "application/javascript";
    if (strcmp(ext, ".png") == 0) return "image/png";
    if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) return "image/jpeg";
    if (strcmp(ext, ".gif") == 0) return "image/gif";
    if (strcmp(ext, ".svg") == 0) return "image/svg+xml";
    if (strcmp(ext, ".json") == 0) return "application/json";
    if (strcmp(ext, ".txt") == 0) return "text/plain";
    return "application/octet-stream";
}

/*** Server global state ***/
static cache_t *global_cache = NULL;
static char *www_root = NULL;
static task_queue_t global_queue;

/*** Worker logic: handle connection on fd ***/
static void handle_client(int fd) {
    arena_t arena;
    arena_init(&arena, 16 * 1024); // small per-request arena
    char buf[REQ_BUF_SIZE];
    ssize_t n = recv(fd, buf, sizeof(buf) - 1, 0);
    if (n <= 0) {
        close(fd);
        arena_free(&arena);
        return;
    }
    buf[n] = '\0';
    http_req_t req = { .fd = fd };
    if (http_parse_request(buf, &req) != 0) {
        // bad request
        const char *resp = "HTTP/1.0 400 Bad Request\r\nContent-Length:11\r\n\r\nBad Request";
        send(fd, resp, strlen(resp), 0);
        close(fd);
        arena_free(&arena);
        return;
    }
    // Only support GET
    if (strcmp(req.method, "GET") != 0) {
        const char *resp = "HTTP/1.0 405 Method Not Allowed\r\nContent-Length:18\r\n\r\nMethod Not Allowed";
        send(fd, resp, strlen(resp), 0);
        close(fd);
        arena_free(&arena);
        return;
    }
    // Prevent path traversal
    char clean_path[2048];
    if (strcmp(req.path, "/") == 0) strcpy(clean_path, "/index.html");
    else strncpy(clean_path, req.path, sizeof(clean_path)-1);
    clean_path[sizeof(clean_path)-1] = '\0';
    if (strstr(clean_path, "..")) {
        const char *resp = "HTTP/1.0 403 Forbidden\r\nContent-Length:9\r\n\r\nForbidden";
        send(fd, resp, strlen(resp), 0);
        close(fd);
        arena_free(&arena);
        return;
    }
    // build full filesystem path
    char fullpath[4096];
    snprintf(fullpath, sizeof(fullpath), "%s%s", www_root, clean_path);
    // check cache
    void *data = NULL;
    size_t sz = 0;
    cache_get(global_cache, fullpath, &data, &sz);
    if (data) {
        // send from cache
        const char *mime = guess_mime(fullpath);
        char hdr[256];
        int hdrlen = snprintf(hdr, sizeof(hdr),
            "HTTP/1.0 200 OK\r\nContent-Length: %zu\r\nContent-Type: %s\r\n\r\n", sz, mime);
        send(fd, hdr, hdrlen, 0);
        send(fd, data

```

## /C/prime_number_fuction.c

```c path="/C/prime_number_fuction.c" 

```

## /C/pyramid_pattern.c

```c path="/C/pyramid_pattern.c" 
// The Pattern will look something like this
//         1
//       1 2 1
//     1 2 3 2 1
//   1 2 3 4 3 2 1
// 1 2 3 4 5 4 3 2 1
//   1 2 3 4 3 2 1
//     1 2 3 2 1
//       1 2 1
//         1


#include <stdio.h>

int main() {
    int n, i, j, k;

    // Input the number of rows (half of the diamond)
    printf("Enter the number of rows: ");
    scanf("%d", &n);

    // UPPER HALF of diamond
    for (i = 1; i <= n; i++) {
        // Print leading spaces
        for (j = 1; j <= n - i; j++) {
            printf("  ");
        }

        // Print increasing numbers from 1 to i
        for (j = 1; j <= i; j++) {
            printf("%d ", j);
        }

        // Print decreasing numbers from i-1 down to 1
        for (j = i - 1; j >= 1; j--) {
            printf("%d ", j);
        }

        // New line after each row
        printf("\n");
    }

    // LOWER HALF of diamond
    for (i = n - 1; i >= 1; i--) {
        // Print leading spaces
        for (j = 1; j <= n - i; j++) {
            printf("  ");
        }

        // Print increasing numbers from 1 to i
        for (j = 1; j <= i; j++) {
            printf("%d ", j);
        }

        // Print decreasing numbers from i-1 down to 1
        for (j = i - 1; j >= 1; j--) {
            printf("%d ", j);
        }

        // New line after each row
        printf("\n");
    }

    return 0;
}


```

## /C/race_circular_track_simulation.c

```c path="/C/race_circular_track_simulation.c" 
#include <stdio.h>
#include <stdlib.h>

// --- Data Structure Definition ---

/**
 * @brief Represents a single segment or point on the circular race track.
 * * This structure forms the node of the circular linked list.
 */
struct Node {
    int id;             // Unique identifier for the track segment (0 is the start/finish line).
    struct Node *next;  // Pointer to the next segment on the track, making it a circular list.
};

// --- Function Prototypes ---
struct Node *create_track(int n, struct Node *head);
int simulate_Race(int k, struct Node *head);

// --- Core Function: Create Circular Track ---

/**
 * @brief Creates a circular race track (circular linked list).
 * * The track has 'n' segments, with a total of (n+1) nodes (0 to n).
 * The head node (id=0) links back to the last node (id=n), forming a circle.
 * * @param n The number of track segments (nodes - 1).
 * @param head Pointer to the head of the list (initially NULL).
 * @return struct Node* The pointer to the head of the circular list (node with id=0).
 */
struct Node *create_track(int n, struct Node *head) {
    struct Node *temp = NULL;
    struct Node *prev = NULL;

    // Create n+1 nodes (from i=0 to i=n)
    for (int i = 0; i <= n; i++) {
        // Allocate memory for the new node (track segment)
        temp = (struct Node *)malloc(sizeof(struct Node));
        
        // Check if memory allocation failed
        if (temp == NULL) {
            fprintf(stderr, "Memory allocation failed!\n");
            // In a real application, you would need to free previously allocated memory here.
            return NULL;
        }

        temp->id = i;
        temp->next = NULL;

        if (head == NULL) {
            // First node is the head (Start/Finish Line: id=0)
            head = temp;
        } else {
            // Link the previous node to the new node
            prev->next = temp;
        }
        
        // Move the 'previous' pointer forward
        prev = temp;
    }

    // Connect the last node (id=n) back to the head (id=0) to make the track circular
    if (temp != NULL) {
        temp->next = head;
    }
    
    return head;
}

// --- Core Function: Race Simulation (Lapping Challenge) ---

/**
 * @brief Simulates a race using the Tortoise and Hare (Floyd's) technique.
 * * Dominic (Tortoise) moves 1 segment per turn.
 * Stephano (Hare) moves 2 segments per turn.
 * * The race ends if:
 * 1. Stephano (faster) laps Dominic (slower) - Indicated by Dom == Steph. (Stephano wins this phase)
 * 2. Dominic completes 'k' required laps without being lapped. (Dominic wins)
 * * @param k The number of laps Dominic is required to finish.
 * @param head The starting point (node with id=0).
 * @return int Returns 0 upon completion.
 */
int simulate_Race(int k, struct Node *head) {
    // Both racers start at the same position (head/id=0)
    struct Node *Dom = head;
    struct Node *Steph = head;
    int laps = 0; // Counts the laps completed by Dominic (the slower racer)

    printf("\n--- Race Simulation Start ---\n");
    printf("Dominic speed: 1 segment/turn (Tortoise)\n");
    printf("Stephano speed: 2 segments/turn (Hare)\n");
    printf("Dominic's required laps: %d\n", k);
    printf("Track segments start at id=0 (Start/Finish).\n\n");

    // Race loop: continues as long as Dominic's required laps are not met
    while (k > laps) {
        // Safety check to ensure pointers are valid before moving
        if (Dom == NULL || Steph == NULL || Steph->next == NULL) {
             printf("Error: Invalid track structure (non-circular or too short).\n");
             return 0;
        }

        // 1. Advance the Racers
        Dom = Dom->next;             // Dominic moves 1 step
        Steph = Steph->next->next;   // Stephano moves 2 steps

        // 2. Check for Lapping (Meeting Point)
        // If the faster racer (Stephano) meets the slower racer (Dominic),
        // it means Stephano has successfully lapped Dominic.
        if (Dom == Steph) {
            printf("Racer collision detected at segment id: %d!\n", Dom->id);
            printf("Result: Stephano won the lapping challenge by catching Dominic!\n");
            return 0;
        }

        // 3. Count Dominic's Laps
        // We count a lap when Dominic (the slower one) crosses the start line (id=0)
        // Note: The original code counted Stephano's lap, but since the end condition uses 'k' for Dom,
        // it is more intuitive to track Dom's laps for the final goal check.
        if (Dom->id == 0) {
            laps++;
            printf("Dominic finished lap %d of %d.\n", laps, k);
        }
    }

    // --- Race End Condition ---
    
    // If the loop finished because k <= laps, Dominic completed his required laps.
    printf("\n--- Race Finished ---\n");
    printf("Result: Dominic finished his required %d laps without being lapped.\n", k);
    printf("Dominic wins the distance challenge!\n");
    
    return 0;
}

// --- Main Program ---

int main() {
    int nodes;
    int dom_laps;

    printf("Enter the number of track segments (e.g., 5 for a track with nodes 0 to 5): ");
    // The number entered here is the 'n' in the create_track function.
    if (scanf("%d", &nodes) != 1 || nodes < 1) {
        printf("Invalid input for track segments.\n");
        return 1;
    }

    printf("Enter the number of laps Dominic has to finish: ");
    if (scanf("%d", &dom_laps) != 1 || dom_laps < 1) {
        printf("Invalid input for laps.\n");
        return 1;
    }

    struct Node *head = NULL;
    
    // Create and link the track
    head = create_track(nodes, head);
    
    // Check for creation error
    if (head == NULL) {
        printf("Failed to create the track. Exiting.\n");
        return 1;
    }

    // Run the simulation
    simulate_Race(dom_laps, head);
    
    // --- Memory Cleanup ---
    
    // Free the dynamically allocated nodes to prevent memory leaks.
    struct Node *current = head;
    struct Node *temp_next = NULL;

    if (current != NULL) {
        // Break the cycle at the head to allow proper traversal for freeing
        struct Node *last_node = current;
        while (last_node->next != head) {
            last_node = last_node->next;
        }
        last_node->next = NULL; 

        // Now traverse and free each node
        while (current != NULL) {
            temp_next = current->next;
            free(current);
            current = temp_next;
        }
    }

    return 0;
}
```

## /C/remove_duplicate_characters.c

```c path="/C/remove_duplicate_characters.c" 
#include <stdio.h>
#include <string.h>

void rm(char str[]) {
    int n = strlen(str);
    int i, j, k;
    for(i = 0; i < n; i++) {
        for(j = i + 1; str[j] != '\0'; ) {
            if(str[i] == str[j]) {
                for(k = j; str[k] != '\0'; k++) {
                    str[k] = str[k+1];
                }
            } else {
                j++;
            }
        }
    }
    printf("%s", str);
}

int main() {
    char str[100];
    scanf("%99s", str);
    rm(str);
    return 0;
}

```

## /C/reverse_string_using_stack.c

```c path="/C/reverse_string_using_stack.c" 
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 50
char stack[MAX_SIZE];
int top = -1; 
void push(char item) 
{
    if (top >= MAX_SIZE - 1) 
	{
        printf("Stack Overflow!\n");
    }
	else 
	{
        stack[++top] = item;
    }
}
char pop() 
{
    if (top == -1) 
	{
        printf("Stack Underflow!\n");
    	return '\0';
    }
	else 
	{
        return stack[top--];
    }
}
int main() 
{
    char str[MAX_SIZE];
    int i;
    printf("Enter a string: ");
    gets(str);
    str[strlen(str)] ='\0';
    for (i = 0; i < strlen(str); i++)
	{
        push(str[i]);
    }
    printf("Reversed string: ");
    while (top != -1)
	{
        printf("%c", pop());
    }
    printf("\n");
    return 0;
}
```

## /C/revesearray.c

```c path="/C/revesearray.c" 
#include <stdio.h>

// Function to reverse array elements in place
void reverseArray(int arr[], int n) {
    int start = 0, end = n - 1, temp;
    while (start < end) {
        // Swap elements at start and end
        temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;
        start++;
        end--;
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    reverseArray(arr, n);

    printf("Reversed Array: ");
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);

    return 0;
}

```

## /C/search_in_rotated_sorted_array.c

```c path="/C/search_in_rotated_sorted_array.c" 

```

## /C/selection_sort.c

```c path="/C/selection_sort.c" 
#include <stdio.h>

int main() {
    int arr[100], n, i, j, temp, minIndex;

    // Input array size
    printf("Enter number of elements: ");
    scanf("%d", &n);

    // Input elements
    printf("Enter %d elements:\n", n);
    for(i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    // Selection sort logic
    for(i = 0; i < n - 1; i++) {
        minIndex = i;
        for(j = i + 1; j < n; j++) {
            if(arr[j] < arr[minIndex]) {
                minIndex = j;
            }
        }

        // Swap smallest with first element of unsorted part
        temp = arr[i];
        arr[i] = arr[minIndex];
        arr[minIndex] = temp;
    }

    // Print sorted array
    printf("Sorted array in ascending order:\n");
    for(i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

```

## /C/selectionsort.c

```c path="/C/selectionsort.c" 
#include <stdio.h>

int main()
{
    int n;
    int min;
    int temp;
    printf("Enter the number of elements in array\n");
    scanf("%d",&n);
    int arr[n];
    printf("Enter the elements of array\n");
    for (int i=0;i<n;i++)
    scanf("%d",&arr[i]);
    for(int i=0;i<=n-2;i++)
    {
        min=i;
        for (int j=i;j<=n-1;j++)
        {
            if (arr[j]<arr[min])
            min=j;
        }
        temp=arr[min];
        arr[min]=arr[i];
        arr[i]=temp;
    }
    for (int i=0;i<n;i++)
    printf("%d",arr[i]);
}
```

## /C/sortarray.c

```c path="/C/sortarray.c" 
#include <stdio.h>

void bubbleSort(int arr[], int n) {
    int i, j, temp;

    // Outer loop for the number of passes
    for (i = 0; i < n - 1; i++) {
        // Inner loop for comparison and swapping
        // n - i - 1 because the last 'i' elements are already in place
        for (j = 0; j < n - i - 1; j++) {
            // Compare adjacent elements
            if (arr[j] > arr[j + 1]) {
                // Swap arr[j] and arr[j+1]
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
}

// Function to print the array
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int data[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(data) / sizeof(data[0]);

    printf("Original array: ");
    printArray(data, n);

    // Sort the array
    bubbleSort(data, n);

    printf("Sorted array: ");
    printArray(data, n);

    return 0;
}
```

## /C/stringpalindrome.c

```c path="/C/stringpalindrome.c" 
#include <stdio.h>
#include <string.h>

void palin(int start , int end , char str[])
{
    if (str[start]!=str[end])
    {
    printf("The string is not a palindrome");
    return;
    }
    if (start>=end)
    {
    printf("The string is a palindrome");
    return;
    }
    palin(start+1,end-1,str);
}


int main()
{
    char str[100];
    printf("Enter the string\n");
    scanf("%s",str);
    size_t n = strlen(str);
    palin(0,n-1,str);
}
```

## /C/syscall_interceptor.c

```c path="/C/syscall_interceptor.c" 
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uidgid.h>
#include <linux/sched.h>
#include <linux/syscalls.h>
#include <linux/uaccess.h>
#include <linux/kallsyms.h>
#include <linux/slab.h>

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A kernel module to intercept sys_openat calls");

// Pointer to original system call
static asmlinkage long (*original_openat)(const struct pt_regs *);

// New system call
static asmlinkage long hook_openat(const struct pt_regs *regs)
{
    const char __user *pathname = (const char __user *)regs->di;
    char *kernel_path;
    kuid_t target_uid = make_kuid(&init_user_ns, 1000); // UID to monitor
    struct task_struct *task = current;

    kernel_path = kmalloc(256, GFP_KERNEL);
    if (!kernel_path) return original_openat(regs);

    if (strncpy_from_user(kernel_path, pathname, 255) > 0) {
        kernel_path[255] = '\0';

        if (task->real_cred->uid.val == target_uid.val) {
            pr_info("[Interceptor] User %d opened file: %s\n", target_uid.val, kernel_path);
        }
    }

    kfree(kernel_path);
    return original_openat(regs);
}

// Initialization
static int __init interceptor_init(void)
{
    pr_info("[Interceptor] Module loaded\n");

    original_openat = (void *)kallsyms_lookup_name("sys_openat");
    if (!original_openat) {
        pr_err("[Interceptor] Cannot find sys_openat\n");
        return -ENOENT;
    }

    pr_info("[Interceptor] sys_openat located at: %px\n", original_openat);

    // Note: Modifying syscall table requires bypassing protections
    // This is intentionally left as an educational example

    return 0;
}

// Exit
static void __exit interceptor_exit(void)
{
    pr_info("[Interceptor] Module unloaded\n");

    // Restore original syscall
    // This requires kernel permissions
}

module_init(interceptor_init);
module_exit(interceptor_exit);

```

## /C/towerofhanoi.c

```c path="/C/towerofhanoi.c" 
#include <stdio.h>

// Recursive function to solve Tower of Hanoi
void towerOfHanoi(int n, char source, char auxiliary, char destination) {
    if (n == 1) {
        printf("Move disk 1 from %c to %c\n", source, destination);
        return;
    }

    // Move n-1 disks from source to auxiliary
    towerOfHanoi(n - 1, source, destination, auxiliary);

    // Move the nth disk from source to destination
    printf("Move disk %d from %c to %c\n", n, source, destination);

    // Move the n-1 disks from auxiliary to destination
    towerOfHanoi(n - 1, auxiliary, source, destination);
}

int main() {
    int n;

    printf("Enter number of disks: ");
    scanf("%d", &n);

    printf("The sequence of moves involved:\n");
    towerOfHanoi(n, 'A', 'B', 'C'); // A = source, B = auxiliary, C = destination

    return 0;
}

```

## /C/transpose_matrix.c

```c path="/C/transpose_matrix.c" 
#include <stdio.h>

#define MAX 100

// Created Function to get valid integer input within range
int getValidInput(const char *prompt, int max) {
    int value;
    while (1) {
        printf("%s (1 to %d): ", prompt, max);
        if (scanf("%d", &value) != 1) {
            // Clear invalid input
            while (getchar() != '\n');
            printf("Invalid input. Please enter a number.\n");
        } else if (value < 1 || value > max) {
            printf("Value out of range. Try again.\n");
        } else {
            break;  // Valid input
        }
    }
    return value;
}

int main() {
    int rows, cols;
    int matrix[MAX][MAX], transpose[MAX][MAX];

    // Get validated input for rows and columns
    rows = getValidInput("Enter the number of rows", MAX);
    cols = getValidInput("Enter the number of columns", MAX);

    // Input matrix elements
    printf("\nEnter the elements of the matrix (%d x %d):\n", rows, cols);
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("Element [%d][%d]: ", i, j);
            while (scanf("%d", &matrix[i][j]) != 1) {
                while (getchar() != '\n');  // Clear input buffer
                printf("Invalid input. Enter an integer for [%d][%d]: ", i, j);
            }
        }
    }

    // Compute transpose
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            transpose[j][i] = matrix[i][j];
        }
    }

    // Print original matrix
    printf("\nOriginal Matrix:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d\t", matrix[i][j]);
        }
        printf("\n");
    }

    // Print transposed matrix
    printf("\nTransposed Matrix:\n");
    for (int i = 0; i < cols; i++) {
        for (int j = 0; j < rows; j++) {
            printf("%d\t", transpose[i][j]);
        }
        printf("\n");
    }

    return 0;
}

```

## /Contribution_Dsa.md

# 🧩 Contributing Guidelines

Welcome to the **DSA Problems & Solutions Repository**!  
We appreciate your interest in contributing. Please follow the guidelines below to maintain quality and consistency across all submissions.

---

## ✅ Do’s

### 1. Write Clean, Readable, and Well-Commented Code
- Use **meaningful variable names** and **consistent indentation**.
- Add comments to explain:
  - Your **approach / algorithm**
  - **Time and Space complexity**
  - Any edge cases handled

### 2. Add Only DSA-Related Problems and Solutions
- Accepted topics include:
  - Arrays, Strings, Linked Lists, Stacks, Queues, Trees, Graphs, Hashing, Dynamic Programming, etc.
- At the top of each file, include:
  ```cpp
  // Problem: Two Sum
  // Source: LeetCode #1
  // Approach: Hashmap
  // Time Complexity: O(n)
  // Space Complexity: O(n)


## /DSA#/DSA-ALGORITHM

``` path="/DSA#/DSA-ALGORITHM" 
1. Linked List Sum

class Node:
    def __init__(self, data):
        self.data, self.next = data, None

def sum_linked_list(head):
    total = 0
    while head:
        total += head.data
        head = head.next
    return total

# Example
head = Node(5); head.next = Node(10); head.next.next = Node(15)
print("Linked List Sum:", sum_linked_list(head))


---

2. Half Linked List (Print first half)

def print_half_list(head):
    slow, fast = head, head
    while fast and fast.next:
        print(slow.data, end=" -> ")
        slow, fast = slow.next, fast.next.next
    print("END")

# Example
head = Node(1); head.next = Node(2); head.next.next = Node(3)
head.next.next.next = Node(4); head.next.next.next.next = Node(5)
print_half_list(head)  # Output: 1 -> 2 -> END


---

3. Hello World (ASCII Style)

def hello_world():
    codes = [72,101,108,108,111,32,87,111,114,108,100]
    return "".join(chr(c) for c in codes)

print(hello_world())


---

4. Sum of 1D Array

def sum_array(arr):
    total = 0
    for num in arr:
        total += num
    return total

print("Array Sum:", sum_array([1,2,3,4,5]))


---

```

## /DSA#/Hard-LinkedListproblems.cpp

```cpp path="/DSA#/Hard-LinkedListproblems.cpp" 
#include <iostream>
#include <vector>
using namespace std;

//Delete all occurances of a key in dll


struct ListNode
{
    int val;
    ListNode *next;
    ListNode *prev;
    ListNode()
    {
        val = 0;
        next = nullptr;
        prev = nullptr;
    }
    ListNode(int data1)
    {
        val = data1;
        next = nullptr;
        prev = nullptr;
    }
    ListNode(int data1, ListNode *next1, ListNode *prev1)
    {
        val = data1;
        next = next1;
        prev = prev1;
    }
};


class Solution {
public:
    ListNode * deleteAllOccurrences(ListNode* head, int target) {
 if (!head) return nullptr;
ListNode* temp = head;

while(temp!=nullptr){

    ListNode* front=temp->next;
if(temp->val==target){
    if(temp==head){
        head=head->next;
        if(head) head->prev=nullptr;
    }else{
        if(temp->prev) temp->prev->next=temp->next;
        if(temp->next) temp->next->prev=temp->prev;
    }
    delete temp;
    }
    temp=front;
}
return head;
    }
};

// Find Pairs with Given Sum in Doubly Linked List


class Solution2 {
public:
    vector<vector<int>> findPairsWithGivenSum(ListNode* head, int target) {
    vector<vector<int>> result;
    if(!head) return result;
    ListNode* left=head;
    ListNode* right=head;
    while(right->next!=nullptr){
right=right->next;
    }
      while(left!=nullptr && right!=nullptr && left!=right && right->next!=left){
        int sum=left->val+right->val;
        if(sum==target){
            result.push_back({left->val,right->val});
left=left->next;
right=right->prev;
        }else if(sum<target){
            left=left->next;
        }else{
            right=right->prev;
        }
      }  
      return result;
    }
};

// Remove duplicated from sorted DLL
class Solution {
public:
    ListNode * removeDuplicates(ListNode *head) {
if(head==nullptr || head->next==nullptr){
    return head;
}

ListNode* temp=head;

while(temp!=nullptr && temp->next!=nullptr){
    
        if(temp->val==temp->next->val){
            ListNode* dup=temp->next;
            temp->next = dup->next;

if(dup->next!=nullptr)
dup->next->prev=temp;
delete dup;
        }else{
            temp=temp->next;
        }
}
return head;
    }
};
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (head == nullptr || k == 1) return head;

        
        ListNode* dummy = new ListNode(0);
        dummy->next = head;

        ListNode* prevGroupEnd = dummy;

        while (true) {
           
            ListNode* kth = prevGroupEnd;
            for (int i = 0; i < k && kth != nullptr; i++) {
                kth = kth->next;
            }
            if (kth == nullptr) break; 

    
            ListNode* groupStart = prevGroupEnd->next;
            ListNode* nextGroupStart = kth->next;

            ListNode* prev = nextGroupStart;
            ListNode* curr = groupStart;
            while (curr != nextGroupStart) {
                ListNode* temp = curr->next;
                curr->next = prev;
                prev = curr;
                curr = temp;
            }

            prevGroupEnd->next = kth;
            prevGroupEnd = groupStart;
        }

        return dummy->next;
    }
};
// Merge k Sorted Lists
#include <queue>
class Solution {
public:
    struct compare {
        bool operator()(ListNode* a, ListNode* b) {
            return a->val > b->val;
        }
    };

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        priority_queue<ListNode*, vector<ListNode*>, compare> pq;
        for (auto node : lists) {
            if (node) pq.push(node);
        }

        ListNode* dummy = new ListNode(0);
        ListNode* tail = dummy;

        while (!pq.empty()) {
            ListNode* curr = pq.top();
            pq.pop();
            tail->next = curr;
            tail = tail->next;
            if (curr->next) pq.push(curr->next);
        }

        return dummy->next;
    }
};

```

## /DSA#/JobScheduling.java

```java path="/DSA#/JobScheduling.java" 
// // <<<< Maximum Profit in Job Scheduling >>>>

// /* You are given n jobs, where every job is represented by:
//    i. startTime[i]: the start time of the job.
//    ii. endTime[i]: the end time of the job.
//    iii. profit[i]: the profit you earn by completing the job.
//    Two jobs cannot be taken that overlap in time.
//    Return the maximum profit you can earn such that there are no two overlapping jobs in your selected subset.
   
//    Note: A job ending at time X is allowed to overlap with another job that starts exactly at time X. */



// // <<<< Solution >>>>

// /**
//  * This implementation uses a combination of dynamic programming with memoization
//  * and binary search for an efficient O(N log N) solution.
//  */


import java.util.Arrays;
import java.util.Comparator;

public class JobScheduling {

    static class Job {
        int s, e, p;
        Job(int s, int e, int p) { this.s = s; this.e = e; this.p = p; }
    }

    public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
        int n = startTime.length;
        Job[] jobs = new Job[n];
        for (int i = 0; i < n; i++) jobs[i] = new Job(startTime[i], endTime[i], profit[i]);

        Arrays.sort(jobs, Comparator.comparingInt(j -> j.s));
        int[] starts = new int[n];
        for (int i = 0; i < n; i++) starts[i] = jobs[i].s;
        int[] dp = new int[n + 1];

        for (int i = n - 1; i >= 0; i--) {
            int next = findNextJob(starts, jobs[i].e);
            dp[i] = Math.max(jobs[i].p + dp[next], dp[i + 1]); // take or skip
        }
        return dp[0];
    }

    private int findNextJob(int[] arr, int target) {
        int l = 0, r = arr.length - 1, ans = arr.length;
        while (l <= r) {
            int m = l + (r - l) / 2;
            if (arr[m] >= target) { ans = m; r = m - 1; } else l = m + 1;
        }
        return ans;
    }

    public static void main(String[] args) {
        JobScheduling js = new JobScheduling();
        int[] start = {1, 2, 3};
        int[] end   = {3, 4, 5};
        int[] prof  = {50, 10, 40};
        System.out.println("Maximum Profit = " + js.jobScheduling(start, end, prof));
    }
}

```

## /DSA#/LRU_Cache.cpp

```cpp path="/DSA#/LRU_Cache.cpp" 
// 🧠 DSA Problem: LRU Cache Implementation
// 📁 Folder: DSA/Design/
// 🧑 Author: Aditya
// 📝 Description:
// Implement a Least Recently Used (LRU) Cache using
// HashMap + Doubly Linked List for O(1) get() and put() operations.

#include <bits/stdc++.h>
using namespace std;

// Node structure for doubly linked list
class Node {
public:
    int key, value;
    Node* prev;
    Node* next;
    Node(int k, int v) {
        key = k;
        value = v;
        prev = next = nullptr;
    }
};

class LRUCache {
private:
    int capacity;
    unordered_map<int, Node*> cache;
    Node* head;
    Node* tail;

    // Helper to add a node right after the head
    void addNode(Node* node) {
        node->next = head->next;
        node->prev = head;
        head->next->prev = node;
        head->next = node;
    }

    // Helper to remove a node
    void removeNode(Node* node) {
        Node* prev = node->prev;
        Node* next = node->next;
        prev->next = next;
        next->prev = prev;
    }

    // Move a node to the front (most recently used)
    void moveToHead(Node* node) {
        removeNode(node);
        addNode(node);
    }

    // Pop least recently used (tail->prev)
    Node* popTail() {
        Node* res = tail->prev;
        removeNode(res);
        return res;
    }

public:
    LRUCache(int cap) {
        capacity = cap;
        head = new Node(0, 0);
        tail = new Node(0, 0);
        head->next = tail;
        tail->prev = head;
    }

    int get(int key) {
        if (cache.find(key) == cache.end())
            return -1;

        Node* node = cache[key];
        moveToHead(node);
        return node->value;
    }

    void put(int key, int value) {
        if (cache.find(key) != cache.end()) {
            Node* node = cache[key];
            node->value = value;
            moveToHead(node);
        } else {
            Node* node = new Node(key, value);
            cache[key] = node;
            addNode(node);

            if (cache.size() > capacity) {
                Node* tailNode = popTail();
                cache.erase(tailNode->key);
                delete tailNode;
            }
        }
    }

    // Optional: Print cache state (for debugging)
    void printCache() {
        Node* curr = head->next;
        cout << "Cache state (MRU -> LRU): ";
        while (curr != tail) {
            cout << "[" << curr->key << ":" << curr->value << "] ";
            curr = curr->next;
        }
        cout << endl;
    }
};

// 🧪 Example test
int main() {
    LRUCache cache(2);
    cache.put(1, 1);
    cache.put(2, 2);
    cout << cache.get(1) << endl; // 1
    cache.put(3, 3);              // evicts key 2
    cout << cache.get(2) << endl; // -1
    cache.put(4, 4);              // evicts key 1
    cout << cache.get(1) << endl; // -1
    cout << cache.get(3) << endl; // 3
    cout << cache.get(4) << endl; // 4
}

```

## /DSA#/LinkedlistAlgos.cpp

```cpp path="/DSA#/LinkedlistAlgos.cpp" 
struct ListNode {
    int val;
    ListNode* next;
    ListNode(int v) : val(v), next(nullptr) {}
};

//Detect Cycle in Linked List (Floyd’s Algorithm)
bool hasCycle(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) return true;
    }
    return false;
}
//Detect Cycle & Remove Cycle (Floyd’s Algorithm, Singly)
bool detectCycle(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) return true;
    }
    return false;
}

void removeCycle(ListNode* head) {
    ListNode* slow = head;
    ListNode* fast = head;
    do {
        if (!fast || !fast->next) return;
        slow = slow->next;
        fast = fast->next->next;
    } while (slow != fast);

    fast = head;
    while (slow->next != fast->next) {
        slow = slow->next;
        fast = fast->next;
    }
    slow->next = nullptr;
}

```

## /DSA#/NOTES.md

# DSA Notes

A compact collection of Data Structures & Algorithms notes, patterns, and study checklist.

## Table of Contents
- Purpose
- Study checklist
- Core data structures (summary)
- Common algorithms & patterns
- Time complexity quick reference
- Problem patterns and tips
- Recommended practice problems & resources

## Purpose
Keep short, high-value reminders for solving typical DSA problems during interview prep and practice.

## Study checklist
- [ ] Arrays & Strings basics
- [ ] Two pointers & sliding window patterns
- [ ] Linked lists (insert/delete/reverse)
- [ ] Stacks & queues
- [ ] Trees (BST, traversal, LCA)
- [ ] Graphs (BFS, DFS, shortest paths)
- [ ] Heaps & priority queues
- [ ] Hash tables / maps / sets
- [ ] Sorting & searching
- [ ] Dynamic programming (top-down & bottom-up)
- [ ] Greedy algorithms
- [ ] Backtracking
- [ ] Complexity analysis practice

## Core data structures (short)
- Array: contiguous memory, O(1) access, O(n) insert/delete worst-case.
- Linked List: O(1) insert/delete at known position, O(n) search/access.
- Stack/Queue: LIFO / FIFO, use for recursion elimination, scheduling.
- Hash map/set: average O(1) lookup/insert, watch for collisions and worst-case.
- Heap: O(log n) push/pop, used for top-k, priority scheduling.
- Tree (binary/AVL/Red-Black): hierarchical data, BST supports ordered ops O(h).
- Graph: adjacency list (sparse) vs matrix (dense).

## Common algorithms & patterns
- Two pointers: sorted arrays, pair-sum, remove duplicates, partitioning.
- Sliding window: subarray problems with variable window (max/min sum, num distinct).
- Fast & slow pointers: detect cycles, middle of list.
- DFS/BFS: tree/graph traversal, connected components, topological sort (Kahn/DFS).
- Dynamic Programming: identify state, transition, base case, iterative vs memoized.
- Greedy: pick local optimum, prove with exchange argument.
- Backtracking: generate combinations/permutations, search with pruning.
- Divide & conquer: mergesort, quicksort, binary search.

## Time complexity quick reference
- Access array by index: O(1)
- Search unsorted array: O(n)
- Binary search (sorted): O(log n)
- Insertion in array (shift): O(n)
- Hash table ops: average O(1)
- BST ops: O(h) (balanced: O(log n))
- Heap push/pop: O(log n)
- Merge sort / Heap sort: O(n log n)
- Quick sort: average O(n log n), worst O(n^2)
- DFS/BFS: O(V + E)
- DP (typical knapsack / longest common subsequence): O(n*m) depending on states

## Problem patterns & tips
- When you see "subarray" think sliding window or prefix sums.
- When asked for "k-th" or "top-k", use heaps or selection algorithms.
- When constraints are large (n up to 10^5+), avoid O(n^2) solutions.
- Use hash maps for frequency/count problems and two-sum variants.
- Convert recursive brute force to DP by identifying overlapping subproblems.
- Sketch small examples and invariants before coding.

## Recommended practice problems
- Arrays: Two Sum, 3Sum, Longest Subarray with Sum K
- Strings: Longest Palindromic Substring, Anagram grouping
- Linked List: Reverse Linked List, Detect Cycle, Merge K Sorted Lists
- Trees: Binary Tree Maximum Path Sum, Serialize/Deserialize
- Graphs: Course Schedule, Number of Islands, Dijkstra problems
- DP: Knapsack, Longest Increasing Subsequence, Edit Distance
- Backtracking: Permutations, Combination Sum

## Resources
- "Introduction to Algorithms" (CLRS) — deep theory
- "Algorithms" by Sedgewick — practical
- LeetCode / HackerRank / Codeforces for practice
- Grokking the Coding Interview (patterns)

---



## /DSA#/RatInAMaze DSA Algo CPP

``` path="/DSA#/RatInAMaze DSA Algo CPP" 
class Solution {
  public:
    void pushing(int x, int y, vector<vector<int>> &v,string temp, vector<string> &ans, vector<vector<int>> &vis) {
    int n = v.size();
    if (x == n-1 && y == n-1) {
        ans.push_back(temp);
        return;
        
    }
    if (y+1<n && v[x][y+1] && vis[x][y+1] == 0) {
        vis[x][y+1] = 1;
        temp += "R";
        pushing(x,y+1,v,temp,ans,vis);
        temp.pop_back();
        vis[x][y+1] = 0;
        
    }
    if (y-1>=0 && v[x][y-1] && vis[x][y-1] == 0) {
        vis[x][y-1] = 1;
        temp += "L";
        pushing(x,y-1,v,temp,ans,vis);
        temp.pop_back();
        vis[x][y-1] = 0;
        
    }
    if (x+1<n && v[x+1][y] && vis[x+1][y] == 0) {
        vis[x+1][y] = 1;
        temp += "D";
        pushing(x+1,y,v,temp,ans,vis);
        temp.pop_back();
        vis[x+1][y] = 0;
        
    }
    if (x-1>=0 && v[x-1][y] && vis[x-1][y] == 0) {
        vis[x-1][y] = 1;
        temp += "U";
        pushing(x-1,y,v,temp,ans,vis);
        temp.pop_back();
        vis[x-1][y] = 0;
        
    }
    return;       
        
    }
    vector<string> ratInMaze(vector<vector<int>>& maze) {
        int n = maze.size();
        string ans = "";
        vector<string> v;
        vector<vector<int>> vis(n,vector<int>(n,0));
        vis[0][0] = 1;
        pushing(0,0,maze,ans,v,vis);
        sort(v.begin(),v.end());
        return v;
        
    }
};

```

## /DSA#/Sorting-Algos/BubbleSort.java

```java path="/DSA#/Sorting-Algos/BubbleSort.java" 
//Bubble Sort: Compare the adjacent elements and swap them if they are in wrong order repeatedly, until the array is sorted.

public class BubbleSort {
    public static void bubbleSort(int[] arr){
        int n =arr.length;
        for(int i=0; i<n-1; i++){
            for(int j=0; j<n-i-1; j++){
                if(arr[j]>arr[j+1]){
                    //Swap using a temp variable
                    int temp=arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
    }
    public static void main(String[] args){
        int[] numbers={9,2,6,3,8};
        bubbleSort(numbers);
        for(int num: numbers){
            System.out.print(num+" ");
        }
    }
    
}
//Time Complexity: O(n^2)
//Preferred when dataset is small / Nearly sorted
```

## /DSA#/Sorting-Algos/CountingSort.cpp

```cpp path="/DSA#/Sorting-Algos/CountingSort.cpp" 
#include <iostream>
#include <algorithm>
using namespace std;

void countingSort(int arr[], int n) {
    int max = *max_element(arr, arr + n);
    int count[max + 1] = {0};

    for (int i = 0; i < n; i++)
        count[arr[i]]++;

    int index = 0;
    for (int i = 0; i <= max; i++)
        while (count[i]--)
            arr[index++] = i;
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    int arr[] = {4, 2, 2, 8, 3, 3, 1};
    int n = sizeof(arr) / sizeof(arr[0]);

    countingSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    return 0;
}

```

## /DSA#/Sorting-Algos/HeapSort.java

```java path="/DSA#/Sorting-Algos/HeapSort.java" 
public class HeapSort {

    public void sort(int arr[]) {
        int n = arr.length;

        // Build heap (rearrange array)
        for (int i = n / 2 - 1; i >= 0; i--)
            heapify(arr, n, i);

        // One by one extract an element from heap
        for (int i = n - 1; i > 0; i--) {
            // Move current root to end
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            // call max heapify on the reduced heap
            heapify(arr, i, 0);
        }
    }

    // To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap
    void heapify(int arr[], int n, int i) {
        int largest = i; // Initialize largest as root
        int l = 2 * i + 1; // left = 2*i + 1
        int r = 2 * i + 2; // right = 2*i + 2

        // If left child is larger than root
        if (l < n && arr[l] > arr[largest])
            largest = l;

        // If right child is larger than largest so far
        if (r < n && arr[r] > arr[largest])
            largest = r;

        // If largest is not root
        if (largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;

            // Recursively heapify the affected sub-tree
            heapify(arr, n, largest);
        }
    }

    // Utility function to print array
    static void printArray(int arr[]) {
        for (int value : arr)
            System.out.print(value + " ");
        System.out.println();
    }

    // Driver code
    public static void main(String args[]) {
        int arr[] = {12, 11, 13, 5, 6, 7};
        HeapSort hs = new HeapSort();
        hs.sort(arr);

        System.out.println("Sorted array is");
        printArray(arr);
    }
}
```

## /DSA#/Sorting-Algos/Huffman_Algorithm.cpp

```cpp path="/DSA#/Sorting-Algos/Huffman_Algorithm.cpp" 
#include <bits/stdc++.h>
using namespace std;

// Node for Huffman Tree
struct Node {
    char ch;
    int freq;
    Node *left, *right;
    Node(char c, int f) : ch(c), freq(f), left(nullptr), right(nullptr) {}
};

// Comparator for priority queue
struct compare {
    bool operator()(Node* a, Node* b) {
        return a->freq > b->freq;
    }
};

// Recursive function to print codes
void printCodes(Node* root, string code) {
    if(!root) return;
    if(!root->left && !root->right) {
        cout << root->ch << ": " << code << endl;
    }
    printCodes(root->left, code + "0");
    printCodes(root->right, code + "1");
}

int main() {
    int n;
    cout << "Enter number of characters: ";
    cin >> n;

    vector<char> chars(n);
    vector<int> freq(n);
    cout << "Enter characters:\n";
    for(int i = 0; i < n; i++) cin >> chars[i];
    cout << "Enter their frequencies:\n";
    for(int i = 0; i < n; i++) cin >> freq[i];

    priority_queue<Node*, vector<Node*>, compare> pq;
    for(int i = 0; i < n; i++) pq.push(new Node(chars[i], freq[i]));

    while(pq.size() > 1) {
        Node* left = pq.top(); pq.pop();
        Node* right = pq.top(); pq.pop();
        Node* merged = new Node('\0', left->freq + right->freq);
        merged->left = left;
        merged->right = right;
        pq.push(merged);
    }

    cout << "Huffman Codes:\n";
    printCodes(pq.top(), "");
    return 0;
}

```

## /DSA#/Sorting-Algos/MergeSort.java

```java path="/DSA#/Sorting-Algos/MergeSort.java" 
// Based on divide and conquer algorithm
// Divide the array into two halves and recursively sort them
// Then merge the arrays to get a sorted array

public class MergeSort{
    public static void mergeSort(int[] arr, int left, int right){
        if(left< right){
            int mid = left + (right-left) /2; //the middle element index
            mergeSort(arr, left, mid); //left subarray
            mergeSort(arr, mid+1, right); //right subarray
            merge(arr, left, mid, right);
        }
    }

    //to merge both sorted subarrays
    private static void merge(int[] arr, int left, int mid, int right){
        int n1= mid-left+1;
        int n2= right-mid;

        int[] leftArray = new int[n1];
        int[] rightArray = new int[n2];

        for(int i=0; i<n1; i++){
            leftArray[i] = arr[left+i];
        }

        for(int j=0; j <n2; j++){
            rightArray[j] = arr[mid+1+j];
        }

        int i=0;
        int j=0;
        int k=left;

        do{
            if(leftArray[i]<=rightArray[j]){
                arr[k] = leftArray[i];
                i++;
            }
            else{
                arr[k] = rightArray[j];
                j++;
            }
            k++;
        }while(i<n1 && j<n2);

        do{
            arr[k] = leftArray[i];
            i++;
            k++;
        }while(i<n1);

        do{
            arr[k] = rightArray[j];
            j++;
            k++;
        }while(j<n2);
    }

    public static void main(String[] args){
        int[] numbers = {5,2,3,12,5};
        mergeSort(numbers, 0, numbers.length-1);
        for(int num:numbers){
            System.out.print(num + " ");
        }
    }
}
```

## /DSA#/Sorting-Algos/QuickSort.java

```java path="/DSA#/Sorting-Algos/QuickSort.java" 
//Quick Sort: It is a divide and conquer algorithm.
// Select a pivot
// partition the array into two sub arrays
// Elements smaller than pivot are to be placed at left
// Elements greater than pivot are to be placed at right

public class QuickSort{

    // Example of Recursion1`
    public static void quickSort(int[] arr, int low, int high){
        if(low<high){
            int pivotIdx = divide(arr, low, high);
            quickSort(arr, low, pivotIdx-1); //left subarray
            quickSort(arr, pivotIdx+1, high); //right subarray
        }
    }

    //Example of Encapsulation
    private static int divide(int[] arr, int low, int high){
        int pivot =arr[high];
        int i =low-1;
        for(int j=low; j<high; j++){
            if(arr[j]<pivot){
                i++;        
                //Swap the elements
                int temp=arr[i];
                arr[i]=arr[j];
                arr[j]= temp;
           }
        }
        int temp=arr[i+1];
        arr[i+1] = arr[high];
        arr[high] = temp;

        return i+1;
    }
    public static void main(String[] args){
        int[] numbers = {6,2,8,1,7,0};
        quickSort(numbers, 0, numbers.length -1);
        for(int num:numbers){
            System.out.print(num + " ");
        }
    }
}
//Time Complexity: O(n log n)
//The fastest sorting algorithm
//In-place sorting, ideal for larder datasets
//Arrays.sort() is based on this algorithm
```

## /DSA#/Sorting-Algos/RadixSort.cpp

```cpp path="/DSA#/Sorting-Algos/RadixSort.cpp" 
#include <iostream>
#include <algorithm>
using namespace std;

int getMax(int arr[], int n) {
    return *max_element(arr, arr + n);
}

void countingSortRadix(int arr[], int n, int exp) {
    int output[n];
    int count[10] = {0};

    for (int i = 0; i < n; i++)
        count[(arr[i] / exp) % 10]++;

    for (int i = 1; i < 10; i++)
        count[i] += count[i - 1];

    for (int i = n - 1; i >= 0; i--) {
        output[count[(arr[i] / exp) % 10] - 1] = arr[i];
        count[(arr[i] / exp) % 10]--;
    }

    for (int i = 0; i < n; i++)
        arr[i] = output[i];
}

void radixSort(int arr[], int n) {
    int m = getMax(arr, n);
    for (int exp = 1; m / exp > 0; exp *= 10)
        countingSortRadix(arr, n, exp);
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
    int n = sizeof(arr) / sizeof(arr[0]);

    radixSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    return 0;
}

```

## /DSA#/Sorting-Algos/ShellSort.cpp

```cpp path="/DSA#/Sorting-Algos/ShellSort.cpp" 
#include <iostream>
using namespace std;

void shellSort(int arr[], int n) {
    for (int gap = n/2; gap > 0; gap /= 2) {
        for (int i = gap; i < n; i++) {
            int temp = arr[i];
            int j;
            for (j = i; j >= gap && arr[j - gap] > temp; j -= gap)
                arr[j] = arr[j - gap];
            arr[j] = temp;
        }
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    int arr[] = {23, 12, 1, 8, 34, 54, 2, 3};
    int n = sizeof(arr) / sizeof(arr[0]);

    shellSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    return 0;
}

```

## /DSA#/Sorting-Algos/Sorting-Algorithms-Using-Python/MergeSort.py

```py path="/DSA#/Sorting-Algos/Sorting-Algorithms-Using-Python/MergeSort.py" 
def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    mid = len(arr) // 2

    left = merge_sort(arr[:mid])

    right = merge_sort(arr[mid:])

    return merge(left, right)


def merge(left, right):
    result = []
    i = j = 0

    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1

    result += left[i:]
    result += right[j:]
    return result


arr = [5, 3, 8, 4, 2, 7, 1, 10]
print("Original array:", arr)
sorted_arr = merge_sort(arr)
print("Sorted array:", sorted_arr)

```

## /DSA#/Sorting-Algos/Sorting-Algorithms-Using-Python/QuickSort.py

```py path="/DSA#/Sorting-Algos/Sorting-Algorithms-Using-Python/QuickSort.py" 
def quicksort(arr):
    """
    Sorts a list using the Quick Sort algorithm.
    """
    if len(arr) <= 1:
        return arr
    else:
        pivot = arr[0]  # Choosing the first element as the pivot
        less = [x for x in arr[1:] if x < pivot]
        greater = [x for x in arr[1:] if x >= pivot]
        return quicksort(less) + [pivot] + quicksort(greater)

# Example usage:
if __name__ == "__main__":
    unsorted_list = [10, 7, 8, 9, 1, 5, 2, 6, 3, 4]
    print("Unsorted list:", unsorted_list)
    sorted_list = quicksort(unsorted_list)
    print("Sorted list:", sorted_list)

    unsorted_list_2 = [64, 34, 25, 12, 22, 11, 90]
    print("Unsorted list 2:", unsorted_list_2)
    sorted_list_2 = quicksort(unsorted_list_2)
    print("Sorted list 2:", sorted_list_2)
```

## /DSA#/Sorting-Algos/heap_sort.cpp

```cpp path="/DSA#/Sorting-Algos/heap_sort.cpp" 
#include <iostream>
using namespace std;

void heapify(int arr[], int n, int i) {
    int largest = i;
    int l = 2*i + 1;
    int r = 2*i + 2;

    if (l < n && arr[l] > arr[largest])
        largest = l;
    if (r < n && arr[r] > arr[largest])
        largest = r;

    if (largest != i) {
        swap(arr[i], arr[largest]);
        heapify(arr, n, largest);
    }
}

void heapSort(int arr[], int n) {
    for (int i = n/2 - 1; i >= 0; i--)
        heapify(arr, n, i);
    for (int i = n - 1; i > 0; i--) {
        swap(arr[0], arr[i]);
        heapify(arr, i, 0);
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    int arr[] = {12, 11, 13, 5, 6, 7};
    int n = sizeof(arr) / sizeof(arr[0]);

    heapSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    return 0;
}

```

## /DSA#/Sorting-Algos/selectionSort.java

```java path="/DSA#/Sorting-Algos/selectionSort.java" 
# Selection Sort in Python

def selection_sort(arr):
    # Loop through all elements in the array
    for i in range(len(arr)):
        # Assume the current index has the smallest element
        min_index = i

        # Find the smallest element in the remaining unsorted part
        for j in range(i + 1, len(arr)):
            if arr[j] < arr[min_index]:
                min_index = j  # Update index of smallest element

        # Swap the found smallest element with the first element of unsorted part
        arr[i], arr[min_index] = arr[min_index], arr[i]

    return arr  # Return the sorted array


# Example usage
arr = [64, 25, 12, 22, 11]
print("Original array:", arr)

sorted_arr = selection_sort(arr)
print("Sorted array:", sorted_arr)

```

## /DSA#/Sorting-Algos/selection_sort.cpp

```cpp path="/DSA#/Sorting-Algos/selection_sort.cpp" 
#include <iostream>
using namespace std;

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++) {
        int minIdx = i;
        for (int j = i + 1; j < n; j++)
            if (arr[j] < arr[minIdx])
                minIdx = j;
        swap(arr[i], arr[minIdx]);
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}

int main() {
    int arr[] = {29, 10, 14, 37, 13};
    int n = sizeof(arr) / sizeof(arr[0]);

    selectionSort(arr, n);

    cout << "Sorted array: ";
    printArray(arr, n);

    return 0;
}

```

## /DSA#/heap_operation.py

```py path="/DSA#/heap_operation.py" 
class Heap:
    def __init__(self):
        self.heap = []

    def createHeap(self, c):
        for e in c:
            self.insert(e)

    def insert(self, e):
        self.heap.append(e)
        
        index = len(self.heap) - 1
        parent = (index - 1) // 2
        
        while index > 0 and self.heap[parent] < self.heap[index]:
            self.heap[index], self.heap[parent] = self.heap[parent], self.heap[index]
            index = parent
            parent = (index - 1) // 2
        
    def top(self):
        if not self.heap:
            return None
        return self.heap[0]

    def delete(self):
        if len(self.heap) == 0:
            print("Empty")
            return None
            
        if len(self.heap) == 1:
            return self.heap.pop()
            
        maxm = self.heap[0]
        self.heap[0] = self.heap.pop()
        
        index = 0
        
        while True:
            left_child_index = (2 * index) + 1
            right_child_index = (2 * index) + 2
            largest = index
            
            if left_child_index < len(self.heap) and self.heap[left_child_index] > self.heap[largest]:
                largest = left_child_index
                
            if right_child_index < len(self.heap) and self.heap[right_child_index] > self.heap[largest]:
                largest = right_child_index
                
            if largest != index:
                self.heap[index], self.heap[largest] = self.heap[largest], self.heap[index]
                index = largest
            else:
                break
                
        return maxm
```

## /DSA#/linkedlist_operation.py

```py path="/DSA#/linkedlist_operation.py" 
class Node:
    def __init__(self, val):
        self.val = val
        self.next = None
    
class SLL:
    def __init__(self):
        self.head = None
    def printList(self):
        if self.head is None:
            print("Empty List")
        else:
            temp = self.head
            while temp:
                print(temp.val)
                temp = temp.next
    def insertBegin(self):
        val = input()
        nodeBegin = Node(val)
        nodeBegin.next = self.head
        self.head = nodeBegin
    def deleteBegin(self):
        temp = self.head
        self.head=temp.next
        temp=None
    def insertPos(self):
        pos=int(input())
        val=input()
        np=Node(val)
        temp=self.head.next
        prev=self.head
        for i in range(pos-1):
            temp=temp.next
            prev=prev.next
        prev.next=np
        np.next=temp
    def deletePos(self):
        pos=int(input())
        temp=self.head.next
        prev=self.head
        for i in range(1,pos-1):
            temp=temp.next
            prev=prev.next
        prev.next=temp.next
        temp.next=None
    def insertEnd(self):
        val=input()
        ne=Node(val)
        temp=self.head
        while temp.next:
            temp=temp.next
        temp.next=ne
    def deleteEnd(self):
        temp=self.head.next
        prev=self.head
        while temp.next:
            temp=temp.next
            prev=prev.next
        prev.next=None


obj = SLL()
obj.insertBegin()
obj.insertBegin()
obj.insertBegin()
obj.deleteEnd()
obj.printList()
```

## /DSA-Project/DSA-Project.iml

```iml path="/DSA-Project/DSA-Project.iml" 
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
  <component name="NewModuleRootManager" inherit-compiler-output="true">
    <exclude-output />
    <content url="file://$MODULE_DIR{{contextString}}quot;>
      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
    </content>
    <orderEntry type="jdk" jdkName="openjdk-23" jdkType="JavaSDK" />
    <orderEntry type="sourceFolder" forTests="false" />
  </component>
</module>
```

## /DSA-Project/src/Main.java

```java path="/DSA-Project/src/Main.java" 
import java.util.Scanner;
//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
    public static void main(String[] args) {
        TodoList todo=new TodoList();
        Scanner sc = new Scanner(System.in);
        int choice;

        do {
            System.out.println("\n1. Add Task\n2. Mark Done\n3. Remove Task\n4. Display Tasks\n0. Exit");
            choice = sc.nextInt();
            sc.nextLine(); // consume newline

            switch (choice) {
                case 1:
                    System.out.print("Enter task description: ");
                    String desc = sc.nextLine();
                    todo.addTask(desc);
                    break;
                case 2:
                    System.out.print("Enter task number to mark done: ");
                    int doneIndex = sc.nextInt();
                    todo.markTaskDone(doneIndex);
                    break;
                case 3:
                    System.out.print("Enter task number to remove: ");
                    int remIndex = sc.nextInt();
                    todo.removeTask(remIndex);
                    break;
                case 4:
                    todo.displayTasks();
                    break;
                case 0:
                    System.out.println("Exiting...");
                    break;
                default:
                    System.out.println("Invalid option.");
            }
        } while (choice != 0);

        sc.close();
    }
}
```

## /DSA-Project/src/Task.java

```java path="/DSA-Project/src/Task.java" 
public class Task {
    private String description;
    private boolean isDone;

    public Task(String description) {
        this.description = description;
        this.isDone = false;
    }

    public String getDescription() {
        return description;
    }

    public boolean isDone() {
        return isDone;
    }

    public void markDone() {
        isDone = true;
    }

}

```

## /DSA-Project/src/TodoList.java

```java path="/DSA-Project/src/TodoList.java" 
import java.util.LinkedList;

public class TodoList {
    private LinkedList<Task> tasks;

    public TodoList() {
        tasks = new LinkedList<>();
    }

    // Add task
    public void addTask(String description) {
        tasks.add(new Task(description));
    }

    // Mark a task done
    public void markTaskDone(int index) {
        if (index >= 0 && index < tasks.size()) {
            tasks.get(index).markDone();
        }
    }

    // Remove a task
    public void removeTask(int index) {
        if (index >= 0 && index < tasks.size()) {
            tasks.remove(index);
        }
    }

    // Display the list
    public void displayTasks() {
        for (int i = 0; i < tasks.size(); i++) {
            Task task = tasks.get(i);
            String status = task.isDone() ? "[Done]" : "[Pending]";
            System.out.println(i + " - " + status + " " + task.getDescription());
        }
    }

}

```

## /Dfs.java

```java path="/Dfs.java" 
import java.util.*;

public class Dfs {
    private int V; // Number of vertices
    private LinkedList<Integer>[] adj; // Adjacency lists

    // Constructor
    public Dfs(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; i++) {
            adj[i] = new LinkedList<>();
        }
    }

    // Add an edge to the graph
    public void addEdge(int v, int w) {
        adj[v].add(w);
    }

    // DFS traversal from a given source
    public void DFS(int start) {
        boolean[] visited = new boolean[V];
        dfsUtil(start, visited);
    }

    // Utility function for DFS
    private void dfsUtil(int v, boolean[] visited) {
        visited[v] = true;
        System.out.print(v + " ");

        for (int n : adj[v]) {
            if (!visited[n]) {
                dfsUtil(n, visited);
            }
        }
    }

    // Sample usage
    public static void main(String[] args) {
        Dfs graph = new Dfs(4);

        graph.addEdge(0, 1);
        graph.addEdge(0, 2);
        graph.addEdge(1, 2);
        graph.addEdge(2, 0);
        graph.addEdge(2, 3);
        graph.addEdge(3, 3);

        System.out.println("DFS starting from vertex 2:");
        graph.DFS(2);
    }
}

```

## /DoublyLinkedList.java

```java path="/DoublyLinkedList.java" 
import java.util.NoSuchElementException;

public class DoublyLinkedList {

    /**
     * Private inner class to represent a node in the list.
     * It holds the data, a reference to the next node, and a reference to the previous node.
     */
    private class Node {
        int data;
        Node next;
        Node prev;

        public Node(int data) {
            this.data = data;
            this.next = null; // Initially null
            this.prev = null; // Initially null
        }
    }

    // --- List Attributes ---
    private Node head; // Pointer to the first node
    private Node tail; // Pointer to the last node
    private int size;  // Number of nodes in the list

    /**
     * Constructor for an empty DoublyLinkedList.
     */
    public DoublyLinkedList() {
        this.head = null;
        this.tail = null;
        this.size = 0;
    }

    // --- Core Methods ---

    /**
     * Checks if the list is empty.
     * @return true if the list has 0 elements, false otherwise.
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Returns the number of elements in the list.
     * @return the size of the list.
     */
    public int getSize() {
        return size;
    }

    /**
     * Adds a new node to the front (head) of the list.
     * @param data The data for the new node.
     */
    public void addFirst(int data) {
        Node newNode = new Node(data);

        if (isEmpty()) {
            // If list is empty, new node is both head and tail
            head = newNode;
            tail = newNode;
        } else {
            // 1. Link new node to the old head
            newNode.next = head;
            // 2. Link old head back to the new node
            head.prev = newNode;
            // 3. Move head pointer to the new node
            head = newNode;
        }
        size++;
    }

    /**
     * Adds a new node to the end (tail) of the list.
     * @param data The data for the new node.
     */
    public void addLast(int data) {
        Node newNode = new Node(data);

        if (isEmpty()) {
            // If list is empty, new node is both head and tail
            head = newNode;
            tail = newNode;
        } else {
            // 1. Link old tail to the new node
            tail.next = newNode;
            // 2. Link new node back to the old tail
            newNode.prev = tail;
            // 3. Move tail pointer to the new node
            tail = newNode;
        }
        size++;
    }

    /**
     * Removes and returns the first node (head) from the list.
     * @return The data of the removed node.
     * @throws NoSuchElementException if the list is empty.
     */
    public int removeFirst() {
        if (isEmpty()) {
            throw new NoSuchElementException("Cannot remove from an empty list.");
        }

        int data = head.data;

        if (head == tail) {
            // Case 1: Only one node in the list
            head = null;
            tail = null;
        } else {

```

## /Dsa_sum

``` path="/Dsa_sum" 
def subset_sum(nums, target):
    result = []
    
    def backtrack(start, path, current_sum):
        # If current sum equals target, record this subset
        if current_sum == target:
            result.append(path[:])
            return
        
        # If sum exceeds target, stop exploring further
        if current_sum > target:
            return
        
        # Try adding each remaining element
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1, path, current_sum + nums[i])
            path.pop()
    
    backtrack(0, [], 0)
    return result


# Example
nums = [3, 4, 5, 2]
target = 7
solutions = subset_sum(nums, target)

print("Subsets that sum to", target, "are:", solutions)

```

## /FactorialExample.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/FactorialExample.class

## /FactorialExample.java

```java path="/FactorialExample.java" 
import java.util.*;

public class FactorialExample {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a non-negative integer: ");
        int num = sc.nextInt();
        long factorial = 1;

        if (num < 0) {
            System.out.println("Factorial is not defined for negative numbers.");
        } else {
            for (int i = 1; i <= num; i++) {
                factorial *= i;
            }
            System.out.println("Factorial of " + num + " = " + factorial);
        }

        sc.close();
    }
}

```

## /Int_as_sum_of_powers.py

```py path="/Int_as_sum_of_powers.py" 
class Solution:
    def numberOfWays(self, n: int, x: int) -> int:
        MOD=10**9+7
        # find largest m with m^x<=n
        m=int(n**(1.0/x))
        # fix rounding edge-cases
        while (m+1)**x<=n:
            m+=1
        while m**x>n:
            m-=1

        powers=[i**x for i in range(1,m+1)]
        dp=[0]*(n+1)
        dp[0]=1

        for v in powers:
            for s in range(n,v-1,-1):   # iterate backwards for 0/1 usage
                dp[s]=(dp[s]+dp[s-v])%MOD

        return dp[n]

```

## /LIS_Dsa

``` path="/LIS_Dsa" 
# ------------------------------------------------------------
# Problem: Longest Increasing Subsequence
# Difficulty: Advanced
# Source: LeetCode #300
# ------------------------------------------------------------
# Statement:
# Given an integer array nums, return the length of the longest
# strictly increasing subsequence.
#
# Example:
#   Input: nums = [10,9,2,5,3,7,101,18]
#   Output: 4  # LIS: [2,3,7,101]
#
# Approach:
#   - Use Dynamic Programming with a patience sorting technique.
#   - Maintain a list `sub` representing the smallest possible
#     tail of all increasing subsequences with length i+1.
#   - Use binary search to find the position to replace or append.
#
# Time Complexity: O(n log n)
# Space Complexity: O(n)
# ------------------------------------------------------------

from bisect import bisect_left

def length_of_lis(nums):
    sub = []  # Holds the smallest tail of all increasing subsequences
    for num in nums:
        i = bisect_left(sub, num)  # Find position to replace or append
        if i == len(sub):
            sub.append(num)  # Extend the subsequence
        else:
            sub[i] = num  # Replace to keep smaller tail
    return len(sub)

# ------------------------------------------------------------
# Driver Code for Testing
# ------------------------------------------------------------
if __name__ == "__main__":
    nums = [10, 9, 2, 5, 3, 7, 101, 18]
    print("Input Array:", nums)
    print("Length of LIS:", length_of_lis(nums))

```

## /LIS_Dsa_Code.md

# ------------------------------------------------------------
# Problem: Longest Increasing Subsequence
# Difficulty: Advanced
# Source: LeetCode #300
# ------------------------------------------------------------
# Statement:
# Given an integer array nums, return the length of the longest
# strictly increasing subsequence.
#
# Example:
#   Input: nums = [10,9,2,5,3,7,101,18]
#   Output: 4  # LIS: [2,3,7,101]
#
# Approach:
#   - Use Dynamic Programming with a patience sorting technique.
#   - Maintain a list `sub` representing the smallest possible
#     tail of all increasing subsequences with length i+1.
#   - Use binary search to find the position to replace or append.
#
# Time Complexity: O(n log n)
# Space Complexity: O(n)
# ------------------------------------------------------------

from bisect import bisect_left

def length_of_lis(nums):
    sub = []  # Holds the smallest tail of all increasing subsequences
    for num in nums:
        i = bisect_left(sub, num)  # Find position to replace or append
        if i == len(sub):
            sub.append(num)  # Extend the subsequence
        else:
            sub[i] = num  # Replace to keep smaller tail
    return len(sub)

# ------------------------------------------------------------
# Driver Code for Testing
# ------------------------------------------------------------
if __name__ == "__main__":
    nums = [10, 9, 2, 5, 3, 7, 101, 18]
    print("Input Array:", nums)
    print("Length of LIS:", length_of_lis(nums))


## /LongestCommonPrefix.java

```java path="/LongestCommonPrefix.java" 
LongestCommonPrefix 

import java.util.Scanner;
import java.util.Arrays;

public class LongestCommonPrefix {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        // Taking user input for number of strings
        System.out.print("Enter number of strings: ");
        int n = sc.nextInt();
        sc.nextLine(); // consume newline

        String[] strs = new String[n];
        System.out.println("Enter the strings one by one:");
        for (int i = 0; i < n; i++) {
            strs[i] = sc.nextLine();
        }

        // Call the function
        String result = longestCommonPrefix(strs);
        System.out.println("Longest Common Prefix: " + result);

        sc.close();
    }

    public static String longestCommonPrefix(String[] strs) {
        if (strs == null || strs.length == 0) {
            return "";
        }

        Arrays.sort(strs); // Sort the array

        String first = strs[0];
        String last = strs[strs.length - 1];

        int i = 0;
        while (i < first.length() && i < last.length() && first.charAt(i) == last.charAt(i)) {
            i++;
        }

        return first.substring(0, i);
    }
}

```

## /MergeSort.java

```java path="/MergeSort.java" 
import java.util.Arrays;

public class MergeSort {

    /**
     * The main function that sorts arr[l...r] using merge()
     * This is the recursive "divide" part.
     *
     * @param arr   The array to be sorted
     * @param left  The starting index
     * @param right The ending index
     */
    public void sort(int arr[], int left, int right) {
        if (left < right) {
            // Find the middle point
            int middle = (left + right) / 2;

            // Recursively sort the first and second halves
            sort(arr, left, middle);
            sort(arr, middle + 1, right);

            // Merge the sorted halves
            merge(arr, left, middle, right);
        }
    }

    /**
     * Merges two subarrays of arr[].
     * First subarray is arr[left...middle]
     * Second subarray is arr[middle+1...right]
     * This is the "conquer" part.
     *
     * @param arr    The original array
     * @param left   The starting index of the first subarray
     * @param middle The ending index of the first subarray
     * @param right  The ending index of the second subarray
     */
    void merge(int arr[], int left, int middle, int right) {
        // Find sizes of two subarrays to be merged
        int n1 = middle - left + 1;
        int n2 = right - middle;

        // --- Create temporary arrays ---
        int L[] = new int[n1];
        int R[] = new int[n2];

        // --- Copy data to temp arrays ---
        for (int i = 0; i < n1; ++i) {
            L[i] = arr[left + i];
        }
        for (int j = 0; j < n2; ++j) {
            R[j] = arr[middle + 1 + j];
        }

        // --- Merge the temp arrays ---

        // Initial indexes of first and second subarrays
        int i = 0, j = 0;

        // Initial index of the merged subarray in the original array
        int k = left;
        
        // Compare elements from L and R and place the smaller one into arr
        while (i < n1 && j < n2) {
            if (L[i] <= R[j]) {
                arr[k] = L[i];
                i++;
            } else {
                arr[k] = R[j];
                j++;
            }
            k++;
        }

        // --- Copy remaining elements (if any) ---
        
        // Copy remaining elements of L[] if any
        while (i < n1) {
            arr[k] = L[i];
            i++;
            k++;
        }

        // Copy remaining elements of R[] if any
        while (j < n2) {
            arr[k] = R[j];
            j++;
            k++;
        }
    }

    /**
     * A main method to test the merge sort implementation.
     */
    public static void main(String args[]) {
        int arr[] = { 12, 11, 13, 5, 6, 7 };

        System.out.println("Original array:");
        System.out.println(Arrays.toString(arr));

        MergeSort ob = new MergeSort();
        ob.sort(arr, 0, arr.length - 1);

        System.out.println("\nSorted array:");
        System.out.println(Arrays.toString(arr));
    }
}

```

## /MoveZeros.java

```java path="/MoveZeros.java" 
//https://leetcode.com/problems/move-zeroes/

class Solution {
    public void moveZeroes(int[] nums) {
        int cnt = 0; 
        int index = 0;
        for(int i=0 ; i < nums.length ; i++){
            if(nums[i] == 0) cnt++;
            else{
                nums[index] = nums[i];
                index++;
            }
            
        }
        
        for(int i=nums.length-1 ; i>=nums.length - cnt ; i--){
            nums[i] = 0;
        }
        
        for(int i=0 ; i < nums.length ; i++) System.out.print(nums[i]+" ");
    }
}

```

## /MultiplicationTable.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/MultiplicationTable.class

## /MultiplicationTable.java

```java path="/MultiplicationTable.java" 
import java.util.Scanner;

public class MultiplicationTable {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a number to print its multiplication table: ");
        int number = sc.nextInt();

        System.out.print("Enter how many multiples you want: ");
        int limit = sc.nextInt();

        System.out.println("\nMultiplication Table of " + number + ":");

        for (int i = 1; i <= limit; i++) {
            System.out.println(number + " x " + i + " = " + (number * i));
        }

        sc.close();
    }
}

```

## /Product of Array Except Self.cpp

```cpp path="/Product of Array Except Self.cpp" 
#include <iostream>
#include <vector>
using namespace std;

// Function to calculate the product of all 
// elements except the current element
vector<int> productExceptSelf(vector<int>& arr) {
    int n = arr.size();
  
    // Fill result array with 1
    vector<int> res(n, 1);

    for (int i = 0; i < n; i++) {
      
        // Compute product of all elements except arr[i]
        for (int j = 0; j < n; j++) {
            if (i != j) 
                res[i] *= arr[j];
        }
    }

    return res;
}

int main() {
    vector<int> arr = {10, 3, 5, 6, 2};
    vector<int> res = productExceptSelf(arr);
    for (int val : res) 
        cout << val << " ";
    return 0;
}

```

## /Projects/android/NotesApp/app/src/main/java/com/example/notesapp/MainActivity.java

```java path="/Projects/android/NotesApp/app/src/main/java/com/example/notesapp/MainActivity.java" 
package com.example.notesapp;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.content.SharedPreferences;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText notesInput;
    private Button saveBtn, clearBtn;
    private SharedPreferences sharedPreferences;
    private static final String PREFS_NAME = "MyNotesPref";
    private static final String KEY_NOTE = "note";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        notesInput = findViewById(R.id.notesInput);
        saveBtn = findViewById(R.id.saveBtn);
        clearBtn = findViewById(R.id.clearBtn);

        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

        // Load saved note
        String savedNote = sharedPreferences.getString(KEY_NOTE, "");
        notesInput.setText(savedNote);

        // Save note
        saveBtn.setOnClickListener(v -> {
            String note = notesInput.getText().toString();
            sharedPreferences.edit().putString(KEY_NOTE, note).apply();
            Toast.makeText(this, "📝 Note saved!", Toast.LENGTH_SHORT).show();
        });

        // Clear note
        clearBtn.setOnClickListener(v -> {
            notesInput.setText("");
            sharedPreferences.edit().remove(KEY_NOTE).apply();
            Toast.makeText(this, "🗑️ Note cleared!", Toast.LENGTH_SHORT).show();
        });
    }
}

```

## /Projects/android/NotesApp/app/src/main/res/layout/activity_main.xml

```xml path="/Projects/android/NotesApp/app/src/main/res/layout/activity_main.xml" 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="20dp"
    android:background="#FDFDFD">

    <TextView
        android:text="📝 Notes App"
        android:textSize="22sp"
        android:textStyle="bold"
        android:layout_marginBottom="20dp"/>

    <EditText
        android:id="@+id/notesInput"
        android:hint="Write your notes here..."
        android:layout_width="match_parent"
        android:layout_height="250dp"
        android:gravity="top|start"
        android:padding="10dp"
        android:background="@android:drawable/editbox_background"
        android:textSize="16sp"/>

    <Button
        android:id="@+id/saveBtn"
        android:text="Save Note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"/>

    <Button
        android:id="@+id/clearBtn"
        android:text="Clear Note"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>
</LinearLayout>

```

## /Projects/android/NumberGuessingGame/app/src/main/java/com/example/numberguess/MainActivity.java

```java path="/Projects/android/NumberGuessingGame/app/src/main/java/com/example/numberguess/MainActivity.java" 
package com.example.numberguess;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private int randomNumber;
    private int guessCount = 0;
    private EditText inputGuess;
    private TextView resultText;
    private Button guessBtn, resetBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        inputGuess = findViewById(R.id.inputGuess);
        resultText = findViewById(R.id.resultText);
        guessBtn = findViewById(R.id.guessBtn);
        resetBtn = findViewById(R.id.resetBtn);

        generateRandomNumber();

        // Disable guess button until input is provided
        guessBtn.setEnabled(false);
        inputGuess.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                guessBtn.setEnabled(!s.toString().trim().isEmpty());
            }

            @Override
            public void afterTextChanged(Editable s) {}
        });

        guessBtn.setOnClickListener(v -> checkGuess());
        resetBtn.setOnClickListener(v -> resetGame());
    }

    private void generateRandomNumber() {
        randomNumber = new Random().nextInt(100) + 1; // Range: 1–100
    }

    private void showMessage(String message) {
        resultText.setText(message);
    }

    private void checkGuess() {
        String guessStr = inputGuess.getText().toString();

        if (guessStr.isEmpty()) {
            showMessage("Please enter a number!");
            return;
        }

        int guess = Integer.parseInt(guessStr);

        // Range validation
        if (guess < 1 || guess > 100) {
            showMessage("Please enter a number between 1 and 100!");
            return;
        }

        guessCount++;

        if (guess < randomNumber) {
            showMessage("Too low! Try again. (Attempts: " + guessCount + ")");
        } else if (guess > randomNumber) {
            showMessage("Too high! Try again. (Attempts: " + guessCount + ")");
        } else {
            showMessage("🎉 Correct! You guessed it in " + guessCount + " attempts!");
        }
    }

    private void resetGame() {
        inputGuess.setText("");
        guessCount = 0;
        generateRandomNumber();
        showMessage("Game reset! Try to guess again.");
        Toast.makeText(this, "🔁 New number generated!", Toast.LENGTH_SHORT).show();
    }
}

```

## /Projects/android/NumberGuessingGame/app/src/main/res/layout/activity_main.xml

```xml path="/Projects/android/NumberGuessingGame/app/src/main/res/layout/activity_main.xml" 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:padding="20dp"
    android:background="#FAFAFA">

    <TextView
        android:text="🎯 Number Guessing Game"
        android:textSize="22sp"
        android:textStyle="bold"
        android:layout_marginBottom="25dp"/>

    <EditText
        android:id="@+id/inputGuess"
        android:hint="Enter your guess (1-100)"
        android:inputType="number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@android:drawable/editbox_background"
        android:layout_marginBottom="15dp"/>

    <Button
        android:id="@+id/guessBtn"
        android:text="Guess"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/resetBtn"
        android:text="Reset Game"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"/>

    <TextView
        android:id="@+id/resultText"
        android:text="Try to guess the number!"
        android:textSize="18sp"
        android:layout_marginTop="25dp"
        android:textColor="#000"/>
</LinearLayout>

```

## /Projects/android/SimpleCounterApp/app/src/main/java/com/example/simplecounter/MainActivity.java

```java path="/Projects/android/SimpleCounterApp/app/src/main/java/com/example/simplecounter/MainActivity.java" 
package com.example.simplecounter;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private int count = 0;
    private TextView counterText;
    private Button incrementBtn, resetBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        counterText = findViewById(R.id.counterText);
        incrementBtn = findViewById(R.id.incrementBtn);
        resetBtn = findViewById(R.id.resetBtn);

        incrementBtn.setOnClickListener(v -> {
            count++;
            counterText.setText(String.valueOf(count));
        });

        resetBtn.setOnClickListener(v -> {
            count = 0;
            counterText.setText(String.valueOf(count));
        });
    }
}

```

## /Projects/android/SimpleCounterApp/app/src/main/res/layout/activity_main.xml

```xml path="/Projects/android/SimpleCounterApp/app/src/main/res/layout/activity_main.xml" 
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    android:padding="20dp"
    android:background="#FAFAFA">

    <TextView
        android:id="@+id/counterText"
        android:text="0"
        android:textSize="50sp"
        android:textColor="#000"
        android:layout_marginBottom="30dp"/>

    <Button
        android:id="@+id/incrementBtn"
        android:text="Increment"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"/>

    <Button
        android:id="@+id/resetBtn"
        android:text="Reset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:padding="10dp"/>
</LinearLayout>

```

## /Projects/java_projects/CalculatorApp/Calculator.java

```java path="/Projects/java_projects/CalculatorApp/Calculator.java" 
package CalculatorApp;

public class Calculator {
    public double add(double a, double b) {
        return a + b;
    }

    public double subtract(double a, double b) {
        return a - b;
    }

    public double multiply(double a, double b) {
        return a * b;
    }

    public double divide(double a, double b) {
        if (b == 0) {
            System.out.println("Error: Division by zero!");
            return Double.NaN;
        }
        return a / b;
    }
}

```

## /Projects/java_projects/CalculatorApp/Main.java

```java path="/Projects/java_projects/CalculatorApp/Main.java" 
package CalculatorApp;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Calculator calc = new Calculator();
        Scanner sc = new Scanner(System.in);
        int choice;
        double a, b;

        System.out.println("=== Simple Calculator ===");
        do {
            System.out.println("\n1. Add");
            System.out.println("2. Subtract");
            System.out.println("3. Multiply");
            System.out.println("4. Divide");
            System.out.println("5. Exit");
            System.out.print("Enter your choice: ");
            choice = sc.nextInt();

            if (choice >= 1 && choice <= 4) {
                System.out.print("Enter first number: ");
                a = sc.nextDouble();
                System.out.print("Enter second number: ");
                b = sc.nextDouble();

                switch (choice) {
                    case 1:
                        System.out.println("Result: " + calc.add(a, b));
                        break;
                    case 2:
                        System.out.println("Result: " + calc.subtract(a, b));
                        break;
                    case 3:
                        System.out.println("Result: " + calc.multiply(a, b));
                        break;
                    case 4:
                        System.out.println("Result: " + calc.divide(a, b));
                        break;
                }
            } else if (choice != 5) {
                System.out.println("Invalid choice! Try again.");
            }
        } while (choice != 5);

        System.out.println("Exiting Calculator. Goodbye!");
        sc.close();
    }
}

```

## /Projects/java_projects/StudentManagement/Main.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/Projects/java_projects/StudentManagement/Main.class

## /Projects/java_projects/StudentManagement/Main.java

```java path="/Projects/java_projects/StudentManagement/Main.java" 
package StudentManagement;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        List<Student> students = new ArrayList<>();
        Scanner sc = new Scanner(System.in);

        System.out.println("=== Student Management System ===");
        while (true) {
            System.out.println("\n1. Add Student");
            System.out.println("2. Show Students");
            System.out.println("3. Exit");
            System.out.print("Enter choice: ");
            int choice = sc.nextInt();
            sc.nextLine(); // consume newline

            switch (choice) {
                case 1:
                    System.out.print("Enter name: ");
                    String name = sc.nextLine();
                    System.out.print("Enter age: ");
                    int age = sc.nextInt();
                    sc.nextLine();
                    System.out.print("Enter course: ");
                    String course = sc.nextLine();

                    students.add(new Student(name, age, course));
                    System.out.println("✅ Student added successfully!");
                    break;
                case 2:
                    if (students.isEmpty()) {
                        System.out.println("No students found!");
                    } else {
                        System.out.println("\n=== Student List ===");
                        for (Student s : students) {
                            s.displayInfo();
                        }
                    }
                    break;
                case 3:
                    System.out.println("Exiting program...");
                    sc.close();
                    System.exit(0);
                    break;
                default:
                    System.out.println("Invalid choice, try again.");
            }
        }
    }
}

```

## /Projects/java_projects/StudentManagement/Student.class

Binary file available at https://raw.githubusercontent.com/ghostmkg/dsa-code/refs/heads/main/Projects/java_projects/StudentManagement/Student.class

## /Projects/java_projects/StudentManagement/Student.java

```java path="/Projects/java_projects/StudentManagement/Student.java" 
package StudentManagement;

public class Student {
    private String name;
    private int age;
    private String course;

    public Student(String name, int age, String course) {
        this.name = name;
        this.age = age;
        this.course = course;
    }

    public void displayInfo() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
        System.out.println("Course: " + course);
        System.out.println("-----------------------");
    }
}

```

## /Projects/java_projects/ToDoListApp/Main.java

```java path="/Projects/java_projects/ToDoListApp/Main.java" 
package ToDoListApp;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        List<Task> tasks = new ArrayList<>();
        Scanner sc = new Scanner(System.in);
        int choice;

        System.out.println("=== To-Do List App ===");

        do {
            System.out.println("\n1. Add Task");
            System.out.println("2. View Tasks");
            System.out.println("3. Mark Task as Done");
            System.out.println("4. Delete Task");
            System.out.println("5. Exit");
            System.out.print("Enter choice: ");
            choice = sc.nextInt();
            sc.nextLine(); // consume newline

            switch (choice) {
                case 1:
                    System.out.print("Enter task description: ");
                    String desc = sc.nextLine();
                    tasks.add(new Task(desc));
                    System.out.println("✅ Task added!");
                    break;

                case 2:
                    if (tasks.isEmpty()) {
                        System.out.println("No tasks yet!");
                    } else {
                        System.out.println("\n=== Your Tasks ===");
                        for (int i = 0; i < tasks.size(); i++) {
                            System.out.println((i + 1) + ". " + tasks.get(i));
                        }
                    }
                    break;

                case 3:
                    System.out.print("Enter task number to mark done: ");
                    int doneIndex = sc.nextInt() - 1;
                    if (doneIndex >= 0 && doneIndex < tasks.size()) {
                        tasks.get(doneIndex).markDone();
                        System.out.println("✅ Task marked as done!");
                    } else {
                        System.out.println("❌ Invalid task number!");
                    }
                    break;

                case 4:
                    System.out.print("Enter task number to delete: ");
                    int delIndex = sc.nextInt() - 1;
                    if (delIndex >= 0 && delIndex < tasks.size()) {
                        tasks.remove(delIndex);
                        System.out.println("🗑️ Task deleted!");
                    } else {
                        System.out.println("❌ Invalid task number!");
                    }
                    break;

                case 5:
                    System.out.println("Exiting To-Do List App. Goodbye!");
                    break;

                default:
                    System.out.println("Invalid choice! Try again.");
            }

        } while (choice != 5);

        sc.close();
    }
}

```

## /Projects/java_projects/ToDoListApp/Task.java

```java path="/Projects/java_projects/ToDoListApp/Task.java" 
package ToDoListApp;

public class Task {
    private String description;
    private boolean completed;

    public Task(String description) {
        this.description = description;
        this.completed = false;
    }

    public void markDone() {
        this.completed = true;
    }

    public boolean isCompleted() {
        return completed;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return (completed ? "[✓] " : "[ ] ") + description;
    }
}

```

## /QuickSort

``` path="/QuickSort" 
import java.util.Arrays;

// The class name should be QuickSort
public class QuickSort {

    /**
     * The main recursive function that implements QuickSort.
     */
    public void sort(int arr[], int low, int high) {
        if (low < high) {
            int pi = partition(arr, low, high);
            sort(arr, low, pi - 1);
            sort(arr, pi + 1, high);
        }
    }

    /**
     * This function takes the last element as pivot...
     */
    int partition(int arr[], int low, int high) {
        // ... (partition logic) ...
        int pivot = arr[high];
        int i = (low - 1); 
        for (int j = low; j < high; j++) {
            if (arr[j] <= pivot) {
                i++; 
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
        int temp = arr[i + 1];
        arr[i + 1] = arr[high];
        arr[high] = temp;
        return i + 1;
    }


    public static void main(String args[]) {
        int arr[] = { 10, 7, 8, 9, 1, 5 };
        
        // The object should be a QuickSort object
        QuickSort ob = new QuickSort();
        ob.sort(arr, 0, arr.length - 1);

        System.out.println("Sorted array:");
        System.out.println(Arrays.toString(arr));
    }
}

```

## /README.md

# 📘 DSA-Code

Welcome to **DSA-Code** 🎉
This repository is a collection of **Data Structures and Algorithms (DSA)** solutions implemented in multiple programming languages.
The goal of this repo is to help learners and contributors **explore, practice, and improve** their problem-solving skills in DSA.

Welcome to **DSA-Code** 🎉  
A community-driven repository of **Data Structures and Algorithms (DSA)** solutions implemented in multiple programming languages.  
The goal of this project is to help learners and contributors **explore, practice, and enhance** their problem-solving skills in DSA.  

## 🚀 Features

* 💻 Solutions in multiple programming languages (C, C++, Python, Java, JavaScript, etc.)
* 🧩 Beginner-friendly problem statements and structured solutions
* 🌍 Open-source project — everyone is welcome to contribute
* 💪 Perfect for **Hacktoberfest**, **coding practice**, and **interview preparation**
* 📂 Each folder contains DSA problems and solutions in the respective programming language

## 🚀 Features  
- 💡 Solutions in multiple languages — *C, C++, Python, Java, JavaScript,* and more.  
- 🧑‍💻 Beginner-friendly problem statements with clear, structured solutions.  
- 🗺️ **Comprehensive DSA Roadmap** to guide your journey.  
- 🌍 Open-source project — perfect for **Hacktoberfest**, coding practice, and interviews.  
- 🧩 Each folder contains DSA problems and solutions for the respective programming language.  

---

## 🤝 How to Contribute

---

### 1️⃣ Fork the Repository  
Click the **Fork** button (top-right) to create your own copy.  

```bash
git clone https://github.com/<your-username>/dsa-code.git
cd dsa-code
```

### 3️⃣ Create a branch

```bash
git checkout -b feature-branch-name
4️⃣ Add Your Code

Navigate to the correct folder (e.g., Python/, Java/, etc.)

Add your DSA problem solution file.

### 5️⃣ Commit and push changes

```bash

Ensure proper file naming and comments for clarity.
5️⃣ Commit and Push Changes

git add .
git commit -m "Added solution for <problem-name> in <language>"
git push origin feature-branch-name
6️⃣ Create a Pull Request

Go to the Pull Requests tab on the original repo.

Click on New Pull Request.

### 6️⃣ Raise a Pull Request (PR)

Submit and wait for review 🚀
📝 Contribution Guidelines

✅ Write clean, readable, and well-commented code.
✅ Add only DSA-related problems and solutions.
✅ Maintain folder structure and avoid duplicates.
🚫 Do not copy-paste code without proper reference or attribution.
📢 Join Our Community

Be a part of our growing community 🌱 — learn, code, and grow together!

💬 Join on Discord

📢 Join on Telegram

💼 Follow on LinkedIn

💬 Join our WhatsApp Community

📺 Subscribe on YouTube

🐦 Follow on Twitter

📸 Follow on Instagram
☕ Support the Project

If you love this project and want to support future development, consider buying us a coffee:

<a href="https://www.buymeacoffee.com/mgoshwami1c"> <img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" height="50" width="210" alt="Buy Me A Coffee"> </a>
🏷️ GitHub Badges
---

## 🏷️ GitHub Badges  

![GitHub Repo stars](https://img.shields.io/github/stars/ghostmkg/dsa-code?style=for-the-badge)  
![GitHub forks](https://img.shields.io/github/forks/ghostmkg/dsa-code?style=for-the-badge)  
![GitHub issues](https://img.shields.io/github/issues/ghostmkg/dsa-code?style=for-the-badge)  
![GitHub pull requests](https://img.shields.io/github/issues-pr/ghostmkg/dsa-code?style=for-the-badge)  
![GitHub license](https://img.shields.io/github/license/ghostmkg/dsa-code?style=for-the-badge)  
![Contributions Welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=for-the-badge)  

---

**Happy Coding! 🚀**



Happy Coding! 🚀

---

### 🔚 Last Step:
1. Jab ye content paste kar lo, to niche **"Mark as resolved"** button pe click karo.  
2. Phir “**Commit merge**” pe click karo.  

Bas ho gaya 🎉  
Ab tera PR **conflict-free** ho gaya hai aur Hacktoberfest ke liye **valid contribution** count ho jayega ✅  

---

Chahe to tu mujhe ek screenshot bhej de editor ka (jab paste kar lega) — main confirm kar dunga ki sab perfect hai aur merge safe hai 👌



## /README_hi.md

# 📘 DSA-Code (डीएसए-कोड)

Read in other languages: [English](README.md)

**DSA-Code** 🎉 में आपका स्वागत है!
यह रिपॉजिटरी **डेटा स्ट्रक्चर्स और एल्गोरिदम (Data Structures and Algorithms - DSA)** के समाधानों का एक संग्रह है, जिन्हें **कई प्रोग्रामिंग भाषाओं** में लागू किया गया है।
इस रेपो का लक्ष्य सीखने वालों और योगदानकर्ताओं को डीएसए में अपनी समस्या-समाधान कौशल का पता लगाने, अभ्यास करने और सुधारने में मदद करना है।

---

## 🚀 मुख्य विशेषताएँ (Features)
- समाधान **कई प्रोग्रामिंग भाषाओं** में उपलब्ध हैं (C, C++, Python, Java, JavaScript, आदि)।
- शुरुआती (Beginner) के अनुकूल समस्या विवरण और संरचित समाधान।
- ओपन-सोर्स प्रोजेक्ट: योगदान करने के लिए सभी का स्वागत है।
- **हैकाtoberfest**, कोडिंग अभ्यास और इंटरव्यू की तैयारी के लिए एकदम सही।

प्रत्येक फ़ोल्डर में संबंधित प्रोग्रामिंग भाषा में डीएसए समस्याएं और समाधान शामिल हैं।

## 🤝 योगदान कैसे करें (How to Contribute)
हमें योगदान (Contributions) बहुत पसंद हैं! इस प्रोजेक्ट में योगदान करने के लिए कृपया नीचे दिए गए चरणों का पालन करें:

1. **रेपो को फोर्क करें (Fork the repo)**
अपने खुद की कॉपी बनाने के लिए `Fork` बटन (इस रिपॉजिटरी के ऊपर दाईं ओर) पर क्लिक करें।

2. **अपने फोर्क को क्लोन करें (Clone your fork)**

```
git clone https://github.com/<your-username>/dsa-code.git
cd dsa-code
```

3. **एक नई ब्रांच बनाएँ (Create a branch)**

```
git checkout -b feature-branch-name
```

4. **अपना कोड जोड़ें (Add your code)**
- सही भाषा फ़ोल्डर में जाएँ (उदाहरण के लिए, Python/, Java/)।
- अपनी डीएसए समस्या समाधान फ़ाइल जोड़ें।
- पठनीयता के लिए उचित फ़ाइल नामकरण और टिप्पणियाँ (comments) सुनिश्चित करें।

5. **परिवर्तनों को कमिट और पुश करें (Commit and push changes)**
```
git add .
git commit -m "Added solution for <problem-name> in <language>"
git push origin feature-branch-name
```
6. **एक पुल रिक्वेस्ट (PR) करें (Raise a Pull Request)**
- इस रेपो में Pull Requests टैब पर जाएँ।
- New Pull Request पर क्लिक करें।
- आपके द्वारा किए गए परिवर्तनों के बारे में एक स्पष्ट शीर्षक और विवरण (description) जोड़ें।
- पीआर सबमिट करें और समीक्षा (review) की प्रतीक्षा करें।

## 📝 योगदान दिशानिर्देश (Contribution Guidelines)
- स्वच्छ, अच्छी तरह से कमेंट किया हुआ और ठीक से स्वरूपित (formatted) कोड लिखें।
- केवल डीएसए-संबंधित समस्याएँ और समाधान जोड़ें।
- उचित संदर्भों के बिना कोड को कॉपी-पेस्ट न करें।
- फ़ोल्डर संरचना (structure) का सम्मान करें और डुप्लिकेट से बचें।

## 📢 हमारे समुदाय से जुड़ें (Join Our Community)
यह प्रोजेक्ट सभी के लिए खुला है। चाहे आप शुरुआती (beginner) हों या अनुभवी कोडर, योगदान करने के लिए आपका स्वागत है। आइए, एक साथ सीखें और आगे बढ़ें! 🌱

हमारे बढ़ते समुदाय का हिस्सा बनें और जुड़े रहें 🚀

- 🗨️ [Discord पर हमसे जुड़ें](https://discord.gg/YMJp48qbwR)
- 📢 [हमारे Telegram से जुड़ें](https://t.me/gwcacademy)
- 💼 [हमारे LinkedIn पेज को फॉलो करें](https://www.linkedin.com/company/gwc-academy/)
- 💬 [हमारे WhatsApp समुदाय से जुड़ें](https://whatsapp.com/channel/0029ValnoT1CBtxNi4lt8h1s)
- 📺 [YouTube पर सब्सक्राइब करें](https://www.youtube.com/c/growwithcode?sub_confirmation=1)
- 🐦 [Twitter पर फॉलो करें](https://x.com/goshwami_manish)
- 📸 [Instagram पर फॉलो करें](https://www.instagram.com/grow_with_code)

## ☕ प्रोजेक्ट को समर्थन दें (Support the Project)
<p>यदि आपको यह प्रोजेक्ट पसंद है और आप भविष्य के विकास (future development) का समर्थन करना चाहते हैं, तो मुझे एक कॉफी खरीदने पर विचार करें:</p><br>
<a href="https://www.buymeacoffee.com/mgoshwami1c"> <img align="left" src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" height="50" width="210" alt="mgoshwami1c" ></a>
  
  <br><br/>

### हैप्पी कोडिंग! 🚀


## /RadixSort.java

```java path="/RadixSort.java" 
/*
 * RadixSort.java
 *
 * Description:
 * Radix Sort is a non-comparison sorting algorithm that sorts numbers 
 * digit by digit starting from the least significant digit (LSD) to 
 * the most significant digit (MSD). It uses Counting Sort as a subroutine.
 *
 * Time Complexity: O(n * k) where k is the number of digits
 * Space Complexity: O(n + k)
 * Stable: Yes
 */

public class RadixSort {
    public static void radixSort(int[] arr) {
        if (arr.length == 0) return;

        // Find the maximum number to know number of digits
        int max = arr[0];
        for (int num : arr) {
            if (num > max) max = num;
        }

        // Apply counting sort for every digit (exp = 1, 10, 100, ...)
        for (int exp = 1; max / exp > 0; exp *= 10) {
            countingSortByDigit(arr, exp);
        }
    }

    private static void countingSortByDigit(int[] arr, int exp) {
        int n = arr.length;
        int[] output = new int[n];
        int[] count = new int[10]; // Digits 0–9

        // Store count of occurrences for each digit
        for (int num : arr) {
            int index = (num / exp) % 10;
            count[index]++;
        }

        // Cumulative count
        for (int i = 1; i < 10; i++) {
            count[i] += count[i - 1];
        }

        // Build the output array (traverse backwards for stability)
        for (int i = n - 1; i >= 0; i--) {
            int index = (arr[i] / exp) % 10;
            output[count[index] - 1] = arr[i];
            count[index]--;
        }

        // Copy output to original array
        System.arraycopy(output, 0, arr, 0, n);
    }
}

```

## /Roman to Integer.cpp

```cpp path="/Roman to Integer.cpp" 
class Solution {
public:
    int romanToInt(string s) {
        unordered_map<char,int> value = {
            {'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}
        };
        int res = 0;
        for(int i = 0;i<s.length();i++){
            if(i+1 < s.length() && value[s[i]]<value[s[i+1]]){
                res += (value[s[i+1]] - value[s[i]]);
                i++;
            }else{
                res += value[s[i]];
            }
        }
        return res;
    }
};

```

## /SQL/A1.sql

```sql path="/SQL/A1.sql" 
CREATE TABLE Employee (
	EmployeeID INT PRIMARY KEY,
	FirstName VARCHAR(50),
	LastName VARCHAR(50),
	Department VARCHAR(50),
	Salary NUMERIC(10,2),
	HireDate DATE,
	City VARCHAR(50),
	Age INT,
	Gender CHAR(1)
);

INSERT INTO Employee(EmployeeID,FirstName,LastName,Department,Salary,HireDate,City,Age,Gender)
Values
(1, 'John', 'Doe', 'IT', 75000.00, '15-MAY-20', 'New York', 30, 'M'),
(2, 'Jane', 'Smith', 'HR', 68000.00, '22-AUG-18', 'Los Angeles', 28, 'F'),
(3, 'Mark', 'Brown', 'Finance', 85000.00, '10-NOV-18', 'Chicago', 35, 'M'),
(4, 'Emily', 'Davis', 'Marketing', 72000.00, '12-MAR-19', 'Houston', 32, 'F'),
(5, 'Michael', 'Wilson', 'IT', 78000.00, '18-JUL-21', 'San Francisco', 29, 'M'),
(6, 'Sarah', 'Johnson', 'Finance', 91000.00, '24-FEB-16', 'New York', 40, 'F'),
(7, 'Chris', 'Lee', 'HR', 60000.00, '10-JAN-22', 'Seattle', 26, 'M'),
(8, 'Anna', 'White', 'Marketing', 68000.00, '05-SEP-20', 'Denver', 31, 'F'),
(9, 'David', 'Hall', 'Finance', 95000.00, '30-JUN-15', 'Chicago', 45, 'M'),
(10, 'Laura', 'Green', 'IT', 72000.00, '01-APR-0', 'Austin', 25, 'F');

SELECT column_name, data_type, character_maximum_length
FROM information_schema.columns
WHERE table_name = 'Employee';

SELECT * FROM Employee

SELECT * FROM Employee 
WHERE Department='IT';

SELECT * FROM Employee
WHERE Salary>75000;

SELECT * FROM Employee
WHERE HireDate> '2020-01-01';

SELECT * FROM Employee
WHERE City='Chicago';

SELECT * FROM EmplOyee
WHERE Gender='M';
```

## /SQL/A2.sql

```sql path="/SQL/A2.sql" 
CREATE TABLE Customer (
 CustomerID INT PRIMARY KEY,
 FirstName VARCHAR(50),
 LastName VARCHAR(50),
 City VARCHAR(50),
 Age INT,
 Email VARCHAR(100)
);

INSERT INTO Customer VALUES
(1, 'John', 'Doe', 'New York', 28, 'john.doe@example.com'),
(2, 'Jane', 'Smith', 'Los Angeles', 34, 'jane.smith@gmail.com'),
(3, 'Alice', 'Johnson', 'Chicago', 22, 'alicej@yahoo.com'),
(4, 'Bob', 'Williams', 'Houston', 45, 'bob_w@outlook.com'),
(5, 'Charlie', 'Brown', 'Phoenix', 31, 'charlie.b@example.com'),
(6, 'David', 'Lee', 'Philadelphia', 29, 'davidlee@gmail.com'),
(7, 'Eve', 'Clark', 'San Diego', 37, 'eve.clark@live.com'),
(8, 'Frank', 'Moore', 'Dallas', 40, 'fmoore@yahoo.com'),
(9, 'Grace', 'Taylor', 'San Jose', 25, 'gracet@gmail.com'),
(10, 'Henry', 'Martin', 'Austin', 33, 'henrym@gmail.com');

--1
SELECT * FROM Customer
WHERE Age>30 AND City='Phoenix';

--2
SELECT * FROM Customer
WHERE Age<30 OR City='New York';

--3
SELECT * FROM Customer
WHERE NOT City='Chicago';

--4
SELECT * FROM Customer
WHERE Age>25 AND NOT City='Dallas';

--5
SELECT * FROM Customer
WHERE City='Los Angeles' OR City='San Diego';

--6
SELECT * FROM Customer
WHERE NOT City='New York' AND AGE<35;

--7
SELECT * FROM Customer
WHERE FirstName LIKE 'J%';

--8
SELECT  * FROM Customer
WHERE LastName LIKE '%n';

--9
SELECT * FROM Customer
WHERE Email LIKE '%gmail%';

--10
SELECT * FROM Customer
WHERE FirstName LIKE '%a%';

--11
SELECT * FROM Customer
WHERE Email LIKE '%.com';

--12
SELECT * FROM Customer
WHERE LENGTH(LastName)=5;

--13
SELECT * FROM Customer
ORDER BY Age ASC;

--14
SELECT * FROM Customer
ORDER BY FirstName DESC;

--15
SELECT * FROM Customer
ORDER BY City,Age;

--16
SELECT * FROM Customer
ORDER BY LastName, FirstName;

--17
SELECT * FROM Customer
ORDER BY Email DESC;

--18
SELECT * FROM Customer
WHERE FirstName='A' OR FirstName='B' AND Age>25;

--19
SELECT * FROM Customer
WHERE NOT CITY='Austin' AND Email LIKE '%yahoo%';

--20
SELECT * FROM Customer
WHERE LastName LIKE 'M%' OR LastName LIKE '%n'
ORDER BY FirstName;

```

## /SQL/A3.sql

```sql path="/SQL/A3.sql" 
INSERT INTO Product VALUES (1, 'Apple iPhone 14', 'Electronics', 79999.00, 20);
INSERT INTO Product VALUES (2, 'Samsung Galaxy S22', 'Electronics', 69999.00, 25);
INSERT INTO Product VALUES (3, 'Sony Headphones', 'Accessories', 1999.00, 100);
INSERT INTO Product VALUES (4, 'HP Laptop', 'Computers', 55999.00, 15);
INSERT INTO Product VALUES (5, 'Dell Mouse', 'Accessories', 499.00, 200);
INSERT INTO Product VALUES (6, 'Canon Camera', 'Electronics', 45999.00, 10);
INSERT INTO Product VALUES (7, 'Apple Watch', 'Wearables', 30999.00, 30);
INSERT INTO Product VALUES (8, 'Logitech Keyboard', 'Accessories', 1299.00, 150);
INSERT INTO Product VALUES (9, 'Samsung TV', 'Electronics', 55999.00, 5);
INSERT INTO Product VALUES (10, 'Mi Band', 'Wearables', 1999.00, 80);

SELECT * FROM Product

--1
SELECT * FROM Product
WHERE ProductName LIKE 'Apple%';

--2
SELECT *  Product
WHERE ProductName LIKE '%Watch';

--3
SELECT * FROM Product
WHERE ProductName LIKE '%Samsung%';

--4
SELECT * FROM Product
WHERE Category='Electronics' OR Category='Computers';

--5
SELECT * FROM Product
WHERE ProductID =1 OR ProductID =3 OR ProductID =5;

--6
SELECT * FROM Product
WHERE Price>=1000 AND Price<=20000;

--7
SELECT * FROM Product
WHERE Quantity>=10 AND Quantity<=50;

--8
SELECT * FROM Product
WHERE Category='Electronics' AND Price<5000;

--9
SELECT * FROM Product
WHERE Quantity>50 AND Price<5000;

--10
SELECT * FROM Product
WHERE Quantity<20 OR Price>5000;

--11
SELECT * FROM Product
WHERE Category='Accessories' OR Category='Wearables';

--12
SELECT * FROM Product
WHERE NOT Category='Electronics';

--13
SELECT * FROM Product
WHERE Price>=1000 AND Price<=20000;

--14
SELECT * FROM Product
ORDER BY Price ASC;

--15
SELECT * FROM Product
ORDER BY Quantity DESC;

--16
SELECT * FROM Product
ORDER BY Category, ProductName;

--17
UPDATE Product
SET Price = 599
WHERE ProductName = 'Dell Mouse';

--18
UPDATE Product
SET Quantity = Quantity + 20
WHERE ProductName = 'Mi Band';

--19
UPDATE Product
SET Price = Price + 2500
WHERE Category='Wearables';

--20
UPDATE Product
SET Quantity = Quantity -5
WHERE Category = 'Electronics';

-21

```

## /SQL/A4.sql

```sql path="/SQL/A4.sql" 
CREATE TABLE ACCOUNT (
 Account_ID INT PRIMARY KEY, 
 Customer_Name VARCHAR(100),
 Account_Type VARCHAR(20),
 Balance DECIMAL(10, 2),
 Branch_Name VARCHAR(100)
 );

 INSERT INTO ACCOUNT VALUES(101,'Alice Sharma','Savings','50000.00','Delhi');
 INSERT INTO ACCOUNT VALUES(102,'Ravi Kumar','Current','120000.00','Mumbai');
 INSERT INTO ACCOUNT VALUES(103,'Sonia Mehta','Savings','75000.00','Chennai');
 INSERT INTO ACCOUNT VALUES(104,'Arjun Singh','Current','30000.00','Delhi');
 INSERT INTO ACCOUNT VALUES(105,'Priya Das','Savings','62000.00','Bangalore');

--1
ALTER TABLE ACCOUNT ADD Email VARCHAR(50);

--2
ALTER TABLE ACCOUNT ADD ACccount_OpeningDate Date;

--3
ALTER TABLE ACCOUNT 
ALTER COLUMN Customer_Name TYPE VARCHAR(150);

--4
RENAME TABLE ACCOUNT TO BANK_ACCOUNT;

```

## /SQL/ActiveUsersInLast30Days.sql

```sql path="/SQL/ActiveUsersInLast30Days.sql" 
SELECT DISTINCT UserId
FROM UserLogins
WHERE LoginDate >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY);

```

## /SQL/AverageDepartmentSalary.sql

```sql path="/SQL/AverageDepartmentSalary.sql" 
--Problem: Find employees earning above the average salary of their department.
SELECT e.Name, e.Salary, d.Name AS Department
FROM Employee e
JOIN Department d ON e.DepartmentId = d.Id
WHERE e.Salary > (
    SELECT AVG(Salary)
    FROM Employee
    WHERE DepartmentId = e.DepartmentId
);

```

## /SQL/BiggestSingleNumber.sql

```sql path="/SQL/BiggestSingleNumber.sql" 
select max(num) as num
from(
    select num from MyNumbers 
    group by num 
    having count(num) = 1
) as uniqueNos;
```

## /SQL/CityWithHighestAverageSalary.sql

```sql path="/SQL/CityWithHighestAverageSalary.sql" 
--Find the city with the highest average employee salary.
SELECT City, AVG(Salary) AS AvgSalary
FROM Employee
GROUP BY City
ORDER BY AvgSalary DESC
LIMIT 1;

```

## /SQL/CombineTwoTables.sql

```sql path="/SQL/CombineTwoTables.sql" 
select firstName, lastName, city, state from Person p left join Address a on p.personId = a.personId;
```

## /SQL/ConsecutiveNumbers.sql

```sql path="/SQL/ConsecutiveNumbers.sql" 
--Problem: Find numbers appearing consecutively at least 3 times.
SELECT DISTINCT num AS ConsecutiveNums
FROM Logs l1
JOIN Logs l2 ON l1.Id = l2.Id - 1 AND l1.Num = l2.Num
JOIN Logs l3 ON l2.Id = l3.Id - 1 AND l2.Num = l3.Num;
select distinct p.num as ConsecutiveNums 
from Logs p, Logs q, Logs r
where
p.id = q.id - 1 and
q.id = r.id - 1 and
p.num = q.num and
q.num = r.num;

-- Problem: Find numbers appearing consecutively at least 3 times.
SELECT DISTINCT num AS ConsecutiveNums
FROM Logs l1
JOIN Logs l2 ON l1.Id = l2.Id - 1 AND l1.Num = l2.Num
JOIN Logs l3 ON l2.Id = l3.Id - 1 AND l2.Num = l3.Num;

select distinct p.num as ConsecutiveNums
from Logs p, Logs q, Logs r
where
    p.Id = q.Id - 1 and
    q.Id = r.Id - 1 and
    p.num = q.num and
    q.num = r.num;

```

## /SQL/CountSalaryCategories.sql

```sql path="/SQL/CountSalaryCategories.sql" 
select 'Low Salary' as category, count(income) as accounts_count 
from Accounts where income < 20000

union all

select 'Average Salary' as category, count(income) as accounts_count 
from Accounts where income <= 50000 and income >= 20000

union all

select 'High Salary' as category, count(income) as accounts_count 
from Accounts where income > 50000


```

## /SQL/CustomerRetentionRate.sql

```sql path="/SQL/CustomerRetentionRate.sql" 
--Find the percentage of customers who placed more than one order.
SELECT 
  ROUND(
    (COUNT(DISTINCT CASE WHEN order_count > 1 THEN CustomerId END) * 100.0 /
     COUNT(DISTINCT CustomerId)), 2
  ) AS RetentionRate
FROM (
    SELECT CustomerId, COUNT(*) AS order_count
    FROM Orders
    GROUP BY CustomerId
) AS customer_orders;

```

## /SQL/CustomerWhoVisitedButDidNotMakeAnyTransaction.sql

```sql path="/SQL/CustomerWhoVisitedButDidNotMakeAnyTransaction.sql" 
-- Write a solution to find the IDs of the users who visited without making any transactions and the number of times they made these types of visits.
-- leetcode 1581

select 
    v.customer_id,
    count(v.visit_id) as count_no_trans
from Visits v
left join Transactions t
on v.visit_id = t.visit_id
where t.amount is null
group by v.customer_id;

```

## /SQL/CustomersWhoNeverOrder.sql

```sql path="/SQL/CustomersWhoNeverOrder.sql" 
--Problem: Find all customers who never placed an order.
SELECT c.Name AS Customers
FROM Customers c
LEFT JOIN Orders o ON c.Id = o.CustomerId
WHERE o.Id IS NULL;

```

## /SQL/DeleteDuplicateEmails.sql

```sql path="/SQL/DeleteDuplicateEmails.sql" 
delete p from Person p, Person q
where
p.email = q.email and p.id > q.id;
```

## /SQL/DepartmentHighestSalary.sql

```sql path="/SQL/DepartmentHighestSalary.sql" 
--Problem: Find the employee(s) who have the highest salary in each department.
SELECT d.Name AS Department,
       e.Name AS Employee,
       e.Salary
FROM Employee e
JOIN Department d ON e.DepartmentId = d.Id
WHERE (e.Salary, e.DepartmentId) IN (
    SELECT MAX(Salary), DepartmentId
    FROM Employee
    GROUP BY DepartmentId
);

```

## /SQL/DepartmentTop3Salaries.sql

```sql path="/SQL/DepartmentTop3Salaries.sql" 
select d.name as Department, e1.name as Employee, e1.Salary
from Employee e1 join Department d
on e1.departmentId = d.id
where 3 > (select count(distinct(e2.Salary)) from Employee e2
            where e1.departmentId = e2.departmentId
            and e2.Salary > e1.Salary);

```

## /SQL/DepartmentTopThreeSalaries.sql

```sql path="/SQL/DepartmentTopThreeSalaries.sql" 
WITH RankedSalaries AS (
    SELECT 
        d.Name AS Department,
        e.Name AS Employee,
        e.Salary,
        DENSE_RANK() OVER (PARTITION BY d.Id ORDER BY e.Salary DESC) AS rnk
    FROM Employee e
    JOIN Department d ON e.DepartmentId = d.Id
)
SELECT Department, Employee, Salary
FROM RankedSalaries
WHERE rnk <= 3;

```

## /SQL/DuplicateEmails.sql

```sql path="/SQL/DuplicateEmails.sql" 
select distinct p.email from person p, person q
where 
p.email = q.email and p.id > q.id;
```

## /SQL/DuplicateProducts.sql

```sql path="/SQL/DuplicateProducts.sql" 
--Problem: Find product names that appear more than once.
SELECT ProductName, COUNT(*) AS Count
FROM Products
GROUP BY ProductName
HAVING COUNT(*) > 1;

```

## /SQL/EmployeeBonus.sql

```sql path="/SQL/EmployeeBonus.sql" 
select name, bonus from Employee left join Bonus on Employee.empId = Bonus.empId where bonus < 1000 OR bonus is null;

```

## /SQL/EmployeeManagerHierarchy.sql

```sql path="/SQL/EmployeeManagerHierarchy.sql" 
SELECT e.Name AS Employee,
       m.Name AS Manager
FROM Employee e
LEFT JOIN Employee m ON e.ManagerId = m.Id;

```

## /SQL/EmployeeProjectCount.sql

```sql path="/SQL/EmployeeProjectCount.sql" 
--Problem: Find employees working on more than 2 projects.
SELECT e.EmployeeId
FROM EmployeeProject e
GROUP BY e.EmployeeId
HAVING COUNT(e.ProjectId) > 2;

```

## /SQL/EmployeesWithoutBonus.sql

```sql path="/SQL/EmployeesWithoutBonus.sql" 
--List employees who have never received a bonus.
SELECT e.Name
FROM Employee e
LEFT JOIN Bonus b ON e.Id = b.EmployeeId
WHERE b.BonusAmount IS NULL;

```

## /SQL/ExchangeSeats.sql

```sql path="/SQL/ExchangeSeats.sql" 
select
case
when id % 2 = 1 and id + 1 <= (select max(id) from Seat) then id + 1
when id % 2 = 0 then id - 1
else id
end 
as id, student from Seat order by id

```

## /SQL/FindFollowersCount.sql

```sql path="/SQL/FindFollowersCount.sql" 
select distinct user_id, count(*) as followers_count 
from followers
group by user_id
order by user_id;
```

## /SQL/FixNamesInTable.sql

```sql path="/SQL/FixNamesInTable.sql" 
select user_id, concat(upper(substring(name, 1, 1)), lower(substring(name, 2, length(name)-1))) as name from Users order by user_id;
```

## /SQL/MonthlyActiveUsers.sql

```sql path="/SQL/MonthlyActiveUsers.sql" 
SELECT DATE_FORMAT(ActivityDate, '%Y-%m') AS Month,
       COUNT(DISTINCT UserId) AS ActiveUsers
FROM UserActivity
GROUP BY DATE_FORMAT(ActivityDate, '%Y-%m')
ORDER BY Month;

```

## /SQL/MonthlyRevenueGrowth.sql

```sql path="/SQL/MonthlyRevenueGrowth.sql" 
--Calculate month-over-month revenue growth percentage.
WITH monthly_sales AS (
    SELECT DATE_FORMAT(OrderDate, '%Y-%m') AS Month,
           SUM(Amount) AS Revenue
    FROM Orders
    GROUP BY DATE_FORMAT(OrderDate, '%Y-%m')
)
SELECT Month,
       Revenue,
       ROUND(((Revenue - LAG(Revenue) OVER (ORDER BY Month)) / 
              LAG(Revenue) OVER (ORDER BY Month)) * 100, 2) AS GrowthPercent
FROM monthly_sales;

```

## /SQL/MostPurchasedProduct.sql

```sql path="/SQL/MostPurchasedProduct.sql" 
SELECT ProductId, COUNT(*) AS TotalPurchases
FROM Orders
GROUP BY ProductId
HAVING COUNT(*) = (
    SELECT MAX(cnt)
    FROM (
        SELECT COUNT(*) AS cnt
        FROM Orders
        GROUP BY ProductId
    ) AS sub
);

```


The content has been capped at 50000 tokens. The user could consider applying other filters to refine the result. The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.
Copied!