├── .github ├── ISSUE_TEMPLATE │ ├── bug.md │ ├── documentation.md │ ├── feature.md │ └── proposal.md ├── auto_assigner_config.yml ├── issues_labeler.yml ├── labeler.yml ├── pull_request_template.md ├── stale.yml └── workflows │ ├── Auto_Issue_Closer.yml │ ├── Issue-assign.yml │ ├── Issue_watcher.yml │ ├── greetings.yml │ ├── issues_labeler.yml │ ├── labeler.yml │ ├── reviewer_auto_assigner.yml │ └── stale.yml ├── .gitignore ├── .vscode └── settings.json ├── 2D Arrays ├── Set Matrix Zero.cpp ├── StairCaseSearch.py ├── count_negative_in_sorted_matrix.cpp ├── count_negative_numbers_in_sorted_matrix.cpp ├── destination_city.cpp ├── equal_matrices.c ├── lucky_numbers_in_a_matrix.cpp ├── matrix_find_string_row_wise.c ├── matrix_rotation.cpp ├── matrix_spiral.cpp ├── search_2d_matrix.cpp ├── search_2d_matrix2.cpp ├── sum_of_all_submatrices.cpp ├── sum_of_all_submatrices_2.cpp ├── sum_of_all_submatrices_3.cpp ├── sum_of_matrix_Q_queries.cpp └── wave_print.cpp ├── Arrays ├── Array Reversal.c ├── Array Reversal.py ├── CommonElements.cpp ├── CommonElements.py ├── CommonElementsOptimal.cpp ├── KLargestpairs.py ├── Kadane's_Algorithm.cpp ├── LeftRightSumEqual.cpp ├── Minimize_the_height.cpp ├── N_unique_numbers_sum_upto_zero.cpp ├── QueryingArray.cpp ├── ShortestContinuousSubarray.py ├── duplicates_in_array.cpp ├── duplicates_in_array.py ├── element_left_smaller_right_greater.cpp ├── first_missing_positive.cpp ├── index_of_an_extra_element.cpp ├── kadane's_algorithm.c ├── largest_sum_subarray.java ├── leaders_in_an_array.cpp ├── max_prod_of_two_elements.cpp ├── merge_two_sorted_arrays.cpp ├── missing_number_in_array.cpp ├── peek_element.cpp ├── remove_duplicates_from_sorted_array.cpp ├── remove_duplicates_from_sorted_array.py ├── replace_elements_with_greatest_element_on_right.cpp ├── sort_an_array_of_0s_1s_and_2s.cpp ├── sort_elements_of_array_by_freq.cpp ├── subset_of_array.cpp ├── subset_of_array.py ├── sum_of_elements_to_right.cpp ├── sum_of_other_elements.cpp ├── sum_of_three_values.c++ └── zero_sum_subarray.java ├── Backtracking ├── Print_all_permutations_of_string.java ├── eightQueen.c ├── rat_maze.cpp └── sudoku.c ├── Bit Manipulation ├── Bit_Difference.cpp ├── Count_total_set_bits.cpp ├── Find_position_of_set_bit.cpp ├── K-th_bit_is_set_or_not.cpp ├── Non_Repeating_Numbers.cpp ├── Number_of_1_Bits.cpp └── Power_of_2.cpp ├── CONTRIBUTING.md ├── CodeVita Problems ├── 7x7-sudoku.c ├── Forest Fire │ ├── cv_forest_bfs.c │ └── cv_forest_bfs_VV2.c ├── Grooving monkeys │ ├── gm v1 naive.c │ ├── gm v2 optimized 1.c │ └── gm v2 optimized 2 using a flag.c ├── Image segmentation.pdf ├── Jurassic park │ └── cv_jurasic_park.c ├── Rat Path Maze.c ├── codu loves sum.c ├── consecutive_prime_sum.cpp ├── constellation stars.c ├── count pairs.c ├── kth_largest_factor.cpp ├── minimize_the_sum.c ├── minimum_gifts.c ├── path_through_graph.cpp ├── single_lane_highway_question.c └── string_pair.c ├── Complex_numbers.cpp ├── DSA 450 GFG ├── reverse_an_array.cpp ├── BTtoBST.py ├── BuyandSell.py ├── CountAndSay.py ├── DeleteNodeinBST.py ├── DiameterOfBinTree.py ├── HeightOfBinTree.py ├── InOrderTraversal-rec.py ├── InorderTraversal-Iterative.py ├── PreOrder-recursive.py ├── PreOrder_iterative.py ├── PrintAnagrams.py ├── TrapRainWater.py ├── chocolate_distribution.py ├── lowest_common_ancestor.py ├── max_and_min_of_array.py ├── max_sum_bottom_up.py ├── max_sum_memoization.py ├── maximum and minimum of an array.cpp ├── maxones.py ├── merge_intervals.py ├── move all negative numbers.cpp ├── move_all_neg_numbers.py ├── next_permutation.py ├── post-ord-iterative.py ├── post-order-rec.py ├── reverse_an_array.py ├── rotate_by_90.py ├── row_with_max_ones.py ├── search_elements_in_a_matrix.py ├── snake_pattern.py ├── spiral_matrix.py ├── subtree_of_another_tree.py └── vertical_order_traversal.py ├── Data Structures ├── Graphs │ ├── BFSTraversal.cpp │ ├── Center_Of_Star_Graph.cpp │ ├── DFSTraversal │ │ ├── DFSTraversal.cpp │ │ └── in.txt │ ├── Khan_algo.py │ ├── RottenOranges.cpp │ ├── Topological_Sort.cpp │ ├── WordBoggle.cpp │ ├── dijkstra.cpp │ └── isGraphBipartite.cpp ├── Linked Lists │ ├── Circular Doubly Linked Lists │ │ ├── delete_at_begin.cpp │ │ ├── delete_at_end.cpp │ │ ├── insert_at_begin.cpp │ │ ├── insert_at_end.cpp │ │ ├── recursive_reverse.cpp │ │ └── reverse.cpp │ ├── Circular Linked Lists │ │ ├── delete_at_begin.cpp │ │ ├── delete_at_end.cpp │ │ ├── insert_at_begin.cpp │ │ ├── insert_at_end.cpp │ │ ├── recursive_reverse.cpp │ │ └── reverse.cpp │ ├── Detet_Cycle_In_LinkedList.cpp │ ├── Doubly Linked List │ │ ├── .DS_Store │ │ ├── delete_at_begin.cpp │ │ ├── delete_at_end.cpp │ │ ├── double linkedlist.cpp │ │ ├── insert_at_begin.cpp │ │ ├── insert_at_end.cpp │ │ ├── recursive_reverse.cpp │ │ └── reverse_a_double_linkedlist.cpp │ └── Singly Linked List │ │ ├── .DS_Store │ │ ├── Flattening_a_link_list.cpp │ │ ├── SLL insertion.cpp │ │ ├── SLL.cpp │ │ ├── Swap_nodes.py │ │ ├── binary_number_linkedlist_integer.cpp │ │ ├── check_if_linkedlist_is_a_palindrome.cpp │ │ ├── check_linkedlist_palindrome.cpp │ │ ├── detect_loop_in_linkedlist.cpp │ │ ├── merge_two_sorted_linkedlist.cpp │ │ ├── middle_of_linkedlist.cpp │ │ ├── nth_node_from_last.cpp │ │ ├── remove_duplicate_element_sorted_linkedlist.cpp │ │ ├── remove_duplicates_unordered_linkedlist.cpp │ │ ├── reverse_linkedlist.cpp │ │ ├── rotate_linkedlist.cpp │ │ └── segregate_even and_odd_nodes_LL.cpp ├── Queues │ ├── priority_queue_max.cpp │ └── priority_queue_min.cpp ├── Stacks │ ├── BalancedParantheses.cpp │ ├── Largest_rectangle_area_under_histogram.cpp │ ├── Sort_stack_using_recursion.cpp │ └── postfix_evaluation.c └── Trees │ ├── Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp │ ├── Diameter_Binary_Tree.cpp │ ├── binary_search_tree.cpp │ ├── binary_tree_to_bst.cpp │ ├── binary_tree_traversal.cpp │ ├── bottom_view_of_binary_tree.cpp │ ├── check_balanced_tree.cpp │ ├── check_for_bst.cpp │ ├── check_if_subtree.cpp │ ├── check_if_tree_isomorphic.cpp │ ├── check_two_trees_identical.cpp │ ├── delete_leaves_with_given_value.cpp │ ├── invert_a_binary_tree.cpp │ ├── level_order_traversal.cpp │ ├── lowest_common_ancestor_binary_tree.cpp │ ├── lowest_common_ancestor_bst.cpp │ ├── merge_two_binary_trees.cpp │ ├── min_bs.cpp │ ├── sum_tree.cpp │ └── tree_from_postorder_and_inorder.cpp ├── Divide and Conquer ├── DCPower.java ├── PowerMem.java └── PowerofN.java ├── Dynamic Programming ├── ClimbingStairs_bottom_up.py ├── ClimbingStairs_memoization.py ├── CoinChange.py ├── Collinearity_of_three_points.cpp ├── FibonacciMem.java ├── FibonacciTab.java ├── FibonacciTabEff.java ├── Klee's Algorithm.cpp ├── Knapsack_01_TabulationMethod.cpp ├── LCS_Memoization.c ├── LCS_Recursion.c ├── LCS_Tabulation.c ├── Longest_common_substring.cpp ├── MinPathSum.java ├── MirrorOfBinTree.py ├── binomial_coefficient.cpp ├── knapsack_01.cpp ├── sliding_window_sum.cpp └── sum_of_subsets.c ├── GCD of two numbers ├── Alternative GCD Algorithm.c ├── Euclid's Algorithm.c ├── GCD Using Recursion.c └── Normal GCD Algorithm.c ├── Games ├── game_of_primes.cpp └── zombie_world.cpp ├── General Questions ├── CLL SLL Wipro.c ├── Checking-if-given-array-is-max-heap.cpp ├── Difficult_pattern.c ├── Difficult_pattern2.c ├── Difficult_pattern3.c ├── Difficult_pattern4.c ├── Plus_One.cpp ├── Round-Robin-Algorithm.c ├── christmas_tree.c ├── find_pair_difference.c ├── inner_reduce_pattern.cpp ├── intersection_of_arrays.c ├── logic_pyramid.c ├── longest_progressive_sequence.c ├── merge_sort.c ├── pattern_1.c ├── pattern_1.py ├── pattern_2.c ├── pattern_2.py ├── pattern_3.c ├── pattern_3.py ├── pattern_4.c ├── pattern_4.py ├── pattern_5.c ├── pattern_5.py └── special_pattern.c ├── Greedy ├── Kruskal’s Minimum Spanning Tree.cpp ├── Prim’s Minimum Spanning Tree.cpp └── n_meetings_in_a_room.cpp ├── Hackerrank solutions └── 10 days of js │ ├── Arithmatic_operator.js │ ├── Arrays.js │ ├── Arrow_functions.js │ ├── Bitwise_Operators.js │ ├── Classes.js │ ├── Conditional_statement_(if-else).js │ ├── Conditional_statement_switch.js │ ├── Create_Rectangle_Object.js │ ├── Functions.js │ ├── Inheritance.js │ ├── Let_and_const.js │ ├── Loops.js │ ├── Throw.js │ ├── Try_catch_finally.js │ └── javascript_dates.js ├── Hashing ├── chef_and_subarrays.cpp └── sequence_pair_weight.cpp ├── LICENSE ├── Numbers ├── Basic_Programs │ ├── abundant_num.c │ ├── armstrong_number.c │ ├── leap_year.c │ ├── palindrome_num.c │ ├── perfect_num.c │ ├── prime_number.c │ ├── prime_number_using_recursion.c │ ├── reverse_num.c │ └── strong_num.c ├── BinarytoDecimal.cpp ├── ClosestNumber.c ├── DecimaltoBinary.cpp ├── FindDivisors.cpp ├── FindDivisors.py ├── JumpingNumbers.cpp ├── LargerNumber.cpp ├── LargerNumber.py ├── NumberofBinDigits.java ├── PerfectNumber.cpp ├── RomantoInteger.py ├── Unique_Digits_Count.cpp ├── alternate_sort_of_numbers.cpp ├── armstrong_number.cpp ├── factorial_of_a_number.c ├── factorial_of_a_number.py ├── factorial_of_a_number_recursion.c ├── factorial_of_a_number_recursion.py ├── fibonacci_series.c ├── fibonacci_series.py ├── lucky_number.cpp ├── num to words step 2 as a function.c ├── powers_of_two.cpp ├── self_dividing_numbers.cpp ├── sum_of_two_primes.cpp └── words of numbers sorted print num also.c ├── OOPs └── Polymorphism │ ├── function_overloading.cpp │ └── operator_overloading.cpp ├── Passwords ├── 1d_password.cpp └── 2d_password.cpp ├── README.md ├── Searching Algorithms ├── Jump_search.c ├── Ternary_search.c ├── binary_search.c ├── binary_search.js ├── jump_search.cpp ├── linear_search.cpp └── linear_search.js ├── Sorting Algorithms ├── Bubble_sort.c ├── Bucket Sort.py ├── bubble_sort.cpp ├── bubble_sort.py ├── bucket_sort.cpp ├── counting_sort.cpp ├── heap_sort.cpp ├── insertion_sort.cpp ├── insertion_sort.py ├── merge_sort.cpp ├── quick_sort.cpp ├── quick_sort.py ├── radix_sort.cpp ├── selection_sort.cpp ├── selection_sort.py ├── shell_sort.cpp └── wavesort.cpp ├── Standard Template Library ├── STL.cpp ├── collecting_candies.cpp ├── queue_example.cpp └── stack_example.cpp ├── Strings ├── Count_word.c ├── Extract_the_Number_from_String.cpp ├── Reverse_vowels_of_a_string.cpp ├── Stuck Keyboard │ ├── .DS_Store │ ├── StuckKeyboard.py │ └── stuck_keyboard.cpp ├── characters_or_sum_digits.cpp ├── check_password.cpp ├── cyclic_palindrome .png ├── decrypt_string_alpha_to_int_mapping.cpp ├── findAndReplacePattern.cpp ├── removePalindromicSubsequences.java ├── remove_character.cpp ├── reverse_words_in_a_string.cpp ├── string_anagram.cpp ├── string_halves_are_alike.cpp ├── string_rotation.cpp ├── string_shift_operations.cpp ├── substring_index.cpp ├── super_ascii_checker .png └── super_ascii_checker.cpp ├── _config.yml └── images └── devincept.gif /.github/ISSUE_TEMPLATE/bug.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🐛 Bug Report 3 | about: Submit a bug report to help us improve 4 | labels: "bug" 5 | --- 6 | 7 | ## 🐛 Bug Report 8 | 9 | (A clear and concise description of what the bug is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/smv1999/CompetitiveProgrammingQuestionBank/blob/master/CONTRIBUTING.md)? 12 | 13 | (Write your answer here.) 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/documentation.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 📚 Documentation 3 | about: Report an issue related to documentation 4 | labels: "documentation" 5 | --- 6 | 7 | ## 📚 Documentation 8 | 9 | (A clear and concise description of what the issue is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/smv1999/CompetitiveProgrammingQuestionBank/blob/master/CONTRIBUTING.md)? 12 | 13 | (Write your answer here.) 14 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 🚀 Feature 3 | about: Submit a proposal for a new feature 4 | labels: "feature" 5 | --- 6 | 7 | ## 🚀 Feature 8 | 9 | (A clear and concise description of what the feature is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/smv1999/CompetitiveProgrammingQuestionBank/blob/master/CONTRIBUTING.md)? 12 | 13 | (Write your answer here.) 14 | 15 | ## Motivation 16 | 17 | (Please outline the motivation for the proposal.) 18 | 19 | ## Pitch 20 | 21 | (Please explain why this feature should be implemented and how it would be used.) 22 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/proposal.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 💥 Proposal 3 | about: Propose a non-trivial change to Competitive Programming Question Bank 4 | labels: "proposal" 5 | --- 6 | 7 | ## 💥 Proposal 8 | 9 | (A clear and concise description of what the proposal is.) 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/smv1999/CompetitiveProgrammingQuestionBank/blob/master/CONTRIBUTING.md)? 12 | 13 | (Write your answer here.) 14 | -------------------------------------------------------------------------------- /.github/auto_assigner_config.yml: -------------------------------------------------------------------------------- 1 | # Set to true to add reviewers to pull requests 2 | addReviewers: true 3 | 4 | # Set to true to add assignees to pull requests 5 | addAssignees: false 6 | 7 | # A list of reviewers to be added to pull requests (GitHub user name) 8 | reviewers: 9 | - smv1999 10 | - Saviour1001 11 | -------------------------------------------------------------------------------- /.github/issues_labeler.yml: -------------------------------------------------------------------------------- 1 | C: 2 | - "( C )" 3 | C-Plus-Plus: 4 | - "(C-Plus-Plus|CPP|cpp|C++)" 5 | C-Sharp: 6 | - "(C-Sharp|csharp|C#)" 7 | Go: 8 | - "(Go|GO|Golang)" 9 | Java: 10 | - "(Java|java)" 11 | JavaScript: 12 | - "(JavaScript|JAVASCRIPT|Javascript|javascript|JS|js)" 13 | Python: 14 | - "(Python|PYTHON|python)" 15 | Q-Sharp: 16 | - "(Q-Sharp|qsharp|Q#)" 17 | enhancement: 18 | - "(enhancement)" 19 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | C: 2 | - "( C )" 3 | C-Plus-Plus: 4 | - "(C-Plus-Plus|CPP|cpp|Cpp|C++)" 5 | C-Sharp: 6 | - "(C-Sharp|csharp|C#|C-SHARP|C-sharp|c-sharp|CSHARP)" 7 | Go: 8 | - "(Go|GO|Golang|golang|GOLANG)" 9 | Java: 10 | - "(Java|java|JAVA)" 11 | JavaScript: 12 | - "(JavaScript|JAVASCRIPT|Javascript|javascript|JS|js|javaScript)" 13 | Python: 14 | - "(Python|PYTHON|python)" 15 | Q-Sharp: 16 | - "(Q-Sharp|qsharp|Q#|Q-SHARP|Q-sharp|q-sharp|QSHARP)" 17 | enhancement: 18 | - "(enhancement)" 19 | Dart: 20 | - "(Dart|dart|DART)" 21 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 10 | 11 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/smv1999/CompetitiveProgrammingQuestionBank/blob/master/CONTRIBUTING.md)? 12 | 13 | (Write your answer here.) 14 | 15 | ### Description 16 | 17 | (Write your answer here.) 18 | 19 | ### Checklist 20 | 21 | - [ ] I've read the contribution guidelines. 22 | - [ ] I've checked the issue list before deciding what to submit. 23 | - [ ] I've edited the `README.md` and link to my code. 24 | 25 | ## Related Issues or Pull Requests 26 | 27 | (Write your answer here.) 28 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # Number of days of inactivity before an issue becomes stale 2 | daysUntilStale: 7 3 | # Number of days of inactivity before a stale issue is closed 4 | daysUntilClose: 8 5 | # Issues with these labels will never be considered stale 6 | exemptLabels: 7 | - bug 8 | - do not merge yet 9 | - help wanted 10 | - high priority 11 | - pinned 12 | # Label to use when marking an issue as stale 13 | staleLabel: stale 14 | # Comment to post when marking an issue as stale. Set to `false` to disable 15 | markComment: > 16 | This issue has been automatically marked as stale because it has not had 17 | recent activity. It will be closed if no further activity occurs. Thank you 18 | for your contributions. 19 | # Comment to post when closing a stale issue. Set to `false` to disable 20 | closeComment: > 21 | Please reopen this issue once you commit the changes requested or 22 | make improvements on the code. Thank you for your contributions. 23 | -------------------------------------------------------------------------------- /.github/workflows/Auto_Issue_Closer.yml: -------------------------------------------------------------------------------- 1 | # Written By XZANATOL 2 | name: Auto Issue Closer on Merge 3 | 4 | on: 5 | pull_request: 6 | # Will trigger on closed PRs 7 | types: [closed] 8 | 9 | jobs: 10 | Close_Issue: 11 | 12 | runs-on: ubuntu-latest 13 | # Checks if PR is merged (subflag) 14 | if: ${{ github.event.pull_request.merged == true }} 15 | 16 | steps: 17 | - name: Closes issues related to a merged pull request. 18 | uses: ldez/gha-mjolnir@v1.0.3 19 | env: 20 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} -------------------------------------------------------------------------------- /.github/workflows/Issue-assign.yml: -------------------------------------------------------------------------------- 1 | name: Assign 2 | 3 | on: 4 | schedule: 5 | - cron: '*/2 * * * *' 6 | issue_comment: 7 | types: [created] 8 | 9 | jobs: 10 | slash_assign: 11 | # If the acton was triggered by a new comment that starts with `/assign` 12 | # or a on a schedule 13 | if: > 14 | (github.event_name == 'issue_comment' && startsWith(github.event.comment.body, '/assign')) || 15 | github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' 16 | runs-on: ubuntu-latest 17 | steps: 18 | - name: Assign the user or unassign stale assignments 19 | uses: JasonEtco/slash-assign-action@v0.0.3 20 | with: 21 | assigned_label: Assigned 22 | days_until_warning: 7 23 | days_until_unassign: 10 24 | stale_assignment_label: Open 25 | -------------------------------------------------------------------------------- /.github/workflows/Issue_watcher.yml: -------------------------------------------------------------------------------- 1 | name: Issue_watcher 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | 7 | jobs: 8 | first-job: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Checkout code 12 | uses: actions/checkout@main 13 | - name: Run Action 14 | uses: TesseractCoding/Issue_Watcher@main 15 | with: 16 | token: '${{ secrets.GITHUB_TOKEN }}' 17 | author: '${{github.actor}}' 18 | repo: smv1999/CompetitiveProgrammingQuestionBank #Change the Repo name 19 | maxIssue: 2 20 | -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: 4 | issues: 5 | types: [opened] 6 | pull_request: 7 | types: [opened] 8 | 9 | jobs: 10 | greeting: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: Saviour1001/Greeting-action@main 14 | with: 15 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 16 | issue_message: 'Hello @${{github.actor}},
17 | Thank you for opening an issue. :partying_face:
18 | To get assigned to this particular issue please use /assign
19 | Check this guide before contributing.' 20 | PR_message: 21 | '

:partying_face: Congratulations :tada:

:pray: 22 | Thank you @${{github.actor}} for taking out your time and contributing to our project. Our team will now review this and if everything looks good it will be merged.' -------------------------------------------------------------------------------- /.github/workflows/issues_labeler.yml: -------------------------------------------------------------------------------- 1 | name: Issues Labeler 2 | on: 3 | issues: 4 | types: [opened, edited] 5 | pull_request_target: 6 | types: [opened, reopened, edited, closed, synchronize] 7 | jobs: 8 | labeler: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: github/issue-labeler@v2.4 12 | with: 13 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 14 | configuration-path: .github/issues_labeler.yml 15 | enable-versioned-regex: 0 16 | -------------------------------------------------------------------------------- /.github/workflows/labeler.yml: -------------------------------------------------------------------------------- 1 | name: "PR_labeler" 2 | on: 3 | pull_request_target: 4 | types: [opened, reopened, edited, closed, synchronize] 5 | 6 | 7 | jobs: 8 | triage: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/labeler@main 12 | with: 13 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 14 | configuration-path: .github/labeler.yml 15 | -------------------------------------------------------------------------------- /.github/workflows/reviewer_auto_assigner.yml: -------------------------------------------------------------------------------- 1 | name: 'Auto Assign Reviewers to Pull Requests' 2 | on: 3 | pull_request: 4 | types: [opened, reopened] 5 | jobs: 6 | add-reviews: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: kentaro-m/auto-assign-action@v1.1.2 10 | with: 11 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 12 | configuration-path: .github/auto_assigner_config.yml 13 | -------------------------------------------------------------------------------- /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | name: Mark Stale Issues and Pull Requests 2 | on: 3 | schedule: 4 | - cron: "0 0 * * *" 5 | jobs: 6 | stale: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/stale@v1 10 | with: 11 | repo-token: ${{ secrets.GITHUB_TOKEN }} 12 | stale-issue-message: > 13 | Please reopen this issue once you add more information and updates here. 14 | stale-pr-message: > 15 | Please reopen this pull request once you commit the changes requested 16 | or make improvements on the code.Thank you for your contributions! 17 | stale-issue-label: "no-issue-activity" 18 | stale-pr-label: "no-pr-activity" 19 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### VisualStudioCode ### 2 | .vscode/* 3 | !.vscode/settings.json 4 | !.vscode/tasks.json 5 | !.vscode/launch.json 6 | !.vscode/extensions.json 7 | *.code-workspace 8 | 9 | # Local History for Visual Studio Code 10 | .history/ 11 | 12 | ### VisualStudioCode Patch ### 13 | # Ignore all local history of files 14 | .history 15 | .ionide -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "files.associations": { 3 | "array": "cpp", 4 | "*.tcc": "cpp", 5 | "deque": "cpp", 6 | "string": "cpp", 7 | "vector": "cpp", 8 | "fstream": "cpp", 9 | "istream": "cpp", 10 | "streambuf": "cpp", 11 | "iostream": "cpp" 12 | } 13 | } -------------------------------------------------------------------------------- /2D Arrays/StairCaseSearch.py: -------------------------------------------------------------------------------- 1 | def stairCaseSearch(matrix , key): 2 | n , m = len(matrix) , len(matrix[0]) 3 | i , j = 0 , m - 1 4 | 5 | isFound = False 6 | 7 | while(i <= n - 1 and j >= 0): 8 | if(matrix[i][j] == key): 9 | isFound = True 10 | print("Found at : " , i , j) 11 | break 12 | elif(matrix[i][j] > key): 13 | j -= 1 14 | else: 15 | i += 1 16 | 17 | if(not(isFound)): 18 | print("Key not found") 19 | 20 | n = int(input("Enter the no. of rows in the matrix : ")) 21 | m = int(input("ENter the no. of columns in the matrix : ")) 22 | 23 | matrix = [] 24 | print("Enter the elements of the Row and Column sorted matrix : ") 25 | for i in range(n): 26 | rows = [int(j) for j in input().split()] 27 | matrix.append(rows) 28 | 29 | key = int(input("Enter the key to search : ")) 30 | 31 | stairCaseSearch(matrix , key) 32 | -------------------------------------------------------------------------------- /2D Arrays/count_negative_in_sorted_matrix.cpp: -------------------------------------------------------------------------------- 1 | // Problem - Count the no. of negative elements in the row and column sorted (descending) matrix 2 | // 3 | // Sample Input - 1 4 | // 3 4 5 | // 4 3 2 -1 6 | // 3 2 -1 -2 7 | // 1 1 -3 -10 8 | // 9 | // Sample Output - 1 10 | // 5 11 | // 12 | // Time Complexity: O(m + n) 13 | // Auxiliary Space Complexity: O(1) 14 | 15 | #include 16 | #include 17 | 18 | // Function to count the no. of negative elements in the sorted matrix 19 | int count_negatives_in_matrix(vector > matrix) { 20 | 21 | int count = 0; 22 | int i = 0 , j = matrix[0].size() - 1; 23 | 24 | // Perform Staircase Search 25 | while(i <= matrix.size() - 1 && j >= 0) { 26 | if(matrix[i][j] < 0) { 27 | count += i; 28 | j--; 29 | } else { 30 | i++; 31 | } 32 | } 33 | return count; 34 | } 35 | 36 | int main() { 37 | 38 | int m , n; 39 | cin >> m >> n; 40 | 41 | vector > matrix(m , vector (n)); 42 | for(int i = 0; i < m; i++) { 43 | for(int j = 0; j < n; j++) 44 | cin >> matrix[i][j]; 45 | } 46 | 47 | int count_of_negatives = count_negatives_in_matrix(matrix); 48 | 49 | cout << "The no. of negative elements in the matrix is : " << count_of_negatives; 50 | return 0; 51 | } -------------------------------------------------------------------------------- /2D Arrays/count_negative_numbers_in_sorted_matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | -------------- 4 | Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of 5 | negative numbers in grid. 6 | 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int countNegatives(vector>& grid) { 12 | int count = 0; 13 | for(vector row : grid){ 14 | for(int i=0;i>& paths) { 14 | unordered_set st; 15 | for(vector p : paths){ 16 | st.insert(p[0]); 17 | } 18 | for(vector p : paths){ 19 | if(!st.count(p[1])) return p[1]; 20 | } 21 | 22 | return ""; 23 | } 24 | }; -------------------------------------------------------------------------------- /2D Arrays/equal_matrices.c: -------------------------------------------------------------------------------- 1 | /* C Program to Check Two Matrices are Equal or Not */ 2 | 3 | #include 4 | 5 | int main() 6 | { 7 | int i, j, rows, columns, a[10][10], b[10][10], isEqual; 8 | 9 | printf("\n Please Enter Number of rows and columns : "); 10 | scanf("%d %d", &i, &j); 11 | 12 | printf("\n Please Enter the First Matrix Elements\n"); 13 | for(rows = 0; rows < i; rows++) 14 | { 15 | for(columns = 0;columns < j;columns++) 16 | { 17 | scanf("%d", &a[rows][columns]); 18 | } 19 | } 20 | 21 | printf("\n Please Enter the Second Matrix Elements\n"); 22 | for(rows = 0; rows < i; rows++) 23 | { 24 | for(columns = 0;columns < j;columns++) 25 | { 26 | scanf("%d", &b[rows][columns]); 27 | } 28 | } 29 | isEqual = 1; 30 | 31 | for(rows = 0; rows < i; rows++) 32 | { 33 | for(columns = 0;columns < j;columns++) 34 | { 35 | if(a[rows][columns] != b[rows][columns]) 36 | { 37 | isEqual = 0; 38 | break; 39 | } 40 | } 41 | } 42 | if(isEqual == 1) 43 | { 44 | printf("\n Matrix a is Equal to Matrix b"); 45 | } 46 | else 47 | { 48 | printf("\n Matrix a is Not Equal to Matrix b"); 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /2D Arrays/lucky_numbers_in_a_matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | Given a m * n matrix of distinct numbers, return all lucky numbers in the matrix in any order. 4 | 5 | A lucky number is an element of the matrix such that it is the minimum element in its row and maximum in its column. 6 | */ 7 | 8 | class Solution { 9 | public: 10 | 11 | vector luckyNumbers (vector>& matrix) { 12 | vector res, maxEles, minEles; 13 | int r = matrix.size(); 14 | int c = matrix[0].size(); 15 | int max = INT_MIN; 16 | int min = INT_MAX; 17 | // find the max element in each column 18 | for(int j=0;j max) 22 | max = matrix[i][j]; 23 | } 24 | maxEles.push_back(max); 25 | } 26 | // find the min element in each row 27 | for(int i=0;i 18 | #include 19 | #include 20 | int main() 21 | { 22 | int n; 23 | scanf("%d", &n); 24 | char arr[n][n], str[1001]; 25 | for(int i=0;i 16 | using namespace std; 17 | int matrix[100][100],temp[100][100]; 18 | int n; 19 | void rotate(int angle) 20 | { 21 | int i,j; 22 | int total = angle/90; 23 | total = total % 4; 24 | while(total--) 25 | { 26 | for(i=0;i>n; 42 | for(i=0;i>matrix[i][j]; 47 | } 48 | } 49 | cin>>angle; 50 | rotate(angle); 51 | totalrot = totalrot + angle; 52 | // rotate(360 - (totalrot%360)); // to convert the rotated matrix to the original one 53 | for(i=0;i 6 | using namespace std; 7 | int main(int argc, char const *argv[]) 8 | { 9 | int n,i,row,col,end_row,end_col,count=0; 10 | cin>>n; 11 | row=col=end_row=end_col=0; 12 | int mat[n][n]; 13 | for(i=0;i end_col) 30 | { 31 | mat[row][col]=++count; 32 | col--; 33 | } 34 | end_row = i; 35 | while (row > end_row) 36 | { 37 | mat[row][col]=++count; 38 | row--; 39 | } 40 | } 41 | if(n%2==1) 42 | mat[n/2][n/2]= n*n; 43 | for(i=0;i 9 | using namespace std; 10 | 11 | class Solution { 12 | public: 13 | bool searchMatrix(vector>& matrix, int target) { 14 | for(vector v : matrix) 15 | { 16 | int first = 0; 17 | int last = matrix[0].size()-1; 18 | while(first<=last) 19 | { 20 | int mid = (first+last)/2; 21 | if(v[mid]==target) 22 | return true; 23 | else if(v[mid]target) 26 | last = mid - 1; 27 | } 28 | } 29 | return false; 30 | } 31 | }; -------------------------------------------------------------------------------- /2D Arrays/search_2d_matrix2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode : #240 3 | 4 | Write an efficient algorithm that searches for a target value in an m x n integer matrix. The matrix has the following properties: 5 | 6 | 1. Integers in each row are sorted in ascending from left to right. 7 | 2. Integers in each column are sorted in ascending from top to bottom. 8 | 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | bool searchMatrix(vector> &matrix, int target) 15 | { 16 | int n = matrix.size(); 17 | if (n == 0) 18 | return false; 19 | int m = matrix[0].size(); 20 | int j = m - 1, i = 0; 21 | while (i < n && j >= 0) 22 | { 23 | if (matrix[i][j] == target) 24 | return true; 25 | else if (matrix[i][j] > target) 26 | j--; 27 | else 28 | i++; 29 | } 30 | return false; 31 | } 32 | }; -------------------------------------------------------------------------------- /2D Arrays/sum_of_all_submatrices.cpp: -------------------------------------------------------------------------------- 1 | // Problem - Print the sum of all submatrices of the given matrix 2 | 3 | // Sample Input - 1 4 | // 3 3 5 | // 1 1 1 6 | // 1 1 1 7 | // 1 1 1 8 | 9 | // Sample Output - 1 10 | // 100 11 | 12 | // Sample Input - 2 13 | // 3 2 14 | // 1 10 8 15 | // -1 5 0 16 | 17 | // Sample Output - 2 18 | // 152 19 | 20 | 21 | 22 | #include 23 | #include 24 | 25 | using namespace std; 26 | 27 | int sum_all_submatrices(vector > grid) { 28 | 29 | int m = grid.size() , n = grid[0].size(); 30 | int sum = 0; 31 | for(int i = 0; i < m; i++) { 32 | for(int j = 0; j < n; j++) { 33 | for(int tl = i; tl < m; tl++) { 34 | for(int br = j; br < n; br++) { 35 | for(int r = i; r <= tl; r++) { 36 | for(int c = j; c <= br; c++) { 37 | sum += grid[r][c]; 38 | } 39 | } 40 | } 41 | } 42 | } 43 | } 44 | 45 | return sum; 46 | 47 | } 48 | 49 | int main() { 50 | 51 | int m , n; 52 | cout << "Enter the no. of rows and columns : " << endl; 53 | cin >> m >> n; 54 | 55 | vector > grid(m , vector (n)); 56 | cout << "Enter the elements of the matrix : " << endl; 57 | for (int i = 0; i < m; i++) { 58 | for (int j = 0; j < n; j++) { 59 | cin >> grid[i][j]; 60 | } 61 | } 62 | 63 | int sum = sum_all_submatrices(grid); 64 | 65 | cout << "The sum of all submatrices of the given matrix is : " << sum << endl; 66 | 67 | return 0; 68 | } -------------------------------------------------------------------------------- /2D Arrays/wave_print.cpp: -------------------------------------------------------------------------------- 1 | // Problem - Print the matrix in the wave form 2 | 3 | // Sample Input - 1 4 | // 3 4 5 | // 1 2 3 4 6 | // 5 6 7 8 7 | // 9 10 11 12 8 | // 13 14 15 16 9 | 10 | // Sample Output - 1 11 | // 1 5 9 13 14 10 6 2 3 7 11 15 16 12 8 4 12 | 13 | 14 | #include 15 | #include 16 | 17 | using namespace std; 18 | 19 | void wave_print(vector > matrix) { 20 | int n = matrix.size(); 21 | int m = matrix[0].size(); 22 | 23 | for(int i = 0; i < m; i++) { 24 | for(int j = 0; j < n; j++) { 25 | 26 | // When row is odd, print the column from bottom to top 27 | if(i & 1) 28 | cout << matrix[n - j - 1][i] << " "; 29 | 30 | // When row is even, print the column from top to bottom 31 | else 32 | cout << matrix[j][i] << " "; 33 | } 34 | } 35 | 36 | } 37 | 38 | int main() { 39 | 40 | int n , m; 41 | cout << "Enter the no. of rows and columns : " << endl; 42 | cin >> n >> m; 43 | 44 | vector > matrix(n , vector (m)); 45 | cout << "Enter the elements of the matrix : " << endl; 46 | for(int i = 0; i < n; i++) { 47 | for(int j = 0; j < m; j++) 48 | cin >> matrix[i][j]; 49 | } 50 | 51 | wave_print(matrix); 52 | 53 | return 0; 54 | } -------------------------------------------------------------------------------- /Arrays/Array Reversal.c: -------------------------------------------------------------------------------- 1 | //This is a Program to reverse an array 2 | // i.e. Input: 1,2,3,4,5 3 | // Output:5,4,3,2,1 4 | #include 5 | #include 6 | // added the useful header file 7 | int main() 8 | { 9 | // initialize the variable 10 | int num, *arr, i,swap=0; 11 | // taking array length from user 12 | scanf("%d", &num); 13 | //dynamically creating array to stop the waste of unnecessary memory 14 | arr = (int*) malloc(num * sizeof(int)); 15 | for(i = 0; i < num; i++) { 16 | // taking input 17 | scanf("%d", arr + i); 18 | } 19 | // This is the main logic to reverse an array 20 | // loop will run until i 14 | #include 15 | #include 16 | 17 | using namespace std; 18 | 19 | int main(int argc, char const *argv[]) 20 | { 21 | vector v1,v2,v3; 22 | 23 | int n1,n2,a; 24 | cin>>n1; 25 | 26 | for(int i=0;i>a; 28 | v1.push_back(a); 29 | } 30 | cin>>n2; 31 | for(int i=0;i>a; 34 | v2.push_back(a); 35 | } 36 | 37 | sort(v1.begin(),v1.end()); 38 | sort(v2.begin(),v2.end()); 39 | 40 | for(int i=0;i 14 | #include 15 | #include 16 | 17 | using namespace std; 18 | 19 | int main(int argc, char const *argv[]) 20 | { 21 | int n1,n2,a; 22 | 23 | cin>>n1; 24 | vector v1,v2,v3; 25 | for(int i=0;i>a; 27 | v1.push_back(a); 28 | } 29 | cin>>n2; 30 | for(int i=0;i>a; 33 | v2.push_back(a); 34 | } 35 | 36 | sort(v1.begin(),v1.end()); 37 | sort(v2.begin(),v2.end()); 38 | 39 | // Two Pointer Method 40 | int j=0,k=0; 41 | while(j 18 | using namespace std; 19 | 20 | 21 | // } Driver Code Ends 22 | 23 | 24 | // Function to find subarray with maximum sum 25 | // arr: input array 26 | // n: size of array 27 | int maxSubarraySum(int arr[], int n){ 28 | 29 | // Your code here 30 | int i,maxCur=arr[0]; 31 | int totalsum=arr[0]; 32 | for(i=1;itotalsum) 36 | { 37 | totalsum=maxCur; 38 | } 39 | } 40 | return totalsum; 41 | 42 | } 43 | 44 | // { Driver Code Starts. 45 | 46 | int main() 47 | { 48 | int t,n; 49 | 50 | cin>>t; //input testcases 51 | while(t--) //while testcases exist 52 | { 53 | 54 | cin>>n; //input size of array 55 | 56 | int a[n]; 57 | 58 | for(int i=0;i>a[i]; //inputting elements of array 60 | 61 | cout << maxSubarraySum(a, n) << endl; 62 | } 63 | } 64 | // } Driver Code Ends -------------------------------------------------------------------------------- /Arrays/LeftRightSumEqual.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of N elements. The aim is to print the elements whose left sum and 3 | right sum are equal. Left sum means the sum of the elements present to the left of 4 | the current element and right sum means the sum of the elements present to the right 5 | of the the current element. 6 | */ 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | int main() 13 | { 14 | int N; 15 | cin>>N; 16 | int arr[N+1], index, totalSum[N+1]; 17 | totalSum[0] = 0; 18 | for(index=1;index<=N;index++) 19 | { 20 | cin>>arr[index]; 21 | totalSum[index] = totalSum[index-1] + arr[index]; 22 | } 23 | for(index=1;index<=N;index++) 24 | { 25 | if((totalSum[index]-arr[index]) == (totalSum[N]-totalSum[index])) 26 | cout< sumZero(int n) { 12 | vector ans; 13 | int i = 1; 14 | if(n % 2 == 0){ 15 | while(ans.size() != n){ 16 | ans.push_back(i); 17 | ans.push_back(-i); 18 | i++; 19 | } 20 | } 21 | else{ 22 | while(ans.size() != n-1){ 23 | ans.push_back(i); 24 | ans.push_back(-i); 25 | i++; 26 | } 27 | ans.push_back(0); 28 | } 29 | return ans; 30 | } 31 | }; -------------------------------------------------------------------------------- /Arrays/QueryingArray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array containing N elements where 1<=N<=100000, and given Q queries, for each query increment the subarray 3 | [L,R] by 1. At the end, print the final elements. 4 | 5 | 6 | */ 7 | 8 | // THIS SOLUTION IS INCOMPLETE 9 | 10 | #include 11 | 12 | using namespace std; 13 | 14 | int main(int argc, char const *argv[]) 15 | { 16 | int N,Q,l,r,i=0; 17 | int arr[N]; 18 | int B[N]={0}; 19 | cin>>N; 20 | for(int i=0;i>arr[i]; 23 | } 24 | 25 | cin>>Q; 26 | while(Q--) 27 | { 28 | cin>>l>>r; 29 | B[l]+=1; 30 | B[r+1]-=1; 31 | } 32 | for(i=0;i 2 | using namespace std; 3 | vector duplicates(int arr[], int n); 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while (t-- > 0) 9 | { 10 | int n; 11 | cin >> n; 12 | int a[n]; 13 | for (int i = 0; i < n; i++) 14 | cin >> a[i]; 15 | vector ans = duplicates(a, n); 16 | for (int i : ans) 17 | cout << i << ' '; 18 | cout << endl; 19 | } 20 | return 0; 21 | } 22 | 23 | vector duplicates(int a[], int n) 24 | { 25 | map mp; 26 | vector res; 27 | int index, flag = 0; 28 | for (index = 0; index < n; index++) 29 | mp[a[index]]++; 30 | for (auto i : mp) 31 | { 32 | if (i.second > 1) 33 | { 34 | res.push_back(i.first); 35 | flag = 1; 36 | } 37 | } 38 | if (!flag) 39 | { 40 | res.push_back(-1); 41 | } 42 | return res; 43 | } 44 | -------------------------------------------------------------------------------- /Arrays/duplicates_in_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Example - 1 2 3 4 6 3 3 5 5 3 | 4 | Duplicates are -> 3 5 5 | ''' 6 | 7 | # Taking array input 8 | l=input().split() 9 | 10 | # Changing string array to integer array 11 | for i in range(0,len(l)): 12 | l[i]=int(l[i]) 13 | 14 | newl=[] 15 | dupli=[] 16 | 17 | # Logic for catching duplicate elements 18 | for i in l: 19 | if i not in newl: 20 | newl.append(i) 21 | else: 22 | if i not in dupli: 23 | dupli.append(i) 24 | 25 | print(dupli) -------------------------------------------------------------------------------- /Arrays/index_of_an_extra_element.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int findExtra(int a[], int b[], int n); 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while (t--) 9 | { 10 | int n; 11 | cin >> n; 12 | int a[n], b[n - 1]; 13 | for (int i = 0; i < n; i++) 14 | { 15 | cin >> a[i]; 16 | } 17 | for (int i = 0; i < n - 1; i++) 18 | { 19 | cin >> b[i]; 20 | } 21 | cout << findExtra(a, b, n) << endl; 22 | } 23 | } 24 | 25 | int findExtra(int a[], int b[], int n) 26 | { 27 | for (int index = 0; index < n; index++) 28 | { 29 | if (a[index] != b[index]) 30 | return index; 31 | } 32 | } -------------------------------------------------------------------------------- /Arrays/kadane's_algorithm.c: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array arr of N integers. Find the contiguous sub-array with maximum sum. 3 | 4 | For Example: 5 | 6 | Input: 7 | N = 5 8 | arr[] = {1,2,3,-2,5} 9 | Output: 9 10 | */ 11 | #include 12 | #include 13 | 14 | int main() 15 | { 16 | 17 | int n; 18 | scanf("%d", &n); 19 | int arr[n], index=0, max_so_far=INT_MIN, temp_max=0; 20 | for(index=0;indexmax_so_far) 26 | max_so_far = temp_max; 27 | if(temp_max<0) 28 | temp_max = 0; 29 | 30 | } 31 | printf("%d", max_so_far); 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /Arrays/largest_sum_subarray.java: -------------------------------------------------------------------------------- 1 | /* 2 | Subsequence is that array in which eements are missing in between two elements but continuous subarray 3 | in which any element is not missing. 4 | Problem: We have to find continuous subarray whose sum is largest. 5 | Example: [-3,2,4,-1,2,3,-2] 6 | Max subarray=[2,4,-1,2,3] 7 | sum=10 8 | */ 9 | 10 | 11 | // Time complexity --> O(n^2) 12 | 13 | import java.util.*; 14 | public class HelloWorld{ 15 | public static void main(String []args){ 16 | int n; 17 | Scanner scan=new Scanner(System.in); 18 | n=scan.nextInt(); 19 | int []ar=new int[n]; 20 | int []sum=new int[n]; 21 | int i,j,count=0,k,max; 22 | max=Integer.MIN_VALUE; 23 | for(i=0;i 2 | using namespace std; 3 | int findExtra(int a[], int b[], int n); 4 | int main() 5 | { 6 | int t; 7 | cin >> t; 8 | while (t--) 9 | { 10 | int n; 11 | cin >> n; 12 | int a[n], b[n - 1]; 13 | for (int i = 0; i < n; i++) 14 | { 15 | cin >> a[i]; 16 | } 17 | for (int i = 0; i < n - 1; i++) 18 | { 19 | cin >> b[i]; 20 | } 21 | cout << findExtra(a, b, n) << endl; 22 | } 23 | } 24 | 25 | int findExtra(int a[], int b[], int n) 26 | { 27 | // add code here. 28 | for (int index = 0; index < n; index++) 29 | { 30 | if (a[index] != b[index]) 31 | return index; 32 | } 33 | } -------------------------------------------------------------------------------- /Arrays/max_prod_of_two_elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | -------------- 4 | 5 | Given the array of integers nums, you will choose two different indices i and j of that array. Return the maximum value 6 | of (nums[i]-1)*(nums[j]-1). 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int maxProduct(vector& nums) { 12 | int max1, max2, ans = 0; 13 | max1 = max2 = INT_MIN; 14 | int n = nums.size(); 15 | for(int i=0;i max1){ 17 | max2 = max1; 18 | max1 = nums[i]; 19 | } 20 | else if(nums[i] > max2){ 21 | max2 = nums[i]; 22 | } 23 | } 24 | ans = (max1-1)* (max2-1); 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Arrays/missing_number_in_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size N-1 such that it can only contain distinct integers in the range of 1 to N. Find the missing element. 3 | */ 4 | 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | //code 12 | int t, n; 13 | cin >> t; 14 | while (t--) 15 | { 16 | cin >> n; 17 | int arr[n], index, sum = 0; 18 | for (index = 0; index < n - 1; index++) 19 | { 20 | cin >> arr[index]; 21 | sum += arr[index]; 22 | } 23 | cout << (n * (n + 1) / 2) - sum << endl; 24 | } 25 | return 0; 26 | } -------------------------------------------------------------------------------- /Arrays/peek_element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A peak element in an array is the one that is not smaller than its neighbours. 3 | Given an array of size N, find the index of any one of its peak elements. 4 | */ 5 | #include 6 | using namespace std; 7 | 8 | int peakElement(int arr[], int n) 9 | { 10 | 11 | int index = 0, resIndex; 12 | if (arr[index] > arr[index + 1]) 13 | { 14 | resIndex = index; 15 | } 16 | for (index = 1; index < n - 1; index++) 17 | { 18 | if (arr[index] > arr[index - 1] && arr[index] > arr[index + 1]) 19 | { 20 | resIndex = index; 21 | } 22 | } 23 | if (arr[n - 1] > arr[n - 2]) 24 | { 25 | resIndex = n - 1; 26 | } 27 | return resIndex; 28 | } 29 | 30 | int main() 31 | { 32 | int t; 33 | cin >> t; 34 | while (t--) 35 | { 36 | int n; 37 | cin >> n; 38 | int a[n]; 39 | for (int i = 0; i < n; i++) 40 | { 41 | cin >> a[i]; 42 | } 43 | bool f = 0; 44 | int A = peakElement(a, n); 45 | 46 | if (n == 1) 47 | f = 1; 48 | else if (A == 0 and a[0] >= a[1]) 49 | f = 1; 50 | else if (A == n - 1 and a[n - 1] >= a[n - 2]) 51 | f = 1; 52 | else if (a[A] >= a[A + 1] and a[A] >= a[A - 1]) 53 | f = 1; 54 | else 55 | f = 0; 56 | 57 | cout << f << endl; 58 | } 59 | 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Arrays/remove_duplicates_from_sorted_array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int remove_duplicate(int[], int); 5 | 6 | int main() 7 | { 8 | int T; 9 | cin >> T; 10 | while (T--) 11 | { 12 | int N; 13 | cin >> N; 14 | int a[N]; 15 | for (int i = 0; i < N; i++) 16 | { 17 | cin >> a[i]; 18 | } 19 | 20 | int n = remove_duplicate(a, sizeof(a) / sizeof(a[0])); 21 | 22 | for (int i = 0; i < n; i++) 23 | cout << a[i] << " "; 24 | cout << endl; 25 | } 26 | } 27 | 28 | int remove_duplicate(int A[], int N) 29 | { 30 | int temp[N], j = 0; 31 | for (int index = 0; index < N - 1; index++) 32 | { 33 | if (A[index] != A[index + 1]) 34 | { 35 | temp[j++] = A[index]; 36 | } 37 | } 38 | temp[j++] = A[N - 1]; 39 | for (int index = 0; index < j; index++) 40 | { 41 | A[index] = temp[index]; 42 | } 43 | return j; 44 | } -------------------------------------------------------------------------------- /Arrays/remove_duplicates_from_sorted_array.py: -------------------------------------------------------------------------------- 1 | # Taking array input 2 | l=input().split() 3 | 4 | # Changing string array to integer array 5 | for i in range(0,len(l)): 6 | l[i]=int(l[i]) 7 | 8 | #sorting 9 | l.sort() 10 | 11 | #Removing duplicate elements 12 | newl = [] 13 | if(len(l)>0): 14 | newl.append(l[0]) 15 | for i in range(1,len(l)): 16 | if l[i-1]!=l[i]: 17 | newl.append(l[i]) 18 | 19 | print(newl) 20 | 21 | 22 | -------------------------------------------------------------------------------- /Arrays/replace_elements_with_greatest_element_on_right.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | -------------- 4 | 5 | Given an array arr, replace every element in that array with the greatest element among the elements to its right, and replace 6 | the last element with -1. 7 | 8 | After doing so, return the array. 9 | */ 10 | 11 | class Solution 12 | { 13 | public: 14 | vector replaceElements(vector &arr) 15 | { 16 | int n = arr.size(); 17 | int max = arr[n - 1]; 18 | vector res(n); 19 | res[n - 1] = -1; 20 | for (int i = n - 2; i >= 0; i--) 21 | { 22 | res[i] = max; 23 | if (arr[i] > max) 24 | max = arr[i]; 25 | } 26 | return res; 27 | } 28 | }; -------------------------------------------------------------------------------- /Arrays/sort_an_array_of_0s_1s_and_2s.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order. 3 | */ 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | //code 11 | int t; 12 | cin >> t; 13 | while (t--) 14 | { 15 | int n; 16 | cin >> n; 17 | int arr[n], index; 18 | for (index = 0; index < n; index++) 19 | cin >> arr[index]; 20 | int low = 0, mid = 0, high = n - 1, temp; 21 | while (mid <= high) 22 | { 23 | if (arr[mid] == 0) 24 | { 25 | temp = arr[mid]; 26 | arr[mid] = arr[low]; 27 | arr[low] = temp; 28 | low++; 29 | mid++; 30 | } 31 | else if (arr[mid] == 2) 32 | { 33 | temp = arr[mid]; 34 | arr[mid] = arr[high]; 35 | arr[high] = temp; 36 | high--; 37 | } 38 | else 39 | mid++; 40 | } 41 | for (index = 0; index < n; index++) 42 | cout << arr[index] << " "; 43 | cout << "\n"; 44 | } 45 | return 0; 46 | } -------------------------------------------------------------------------------- /Arrays/subset_of_array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two arrays: arr1[0..m-1] of size m and arr2[0..n-1] of size n. Task is to check whether arr2[] is a subset 3 | of arr1[] or not. Both the arrays can be both unsorted or sorted. It may be assumed that elements in both array are distinct. 4 | */ 5 | #include 6 | #include 7 | using namespace std; 8 | 9 | bool isSubset(int arr1[], int arr2[], int m, int n) 10 | { 11 | unordered_set s; 12 | for (int index = 0; index < m; index++) 13 | { 14 | s.insert(arr1[index]); 15 | } 16 | for (int index = 0; index < n; index++) 17 | { 18 | if (s.find(arr2[index]) == s.end()) 19 | return false; 20 | } 21 | return true; 22 | } 23 | 24 | int main() 25 | { 26 | //code 27 | int t; 28 | cin >> t; 29 | while (t--) 30 | { 31 | int m, n, flag = 0; 32 | cin >> m >> n; 33 | int arr1[m], arr2[n]; 34 | for (int index = 0; index < m; index++) 35 | { 36 | cin >> arr1[index]; 37 | } 38 | for (int index = 0; index < n; index++) 39 | { 40 | cin >> arr2[index]; 41 | } 42 | if (isSubset(arr1, arr2, m, n)) 43 | cout << "Yes\n"; 44 | else 45 | cout << "No\n"; 46 | } 47 | return 0; 48 | } -------------------------------------------------------------------------------- /Arrays/subset_of_array.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Given two arrays: arr1[0..m-1] of size m and arr2[0..n-1] of size n. Task is to check whether arr2[] is a subset 3 | of arr1[] or not. Both the arrays can be both unsorted or sorted. It may be assumed that elements in both array are distinct. 4 | ''' 5 | 6 | # Taking array input 7 | l1=input().split() 8 | l2=input().split() 9 | 10 | #Creating array of common elements 11 | r=[] 12 | for i in l1: 13 | if i in l2: 14 | r.append(i) 15 | 16 | if r==l2: 17 | print("Array 2 is the subset of Array 1") 18 | else: 19 | print("Array 2 is NOT the subset of Array 1") -------------------------------------------------------------------------------- /Arrays/sum_of_elements_to_right.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, modify the array such that each element is replaced by the sum of the elements to the right of it 3 | (in position). 4 | 5 | For eg: 6 | 7 | Input: 8 | 4 5 2 3 1 9 | Output: 10 | 11 6 4 1 0 11 | 12 | 13 | */ 14 | 15 | #include 16 | 17 | using namespace std; 18 | 19 | int main(int argc, char const *argv[]) 20 | { 21 | int arr[] = {4, 5, 2, 3, 1}; 22 | 23 | int size,sum=0; 24 | 25 | size = sizeof(arr)/sizeof(arr[0]); 26 | for(int ind=0;ind 14 | 15 | using namespace std; 16 | 17 | int main(int argc, char const *argv[]) 18 | { 19 | int arr[] = {1,4,5,3,2}; 20 | int size,sum=0; 21 | 22 | size = sizeof(arr)/sizeof(arr[0]); 23 | for(int ind = 0;ind < size;ind++) 24 | { 25 | sum+=arr[ind]; 26 | } 27 | 28 | for(int ind=0;ind 15 | #define fl(i,a,b) for(i=a;i>n>>k; 25 | vector> a; 26 | pair p; 27 | 28 | for(ll i=0; i>p.first; 31 | p.second=i+1; 32 | a.push_back(p); 33 | } 34 | sort(begin(a), end(a)); 35 | 36 | for (ll i = 0; i < n; i++) 37 | { 38 | l=0; 39 | r=n-1; 40 | target= k-a[i].first; 41 | while(l 18 | using namespace std; 19 | 20 | // Function to find number of bits to be flip 21 | // to convert A to B 22 | int countBitsFlip(int a, int b){ 23 | 24 | // Your logic here 25 | int ans=a^b; 26 | int c=0; 27 | while(ans>0) 28 | { 29 | ans &=(ans-1); 30 | c++; 31 | } 32 | return c; 33 | 34 | } 35 | 36 | // { Driver Code Starts. 37 | 38 | // Driver Code 39 | int main() 40 | { 41 | int t; 42 | cin>>t;// input the testcases 43 | while(t--) //while testcases exist 44 | { 45 | int a,b; 46 | cin>>a>>b; //input a and b 47 | 48 | cout< 18 | using namespace std; 19 | 20 | // Function to count set bits in the given number x 21 | // n: input to count the number of set bits 22 | int largestpowerof2inrange(int n) 23 | { 24 | int x=0; 25 | while((1<>t;// input testcases 48 | while(t--) //while testcases exist 49 | { 50 | int n; 51 | cin>>n; //input n 52 | 53 | cout << countSetBits(n) << endl;// print the answer 54 | } 55 | return 0; 56 | } 57 | // } Driver Code Ends -------------------------------------------------------------------------------- /Bit Manipulation/K-th_bit_is_set_or_not.cpp: -------------------------------------------------------------------------------- 1 | // Given a number N and a bit number K, check if the Kth bit of N is set or not.Position of set bit '1' should be indexed starting with 0 from the LSB side in the binary representation of the number. 2 | 3 | // Example 4 | // Input: N = 4, K = 0 5 | // Output: No 6 | 7 | // Time Complexity: O(LogN) 8 | // Auxiliary Space: O(1) 9 | 10 | #include 11 | using namespace std; 12 | 13 | bool checkKthBit(int n, int k) 14 | { 15 | if((1<>t;//taking testcases 24 | while(t--) 25 | { 26 | long long n; 27 | cin>>n;//input n 28 | int k; 29 | cin>>k;//bit number k 30 | 31 | if(checkKthBit(n, k)) 32 | cout << "Yes" << endl; 33 | else 34 | cout << "No" << endl; 35 | } 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /Bit Manipulation/Number_of_1_Bits.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* Given a positive integer N, print count of set bits in it. 3 | 4 | Example 1: 5 | 6 | Input: 7 | N = 6 8 | Output: 9 | 2 10 | Explanation: 11 | Binary representation is '110' 12 | So the count of the set bit is 2.*/ 13 | #include 14 | using namespace std; 15 | 16 | 17 | 18 | class Solution 19 | { 20 | public: 21 | int setBits(int N) 22 | { 23 | int count =0; 24 | while (N) { 25 | N &=(N-1); 26 | count ++; 27 | 28 | } 29 | return count; 30 | } 31 | }; 32 | 33 | // { Driver Code Starts. 34 | int main() 35 | { 36 | int t; 37 | cin >> t; 38 | while (t--) 39 | { 40 | int N; 41 | cin >> N; 42 | 43 | Solution ob; 44 | int cnt = ob.setBits(N); 45 | cout << cnt << endl; 46 | } 47 | return 0; 48 | } 49 | // } Driver Code Ends -------------------------------------------------------------------------------- /Bit Manipulation/Power_of_2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a non-negative integer N. The task is to check if N is a power of 2. More formally, check if N can be expressed as 2x for some x. 3 | 4 | 5 | Example 1: 6 | 7 | Input: N = 1 8 | Output: true 9 | Explanation: 10 | 1 is equal to 2 raised to 0 (20 = 1).*/ 11 | //Initial Template for C++ 12 | 13 | #include 14 | using namespace std; 15 | 16 | // Function to check power of two 17 | bool isPowerofTwo(long long n){ 18 | 19 | // Your code here 20 | if(n==0) 21 | return 0; 22 | 23 | else if(n>0) 24 | { 25 | if((n & n-1)==0) 26 | return 1; 27 | } 28 | return 0; 29 | } 30 | 31 | // Driver code 32 | int main() 33 | { 34 | 35 | int t; 36 | cin>>t;//testcases 37 | 38 | for(int i=0;i>n; 42 | 43 | if(isPowerofTwo(n))//Now, if log2 produces an integer not decimal then we are sure raising 2 to this value 44 | cout<<"YES"< 2 | #include 3 | 4 | int main() 5 | { 6 | 7 | int N; 8 | scanf("%d", &N); 9 | int input[N], ind, rem; 10 | for(ind=0;ind21) 20 | { 21 | rem = input[ind] % 22; 22 | rem += 2; 23 | } 24 | else rem = input[ind]; 25 | res = res + two_digits[rem]; 26 | } 27 | 28 | printf("%llu", res%100); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /CodeVita Problems/constellation stars.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | char space[3][100] = 6 | { 7 | "#.*.#******#****.****#.*.", 8 | "#***#******#*.**.*.*.#***", 9 | "#*.*#******#*********#*.*" 10 | }; 11 | 12 | int space_ind; 13 | 14 | for(space_ind = 0; space[0][space_ind];space_ind++) 15 | { 16 | if(space[0][space_ind] == '#') 17 | printf("#"); 18 | else if (space[2][space_ind] == '.' ) 19 | continue; 20 | else if(space[0][space_ind] == '.') 21 | printf("A"); 22 | else if(space[1][space_ind] == '.') 23 | printf("I"); 24 | else if(space[0][space_ind+1] == '.') 25 | printf("U"); 26 | else if(space[1][space_ind+1] == '.') 27 | printf("O"); 28 | else printf("E"); 29 | if(space[0][space_ind] == '#' || space[2][space_ind] == '.' ) 30 | continue; 31 | else 32 | space_ind+=2; 33 | 34 | } 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /CodeVita Problems/count pairs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int binarySearch(int arr[], int n, int k) 5 | { 6 | int start = 0; 7 | int end = n-1; 8 | 9 | while(start<=end) 10 | { 11 | int mid = (start+end)/2; 12 | 13 | if(arr[mid]==k) 14 | return mid; 15 | else if(arr[mid]k) 18 | end = mid - 1; 19 | } 20 | return 0; 21 | } 22 | //6 3 23 | //5 5 7 9 15 2 24 | int main() 25 | { 26 | int n, k, happyCounter=0; 27 | scanf("%d %d", &n,&k); 28 | 29 | int arr[n]; 30 | 31 | for(int arr_ind=0;arr_ind 17 | 18 | using namespace std; 19 | 20 | int main(int argc, char const *argv[]) 21 | { 22 | int n,k, count=0; 23 | cin>>n>>k; 24 | for(int num=1;num<=n/2;num++) 25 | { 26 | if(n%num==0) 27 | { 28 | count++; 29 | } 30 | if(count==k+1) 31 | { 32 | cout< 18 | using namespace std; 19 | 20 | /* Function to reverse arr[] from start to end*/ 21 | void rvereseArray(int arr[], int start, int end) 22 | { 23 | while (start < end) 24 | { 25 | int temp = arr[start]; 26 | arr[start] = arr[end]; 27 | arr[end] = temp; 28 | start++; 29 | end--; 30 | } 31 | } 32 | 33 | /* Utility function to print an array */ 34 | void printArray(int arr[], int size) 35 | { 36 | for (int i = 0; i < size; i++) 37 | cout << arr[i] << " "; 38 | 39 | cout << endl; 40 | } 41 | 42 | /* Driver function to test above functions */ 43 | int main() 44 | { 45 | int arr[] = {1, 2, 3, 4, 5, 6}; 46 | 47 | int n = sizeof(arr) / sizeof(arr[0]); 48 | 49 | // To print original array 50 | printArray(arr, n); 51 | 52 | // Function calling 53 | rvereseArray(arr, 0, n-1); 54 | 55 | cout << "Reversed array is" << endl; 56 | 57 | // To print the Reversed array 58 | printArray(arr, n); 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /DSA 450 GFG/BuyandSell.py: -------------------------------------------------------------------------------- 1 | # Link to the problem : https://leetcode.com/problems/best-time-to-buy-and-sell-stock/ 2 | 3 | class Solution: 4 | def maxProfit(self, prices): 5 | min_so_far = prices[0] 6 | max_profit = 0 7 | n = len(prices) 8 | for i in prices : 9 | min_so_far = min(min_so_far , i) 10 | profit = i - min_so_far 11 | max_profit = max(max_profit , profit) 12 | return max_profit 13 | -------------------------------------------------------------------------------- /DSA 450 GFG/CountAndSay.py: -------------------------------------------------------------------------------- 1 | # Problem : https://leetcode.com/problems/count-and-say/ 2 | 3 | # Input: n = 4 4 | # Output: "1211" 5 | # Explanation: 6 | # countAndSay(1) = "1" 7 | # countAndSay(2) = say "1" = one 1 = "11" 8 | # countAndSay(3) = say "11" = two 1's = "21" 9 | # countAndSay(4) = say "21" = one 2 + one 1 = "12" + "11" = "1211" 10 | 11 | # Initialize counter = 1 to store the count of every element 12 | # Initialize o/p string as ret = "" 13 | # If the previous element in the string is equal to the current element in the string , increament the counter 14 | # else Concatenate the count and the previous element of the string in ret 15 | 16 | # Return ret 17 | 18 | class Solution: 19 | def countAndSay(self, n): 20 | if (n == 1): 21 | return ("1") 22 | 23 | s = self.countAndSay(n-1) 24 | 25 | ret = "" 26 | cnt = 1 27 | i = 1 28 | while i < len(s) + 1: 29 | if i < len(s) and s[i] == s[i-1]: 30 | cnt += 1 31 | else: 32 | ret += str(cnt) + str(s[i-1]) 33 | cnt = 1 34 | i += 1 35 | 36 | return (ret) -------------------------------------------------------------------------------- /DSA 450 GFG/DeleteNodeinBST.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/delete-node-in-a-bst/submissions/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | 11 | def findMinimum(self , root): 12 | current = root 13 | while(current.left): 14 | current = current.left 15 | return current 16 | 17 | def deleteNode(self, root: TreeNode, key: int) -> TreeNode: 18 | 19 | if not root: 20 | return root 21 | 22 | 23 | elif(key < root.val): 24 | root.left = self.deleteNode(root.left , key) 25 | 26 | elif(key > root.val): 27 | root.right = self.deleteNode(root.right , key) 28 | 29 | else: 30 | 31 | #Leaf 32 | if not root.left and not root.right: 33 | root = None 34 | 35 | #1 child 36 | elif not root.left: 37 | root = root.right 38 | 39 | elif not root.right : 40 | root = root.left 41 | 42 | #2 child 43 | else: 44 | temp = self.findMinimum(root.right) 45 | root.val = temp.val 46 | root.right = self.deleteNode(root.right , temp.val) 47 | 48 | return root 49 | 50 | -------------------------------------------------------------------------------- /DSA 450 GFG/InorderTraversal-Iterative.py: -------------------------------------------------------------------------------- 1 | # Link to the problem : https://leetcode.com/problems/binary-tree-inorder-traversal/submissions/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | 11 | from collections import deque 12 | class Solution: 13 | def inorderTraversal(self, root): 14 | 15 | op = [] 16 | stack = deque() 17 | 18 | curr = root 19 | 20 | while stack or curr: 21 | 22 | if curr: 23 | stack.append(curr) 24 | curr = curr.left 25 | else: 26 | curr = stack.pop() 27 | op.append(curr.val) 28 | curr = curr.right 29 | 30 | return op -------------------------------------------------------------------------------- /DSA 450 GFG/PreOrder_iterative.py: -------------------------------------------------------------------------------- 1 | # Link for the problem : https://leetcode.com/problems/binary-tree-preorder-traversal/ 2 | 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | 11 | from collections import deque 12 | class Solution: 13 | def preorderTraversal(self, root): 14 | stack = deque() 15 | op = [] 16 | 17 | if(root == None): 18 | return 19 | 20 | stack.append(root) 21 | 22 | while stack: 23 | 24 | curr = stack.pop() 25 | op.append(curr.val) 26 | 27 | 28 | if(curr.right): 29 | stack.append(curr.right) 30 | 31 | if(curr.left): 32 | stack.append(curr.left) 33 | 34 | return op 35 | -------------------------------------------------------------------------------- /DSA 450 GFG/PrintAnagrams.py: -------------------------------------------------------------------------------- 1 | 2 | # Problem : https://practice.geeksforgeeks.org/problems/print-anagrams-together/1 3 | 4 | 5 | # Input: 6 | # N = 5 7 | # words[] = {act,god,cat,dog,tac} 8 | # Output: 9 | # god dog 10 | # act cat tac 11 | # Explanation: 12 | # There are 2 groups of 13 | # anagrams "god", "dog" make group 1. 14 | # "act", "cat", "tac" make group 2. 15 | 16 | from collections import defaultdict 17 | 18 | def Anagrams(words,n): 19 | ''' 20 | words: list of word 21 | n: no of words 22 | return : list of group of anagram {list will be sorted in driver code (not word in grp)} 23 | ''' 24 | 25 | #code here 26 | anagrams = defaultdict(list) 27 | 28 | for word in words: 29 | anagrams["".join(sorted(word))].append(word) 30 | 31 | return anagrams.values() 32 | 33 | 34 | # Driver Code 35 | 36 | if __name__ =='__main__': 37 | t= int(input()) 38 | for tcs in range(t): 39 | n= int(input()) 40 | words=input().split() 41 | 42 | ans=Anagrams(words,n) 43 | 44 | for grp in sorted(ans): 45 | for word in grp: 46 | print(word,end=' ') 47 | print() 48 | 49 | 50 | 51 | # Used default dict from collections module . It does not raise key value error -------------------------------------------------------------------------------- /DSA 450 GFG/TrapRainWater.py: -------------------------------------------------------------------------------- 1 | # Problem : https://practice.geeksforgeeks.org/problems/trapping-rain-water-1587115621/1 2 | 3 | class Solution: 4 | def trappingWater(self, arr,n): 5 | #Code here 6 | left = [0]*n 7 | right = [0]*n 8 | 9 | left[0] = arr[0] 10 | right[n-1] = arr[n-1] 11 | trap_sum = 0 12 | 13 | for i in range (1 , n): 14 | left[i] = max(left[i-1] , arr[i]) 15 | for i in range(n-2 , -1 , -1): 16 | right[i] = max(arr[i] , right[i+1]) 17 | for i in range (0 , n): 18 | trap_sum += min(left[i] , right[i]) - arr[i] 19 | 20 | return trap_sum 21 | #{ 22 | # Driver Code Starts 23 | #Initial Template for Python 3 24 | 25 | import math 26 | 27 | 28 | 29 | def main(): 30 | T=int(input()) 31 | while(T>0): 32 | 33 | n=int(input()) 34 | 35 | arr=[int(x) for x in input().strip().split()] 36 | obj = Solution() 37 | print(obj.trappingWater(arr,n)) 38 | 39 | 40 | T-=1 41 | 42 | 43 | if __name__ == "__main__": 44 | main() 45 | 46 | 47 | 48 | # } Driver Code Ends -------------------------------------------------------------------------------- /DSA 450 GFG/chocolate_distribution.py: -------------------------------------------------------------------------------- 1 | # Problem : https://practice.geeksforgeeks.org/problems/chocolate-distribution-problem3825/1# 2 | 3 | #Given an array A[ ] of positive integers of size N, where each value represents the number of chocolates in a packet. Each packet can have a variable number of chocolates. There are M students, the task is to distribute chocolate packets among M students such that : 4 | #1. Each student gets exactly one packet. 5 | #2. The difference between maximum number of chocolates given to a student and minimum number of chocolates given to a student is minimum. 6 | 7 | 8 | class Solution: 9 | 10 | def findMinDiff(self, A,N,M): 11 | 12 | # code here 13 | if(N == 0 or M == 0): 14 | return 0 15 | elif (N < M): 16 | return -1 17 | else: 18 | A.sort() 19 | min_diff = A[N-1] - A[0] 20 | for i in range(0 , N - M + 1): 21 | min_diff = min(min_diff , A[i+M-1] - A[i]) 22 | return min_diff 23 | 24 | 25 | #{ 26 | # Driver Code Starts 27 | #Initial Template for Python 3 28 | 29 | if __name__ == '__main__': 30 | 31 | t = int(input()) 32 | 33 | for _ in range(t): 34 | N = int(input()) 35 | A = [int(x) for x in input().split()] 36 | M = int(input()) 37 | 38 | 39 | solObj = Solution() 40 | 41 | print(solObj.findMinDiff(A,N,M)) 42 | # } Driver Code Ends -------------------------------------------------------------------------------- /DSA 450 GFG/max_and_min_of_array.py: -------------------------------------------------------------------------------- 1 | # Maximum and minimum of an array using minimum number of comparisons - Python 2 | 3 | def getMinMax(arr): 4 | 5 | n = len(arr) 6 | 7 | # If array has even number of elements then initialize the first two elements as minimum and maximum 8 | if(n % 2 == 0): 9 | maximum = max(arr[0], arr[1]) 10 | minimum = min(arr[0], arr[1]) 11 | 12 | # set the starting index for loop 13 | i = 2 14 | 15 | # If array has odd number of elements then initialize the first element as minimum and maximum 16 | else: 17 | maximum = minimum = arr[0] 18 | 19 | # set the starting index for loop 20 | i = 1 21 | 22 | # In the while loop, pick elements in pair and compare the pair with max and min so far 23 | while(i < n - 1): 24 | if arr[i] < arr[i + 1]: 25 | maximum = max(maximum, arr[i + 1]) 26 | minimum = min(minimum, arr[i]) 27 | else: 28 | maximum = max(maximum, arr[i]) 29 | minimum = min(minimum, arr[i + 1]) 30 | 31 | # Increment the index by 2 as two elements are processed in loop 32 | i += 2 33 | 34 | return (maximum, minimum) 35 | 36 | # Driver Code 37 | if __name__ =='__main__': 38 | 39 | arr = [9, 1, 45, 2, 330, 3] 40 | maximum, minimum = getMinMax(arr) 41 | print("Minimum element is", minimum) 42 | print("Maximum element is", maximum) 43 | 44 | 45 | -------------------------------------------------------------------------------- /DSA 450 GFG/max_sum_bottom_up.py: -------------------------------------------------------------------------------- 1 | #https://practice.geeksforgeeks.org/problems/maximum-sum-problem2211/1/ 2 | 3 | 4 | #Approach 2 - Bottom Up approach 5 | 6 | 7 | def maxSum(self, n): 8 | # code here 9 | dp = [0]*(n+1) 10 | dp[0] = 0 11 | if(n >= 1): 12 | dp[1] = 1 13 | for i in range(2 , n+1): 14 | dp[i] = max((dp[int(i/2)] + dp[int(i/3)] + dp[int(i/4)]) , i) 15 | 16 | return dp[n] 17 | 18 | 19 | #{ 20 | # Driver Code Starts 21 | #Initial Template for Python 3 22 | 23 | if __name__ == '__main__': 24 | t = int(input()) 25 | for _ in range(t): 26 | n = int(input()) 27 | ob = Solution() 28 | print(ob.maxSum(n)) 29 | # } Driver Code Ends -------------------------------------------------------------------------------- /DSA 450 GFG/max_sum_memoization.py: -------------------------------------------------------------------------------- 1 | 2 | #https://practice.geeksforgeeks.org/problems/maximum-sum-problem2211/1/ 3 | 4 | # Approach 1 - Memoization 5 | 6 | from functools import lru_cache 7 | 8 | class Solution: 9 | @lru_cache(maxsize = 1000) 10 | def maxSum(self, n): 11 | # code here 12 | if(n == 0 or n == 1): 13 | return n 14 | else: 15 | return max( (self.maxSum(n//2) + self.maxSum(n//3) + self.maxSum(n//4)) , n ) 16 | 17 | 18 | 19 | #{ 20 | # Driver Code Starts 21 | #Initial Template for Python 3 22 | 23 | if __name__ == '__main__': 24 | t = int(input()) 25 | for _ in range(t): 26 | n = int(input()) 27 | ob = Solution() 28 | print(ob.maxSum(n)) 29 | # } Driver Code Ends 30 | 31 | 32 | -------------------------------------------------------------------------------- /DSA 450 GFG/merge_intervals.py: -------------------------------------------------------------------------------- 1 | 2 | # Link for the problem : https://leetcode.com/problems/merge-intervals/ 3 | 4 | # Input: intervals = [[1,3],[2,6],[8,10],[15,18]] 5 | # Output: [[1,6],[8,10],[15,18]] 6 | # Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. 7 | 8 | # Create a list merged to store the merged intervals 9 | # Condition for merging : If the first index of current interval is less than last index of previous interval 10 | # If condition satisfies , replace the last index of previous interval with the maximum between current and previous interval's last index 11 | # If not , then simply append the interval in the merged list 12 | 13 | 14 | 15 | class Solution: 16 | def merge(self, intervals): 17 | 18 | intervals.sort(key = lambda x : x[0]) 19 | merged = [] 20 | 21 | for interval in intervals : 22 | 23 | if not merged or merged[-1][1] < interval[0] : 24 | merged.append(interval) 25 | else : 26 | merged[-1][1] = max(merged[-1][1] , interval[1]) 27 | 28 | return merged 29 | 30 | 31 | -------------------------------------------------------------------------------- /DSA 450 GFG/move all negative numbers.cpp: -------------------------------------------------------------------------------- 1 | /* Move all negative numbers to beginning and positive to end with constant extra space 2 | An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers. 3 | Examples : 4 | 5 | Input: -12, 11, -13, -5, 6, -7, 5, -3, -6 6 | Output: -12 -13 -5 -7 -3 -6 11 6 5 7 | */ 8 | 9 | // A C++ program to put all negative 10 | // numbers before positive numbers 11 | #include 12 | using namespace std; 13 | 14 | void rearrange(int arr[], int n) 15 | { 16 | int j = 0; 17 | for (int i = 0; i < n; i++) { 18 | if (arr[i] < 0) { 19 | if (i != j) 20 | swap(arr[i], arr[j]); 21 | j++; 22 | } 23 | } 24 | } 25 | 26 | // A utility function to print an array 27 | void printArray(int arr[], int n) 28 | { 29 | for (int i = 0; i < n; i++) 30 | printf("%d ", arr[i]); 31 | } 32 | 33 | // Driver code 34 | int main() 35 | { 36 | int arr[] = { -1, 2, -3, 4, 5, 6, -7, 8, 9 }; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | rearrange(arr, n); 39 | printArray(arr, n); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /DSA 450 GFG/move_all_neg_numbers.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def rearrange (arr , n ): 4 | j = 0 5 | for i in range(0 , n) : 6 | if(arr[i] < 0): 7 | temp = arr[i] 8 | arr[i] = arr[j] 9 | arr[j] = temp 10 | j = j + 1 11 | print(arr) 12 | 13 | #Driver code 14 | sequence = [1 , 3, - 6 , 9 , -3 , -1] 15 | length = len(sequence) 16 | print(sequence.sort) 17 | rearrange(sequence , length) -------------------------------------------------------------------------------- /DSA 450 GFG/next_permutation.py: -------------------------------------------------------------------------------- 1 | # Link for the problem : https://leetcode.com/problems/next-permutation/ 2 | 3 | 4 | class Solution(object): 5 | 6 | def nextPermutation(self, nums): 7 | found = False 8 | i = len(nums)-2 9 | while i >=0: 10 | if nums[i] < nums[i+1]: 11 | found =True 12 | break 13 | i-=1 14 | if not found: 15 | nums.sort() 16 | else: 17 | m = self.findMaxIndex(i+1,nums,nums[i]) 18 | nums[i],nums[m] = nums[m],nums[i] 19 | nums[i+1:] = nums[i+1:][::-1] 20 | return nums 21 | 22 | def findMaxIndex(self,index,a,curr): 23 | ans = -1 24 | index = 0 25 | for i in range(index,len(a)): 26 | if a[i]>curr: 27 | if ans == -1: 28 | ans = curr 29 | index = i 30 | else: 31 | ans = min(ans,a[i]) 32 | index = i 33 | return index 34 | ob1 = Solution() 35 | -------------------------------------------------------------------------------- /DSA 450 GFG/post-ord-iterative.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.com/problems/binary-tree-postorder-traversal/ 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode: 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | class Solution: 11 | def postorderTraversal(self, root: TreeNode) -> List[int]: 12 | 13 | if root == None: 14 | return 15 | 16 | stack = deque() 17 | stack.append(root) 18 | 19 | # create another stack to store postorder traversal 20 | out = deque() 21 | 22 | # loop till stack is empty 23 | while stack: 24 | 25 | # pop a node from the stack and push the data into the output stack 26 | curr = stack.pop() 27 | out.append(curr.val) 28 | 29 | # push the left and right child of the popped node into the stack 30 | if curr.left: 31 | stack.append(curr.left) 32 | 33 | if curr.right: 34 | stack.append(curr.right) 35 | 36 | out.reverse() 37 | 38 | return out -------------------------------------------------------------------------------- /DSA 450 GFG/reverse_an_array.py: -------------------------------------------------------------------------------- 1 | # Write a program to reverse an array 2 | # Given an array (or string), the task is to reverse the array/string. 3 | # Examples : 4 | 5 | # Input : arr[] = [1, 2, 3] 6 | # Output : arr[] = [3, 2, 1] 7 | # Input : arr[] = [4, 5, 1, 2] 8 | # Output : arr[] = [2, 1, 5, 4] 9 | 10 | 11 | 12 | 13 | # Reverse of an array can be implented in Python using the List slicing 14 | 15 | def reverseList(a): 16 | print( a[::-1]) 17 | 18 | # Driver Code 19 | arr = [4,5,1,2] 20 | print(arr) 21 | print("Reverse : ") 22 | reverseList(arr) -------------------------------------------------------------------------------- /DSA 450 GFG/rotate_by_90.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | #https://practice.geeksforgeeks.org/problems/rotate-by-90-degree0356/1/?company[]=Morgan%20Stanley&company[]=Morgan%20Stanley&page=1&query=company[]Morgan%20Stanleypage1company[]Morgan%20Stanley 4 | 5 | 6 | def rotate(a): 7 | #code here 8 | 9 | n = len(a) 10 | 11 | # Transpose 12 | for i in range(n): 13 | for j in range(i): 14 | a[i][j] , a[j][i] = a[j][i] , a[i][j] 15 | 16 | # Rotate the rows 17 | 18 | for i in range(int(n/2)): 19 | a[i] , a[n-i-1] = a[n-i-1] , a[i] 20 | 21 | return a 22 | 23 | #{ 24 | # Driver Code Starts 25 | #Initial Template for Python 3 26 | 27 | 28 | if __name__ == '__main__': 29 | t = int(input()) 30 | for _ in range(t): 31 | N=int(input()) 32 | arr=[int(x) for x in input().split()] 33 | matrix=[] 34 | 35 | for i in range(0,N*N,N): 36 | matrix.append(arr[i:i+N]) 37 | 38 | rotate(matrix) 39 | for i in range(N): 40 | for j in range(N): 41 | print(matrix[i][j], end =' ') 42 | print() 43 | 44 | 45 | # } Driver Code Ends -------------------------------------------------------------------------------- /DSA 450 GFG/snake_pattern.py: -------------------------------------------------------------------------------- 1 | # Link for the problem : https://practice.geeksforgeeks.org/problems/print-matrix-in-snake-pattern-1587115621/1 2 | 3 | 4 | def snakePattern(matrix): 5 | # code here 6 | n_rows = len(matrix) 7 | n_columns = len(matrix[0]) 8 | k = 0 9 | output = [] 10 | 11 | for i in range(0 , n_rows): 12 | if(i%2 == 0): 13 | for j in range(0 , n_columns): 14 | output.append(matrix[i][j]) 15 | elif(i%2 != 0): 16 | for j in range(n_columns-1 , -1, -1): 17 | output.append(matrix[i][j]) 18 | 19 | return output 20 | 21 | 22 | #{ 23 | # Driver Code Starts 24 | #Initial Template for Python 3 25 | 26 | if __name__ == '__main__': 27 | t = int(input()) 28 | for _ in range(t): 29 | n = int(input()) 30 | values = list(map(int, input().strip().split())) 31 | k = 0 32 | matrix =[] 33 | for i in range(n): 34 | row=[] 35 | for j in range(n): 36 | row.append(values[k]) 37 | k+=1 38 | matrix.append(row) 39 | ans = snakePattern(matrix) 40 | for i in ans: 41 | print(i,end=" ") 42 | print() 43 | 44 | 45 | # } Driver Code Ends -------------------------------------------------------------------------------- /DSA 450 GFG/spiral_matrix.py: -------------------------------------------------------------------------------- 1 | # Link to the problem : https://leetcode.com/problems/spiral-matrix/ 2 | 3 | class Solution: 4 | def spiralOrder(self, matrix: List[List[int]]) -> List[int]: 5 | res = [] 6 | n = len(matrix) 7 | if (n == 0): 8 | return matrix 9 | 10 | # Initialize the Boundaries 11 | rowBeg = 0 12 | rowEnd = len(matrix) - 1 13 | colBeg = 0 14 | colEnd = len(matrix[0]) - 1 15 | 16 | #Right Traversal 17 | while(rowBeg <= rowEnd and colBeg <= colEnd): 18 | 19 | for i in range(colBeg , colEnd + 1): 20 | res.append(matrix[rowBeg][i]) 21 | rowBeg += 1 22 | 23 | #Bottom Traversal 24 | for i in range(rowBeg , rowEnd + 1): 25 | res.append(matrix[i][colEnd]) 26 | colEnd -= 1 27 | 28 | #Left Traversal 29 | 30 | if(rowBeg <= rowEnd): 31 | for i in range(colEnd , colBeg - 1 , -1 ): 32 | res.append(matrix[rowEnd][i]) 33 | rowEnd -= 1 34 | 35 | #Upward Traversal 36 | 37 | if(colBeg <= colEnd): 38 | for i in range(rowEnd , rowBeg - 1 , -1): 39 | res.append(matrix[i][colBeg]) 40 | colBeg += 1 41 | 42 | return res -------------------------------------------------------------------------------- /DSA 450 GFG/subtree_of_another_tree.py: -------------------------------------------------------------------------------- 1 | 2 | # https://leetcode.com/problems/subtree-of-another-tree/submissions/ 3 | 4 | # Definition for a binary tree node. 5 | # class TreeNode(object): 6 | # def __init__(self, val=0, left=None, right=None): 7 | # self.val = val 8 | # self.left = left 9 | # self.right = right 10 | 11 | class Solution(object): 12 | 13 | def sameTree(self , root , subRoot): 14 | if(root == None or subRoot == None): 15 | return root == None and subRoot == None 16 | elif(root.val == subRoot.val): 17 | return self.sameTree(root.right , subRoot.right) and self.sameTree(root.left , subRoot.left) 18 | else: 19 | return False 20 | 21 | def isSubtree(self, root, subRoot): 22 | """ 23 | :type root: TreeNode 24 | :type subRoot: TreeNode 25 | :rtype: bool 26 | """ 27 | if(root == None): 28 | return False 29 | elif(self.sameTree(root , subRoot)): 30 | return True 31 | else: 32 | return self.isSubtree(root.right , subRoot) or self.isSubtree(root.left , subRoot) 33 | 34 | -------------------------------------------------------------------------------- /DSA 450 GFG/vertical_order_traversal.py: -------------------------------------------------------------------------------- 1 | #Link to the problem : https://leetcode.com/problems/vertical-order-traversal-of-a-binary-tree/ 2 | 3 | # Definition for a binary tree node. 4 | # class TreeNode: 5 | # def __init__(self, val=0, left=None, right=None): 6 | # self.val = val 7 | # self.left = left 8 | # self.right = right 9 | class Solution: 10 | def verticalTraversal(self, root): 11 | 12 | def _traverse(node, row, col, cache): 13 | 14 | if not node: 15 | return 16 | _traverse(node.left, row + 1, col - 1, cache) 17 | cache[col].append((row, node.val)) 18 | _traverse(node.right, row + 1, col + 1, cache) 19 | 20 | cache = defaultdict(list) 21 | _traverse(root, 0, 0, cache) 22 | ans = [] 23 | for key in sorted(cache): 24 | ans.append(x[1] for x in sorted(cache[key])) 25 | return ans -------------------------------------------------------------------------------- /Data Structures/Graphs/DFSTraversal/DFSTraversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int N = 1e6+3; 5 | vector g[N]; 6 | bool vis[N]; 7 | 8 | void dfs(int u) 9 | { 10 | vis[u] = 1; 11 | for(int v:g[u]) 12 | { 13 | if(vis[v]) continue; 14 | dfs(v); 15 | } 16 | } 17 | 18 | int main(int argc, char const *argv[]) 19 | { 20 | freopen("in.txt","r",stdin); 21 | int n,m,u,v; 22 | cin>>n>>m; 23 | while(m--) 24 | { 25 | cin>>u>>v; 26 | g[u].push_back(v); 27 | g[v].push_back(u); // comment this in the case of directional edges 28 | } 29 | 30 | dfs(1); // starting node 31 | 32 | if(vis[6]) cout<<"Yes"; 33 | else cout<<"No, we can't reach!"; 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /Data Structures/Graphs/DFSTraversal/in.txt: -------------------------------------------------------------------------------- 1 | 6 5 2 | 1 2 3 | 2 3 4 | 3 1 5 | 2 6 6 | 4 5 7 | -------------------------------------------------------------------------------- /Data Structures/Graphs/isGraphBipartite.cpp: -------------------------------------------------------------------------------- 1 | /* ' Is Graph Bipartite ' problem from Leetcode 2 | 3 | A graph is bipartite if the nodes can be partitioned into two independent sets A and B 4 | such that every edge in the graph connects a node in set A and a node in set B. 5 | 6 | The main function is predefined. Here is the code to the question. 7 | */ 8 | 9 | 10 | class Solution { 11 | public: 12 | 13 | vector color; 14 | bool dfs(int node, vector> &graph){ 15 | for(auto child: graph[node]){ 16 | if(color[child] != -1){ 17 | if(color[child] == color[node]) 18 | return false; 19 | continue; 20 | } 21 | color[child] = (color[node] + 1)%2; 22 | if(!dfs(child, graph)) 23 | return false; 24 | } 25 | return true; 26 | } 27 | 28 | bool isBipartite(vector>& graph) { 29 | int n = graph.size(); 30 | color = vector (n, -1); 31 | for(int node=0; node 6 | 7 | using namespace std; 8 | 9 | class Node{ 10 | public: 11 | int data; 12 | Node *next; 13 | }; 14 | void printLinkedList(Node *temp) 15 | { 16 | while(temp!=NULL) 17 | { 18 | cout<data<<"->"; 19 | temp = temp->next; 20 | } 21 | cout<<"NULL"; 22 | } 23 | int main() 24 | { 25 | Node *head = NULL; 26 | Node *second = NULL; 27 | Node *third = NULL; 28 | 29 | // allocating three nodes 30 | head = new Node(); 31 | second = new Node(); 32 | third = new Node(); 33 | 34 | head->data = 1; 35 | head->next = second; 36 | 37 | second->data = 2; 38 | second->next = third; 39 | 40 | third->data = 3; 41 | third->next=NULL; 42 | 43 | // traversing the linkedlist 44 | printLinkedList(head); 45 | 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Singly Linked List/binary_number_linkedlist_integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | LeetCode : #1290 3 | Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. 4 | The linked list holds the binary representation of a number. 5 | 6 | Return the decimal value of the number in the linked list. 7 | */ 8 | class Solution { 9 | public: 10 | int getDecimalValue(ListNode* head) { 11 | int total = 0, res = 0; 12 | ListNode *temp = head; 13 | while(temp != NULL){ 14 | temp = temp->next; 15 | total++; 16 | } 17 | temp = head; 18 | total--; 19 | while(temp != NULL){ 20 | res += pow(2, total) * temp->val; 21 | total--; 22 | temp = temp->next; 23 | } 24 | return res; 25 | } 26 | }; -------------------------------------------------------------------------------- /Data Structures/Queues/priority_queue_max.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | priority_queue pq; 9 | pq.push(90); 10 | pq.push(20); 11 | pq.push(40); 12 | pq.push(10); 13 | while(!pq.empty()){ 14 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char const *argv[]) 7 | { 8 | priority_queue, greater> pq; 9 | pq.push(90); 10 | pq.push(20); 11 | pq.push(40); 12 | pq.push(10); 13 | while(!pq.empty()){ 14 | cout< 6 | using namespace std; 7 | bool isBalanced(string); 8 | 9 | bool isBalanced(string expr) 10 | { 11 | stack st; 12 | int size = expr.length(); 13 | 14 | for(int i=0;i>t; 35 | while(t--) 36 | { 37 | cin>>expr; 38 | if(isBalanced(expr)) 39 | cout<<"balanced\n"; 40 | else cout<<"not balanced\n"; 41 | } 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Data Structures/Trees/binary_tree_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Node 6 | { 7 | public: 8 | int data; 9 | Node *left, *right; 10 | }; 11 | 12 | void inOrder(Node *root) 13 | { 14 | if (root == NULL) 15 | return; 16 | inOrder(root->left); 17 | cout << root->data << " "; 18 | inOrder(root->right); 19 | } 20 | 21 | void preOrder(Node *root) 22 | { 23 | if (root == NULL) 24 | return; 25 | cout << root->data << " "; 26 | preOrder(root->left); 27 | preOrder(root->right); 28 | } 29 | 30 | void postOrder(Node *root) 31 | { 32 | if (root == NULL) 33 | return; 34 | postOrder(root->left); 35 | postOrder(root->right); 36 | cout << root->data << " "; 37 | } 38 | 39 | int main() 40 | { 41 | Node *root = NULL, *one = NULL, *two = NULL, *three = NULL, *four = NULL; 42 | 43 | root = new Node(); 44 | root->data = 10; // root node 45 | 46 | one = new Node(); 47 | two = new Node(); 48 | three = new Node(); 49 | four = new Node(); 50 | 51 | one->data = 20; 52 | two->data = 30; 53 | three->data = 40; 54 | four->data = 50; 55 | 56 | root->left = one; 57 | root->right = two; 58 | 59 | root->left->left = three; 60 | root->left->right = four; 61 | 62 | inOrder(root); 63 | cout << endl; 64 | preOrder(root); 65 | cout << endl; 66 | postOrder(root); 67 | 68 | return 0; 69 | } 70 | -------------------------------------------------------------------------------- /Data Structures/Trees/delete_leaves_with_given_value.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | -------------- 4 | Given a binary tree root and an integer target, delete all the leaf nodes with value target. 5 | 6 | Note that once you delete a leaf node with value target, if it's parent node becomes a leaf node and has the value target, it 7 | should also be deleted (you need to continue doing that until you can't). 8 | */ 9 | 10 | /** 11 | * Definition for a binary tree node. 12 | * struct TreeNode { 13 | * int val; 14 | * TreeNode *left; 15 | * TreeNode *right; 16 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 17 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 18 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 19 | * }; 20 | */ 21 | class Solution 22 | { 23 | public: 24 | TreeNode *removeLeafNodes(TreeNode *root, int target) 25 | { 26 | if (!root) 27 | return NULL; 28 | 29 | root->left = removeLeafNodes(root->left, target); 30 | root->right = removeLeafNodes(root->right, target); 31 | 32 | if (root->left == NULL && root->right == NULL && root->val == target) 33 | { 34 | return NULL; 35 | } 36 | 37 | return root; 38 | } 39 | }; -------------------------------------------------------------------------------- /Data Structures/Trees/invert_a_binary_tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | 4 | Invert a binary tree i.e., Convert a Binary Tree into its Mirror Tree. 5 | 6 | */ 7 | 8 | /** 9 | * Definition for a binary tree node. 10 | * struct TreeNode { 11 | * int val; 12 | * TreeNode *left; 13 | * TreeNode *right; 14 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 15 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 16 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 17 | * }; 18 | */ 19 | class Solution 20 | { 21 | public: 22 | TreeNode *invertTree(TreeNode *root) 23 | { 24 | if (!root) 25 | return nullptr; 26 | else 27 | { 28 | 29 | TreeNode *temp = (TreeNode *)malloc(sizeof(TreeNode)); 30 | 31 | invertTree(root->left); 32 | invertTree(root->right); 33 | 34 | temp = root->left; 35 | root->left = root->right; 36 | root->right = temp; 37 | } 38 | 39 | return root; 40 | } 41 | }; -------------------------------------------------------------------------------- /Data Structures/Trees/merge_two_binary_trees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | -------------- 4 | 5 | Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped 6 | while the others are not. 7 | 8 | You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new 9 | value of the merged node. Otherwise, the NOT null node will be used as the node of new tree. 10 | */ 11 | 12 | /** 13 | * Definition for a binary tree node. 14 | * struct TreeNode { 15 | * int val; 16 | * TreeNode *left; 17 | * TreeNode *right; 18 | * TreeNode() : val(0), left(nullptr), right(nullptr) {} 19 | * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 20 | * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 21 | * }; 22 | */ 23 | class Solution 24 | { 25 | public: 26 | TreeNode *mergeTrees(TreeNode *t1, TreeNode *t2) 27 | { 28 | 29 | if (t1 == NULL && t2 == NULL) 30 | return NULL; 31 | if (!t2) 32 | return t1; 33 | if (!t1) 34 | return t2; 35 | 36 | TreeNode *new_node = (TreeNode *)malloc(sizeof(struct TreeNode)); 37 | new_node->val = t1->val + t2->val; 38 | new_node->left = mergeTrees(t1->left, t2->left); 39 | new_node->right = mergeTrees(t1->right, t2->right); 40 | return new_node; 41 | } 42 | }; -------------------------------------------------------------------------------- /Divide and Conquer/DCPower.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class DCPower 4 | { 5 | public static int power(int a,int b) 6 | { 7 | if(b==0) 8 | return 1; 9 | if(b%2==0) 10 | { 11 | return power(a,b/2)*power(a,b/2); 12 | } 13 | else { 14 | return power(a,b/2)*power(a,b/2)*a; 15 | } 16 | } 17 | public static void main(String args[]) 18 | { 19 | int a,b; 20 | Scanner sc = new Scanner(System.in); 21 | 22 | a = sc.nextInt(); 23 | b = sc.nextInt(); 24 | 25 | sc.close(); 26 | System.out.println(power(a,b)); 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Divide and Conquer/PowerMem.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class PowerMem 4 | { 5 | public static int power(int a,int b) 6 | { int halfpower; 7 | if(b==0) 8 | return 1; 9 | if(b%2==0) 10 | { halfpower = power(a,b/2); 11 | return halfpower*halfpower; 12 | } 13 | else { 14 | halfpower = power(a,b/2); 15 | return halfpower*halfpower*a; 16 | } 17 | } 18 | public static void main(String args[]) 19 | { 20 | int a,b; 21 | Scanner sc = new Scanner(System.in); 22 | 23 | a = sc.nextInt(); 24 | b = sc.nextInt(); 25 | 26 | sc.close(); 27 | 28 | System.out.println(power(a,b)); 29 | 30 | } 31 | } -------------------------------------------------------------------------------- /Divide and Conquer/PowerofN.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class PowerofN 3 | { 4 | public static void main(String args[]) 5 | { 6 | int n,p; 7 | Scanner sc = new Scanner(System.in); 8 | 9 | n = sc.nextInt(); 10 | p = sc.nextInt(); 11 | 12 | int pow = 1; 13 | for(int i=1;i<=p;i++) 14 | { 15 | pow*=n; 16 | } 17 | System.out.println(pow); 18 | } 19 | } -------------------------------------------------------------------------------- /Dynamic Programming/ClimbingStairs_bottom_up.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/climbing-stairs/submissions/ 2 | 3 | # Bottom Up approach 4 | 5 | class Solution: 6 | def climbStairs(self, n: int) -> int: 7 | if(n == 1): 8 | return 1 9 | dp = [0]*(n) 10 | dp[0] = 1 11 | dp[1] = 2 12 | for i in range(2 , n): 13 | dp[i] = dp[i-1] + dp[i-2] 14 | return dp[n-1] -------------------------------------------------------------------------------- /Dynamic Programming/ClimbingStairs_memoization.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/climbing-stairs/ 2 | 3 | # Memoization 4 | 5 | from functools import lru_cache 6 | 7 | class Solution: 8 | @lru_cache(maxsize = 1000) 9 | def climbStairs(self, n: int) -> int: 10 | if(n == 0 or n == 1): 11 | return 1 12 | else: 13 | return self.climbStairs(n-1) + self.climbStairs(n-2) 14 | -------------------------------------------------------------------------------- /Dynamic Programming/FibonacciMem.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class FibonacciMem { 4 | final int max=100; 5 | int fib_array[]= new int[max]; 6 | 7 | public void initialize() 8 | { 9 | fib_array[0]=0; 10 | fib_array[1]=1; 11 | for(int i=2;i 2 | int LCS(char s1[], char s2[]); 3 | int LCS_utility(char s1[], char s2[], int s1_ind, int s2_ind); 4 | #define max(x,y) ( (x) > (y) ? (x) : (y)) 5 | 6 | int main() 7 | { 8 | // char s1[] = "abcd", s2[]="axd"; 9 | // char s1[] = "abcdef", s2[] = "axyczf"; 10 | char s1[] = "abcdefghijklmnopqrstuvwxyz", s2[]="selvakumarbalakrishnan"; 11 | int lcs; 12 | 13 | lcs = LCS(s1,s2); 14 | printf("%d", lcs); 15 | 16 | 17 | return 0; 18 | } 19 | int LCS(char s1[], char s2[]) 20 | { 21 | return LCS_utility(s1,s2,0,0); 22 | } 23 | int LCS_utility(char s1[], char s2[], int s1_ind, int s2_ind) 24 | { 25 | int left, right; 26 | if(s1[s1_ind] == 0 || s2[s2_ind] == 0) 27 | return 0; 28 | if(s1[s1_ind] == s2[s2_ind]) 29 | return 1 + LCS_utility(s1,s2, s1_ind+1, s2_ind+1); 30 | else 31 | { 32 | left=LCS_utility(s1, s2, s1_ind,s2_ind+1); 33 | right = LCS_utility(s1,s2, s1_ind+1,s2_ind); 34 | return max(left,right); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Dynamic Programming/Longest_common_substring.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings. The task is to find the length of the longest common substring. 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | 8 | class Solution{ 9 | public: 10 | 11 | int longestCommonSubstr (string s1, string s2, int n, int m) 12 | { 13 | int len_subs[n+1][m+1]; 14 | int i,j,maxLength=0; 15 | 16 | for(i=0;i<=n;i++) 17 | len_subs[i][0] = 0; //first row 18 | 19 | for(i=0;i<=m;i++) 20 | len_subs[0][i] = 0; // first column 21 | 22 | for(i = 1;i<=n;i++) 23 | { 24 | for(j=1;j<=m;j++) 25 | { 26 | if(s1[i-1] == s2[j-1]) 27 | { 28 | len_subs[i][j] = 1 + len_subs[i-1][j-1]; 29 | if(maxLength < len_subs[i][j]) 30 | maxLength = len_subs[i][j]; 31 | } 32 | else 33 | len_subs[i][j] = 0; 34 | } 35 | } 36 | return maxLength; 37 | } 38 | }; 39 | int main() 40 | { 41 | int t; cin >> t; 42 | while (t--) 43 | { 44 | int n, m; cin >> n >> m; 45 | string s1, s2; 46 | cin >> s1 >> s2; 47 | Solution ob; 48 | 49 | cout << ob.longestCommonSubstr (s1, s2, n, m) << endl; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Dynamic Programming/MinPathSum.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.Math; 3 | 4 | public class MinPathSum 5 | { 6 | //to find the minimum path 7 | public static int minPathSum(int a[][]) 8 | { 9 | for (int i = 1; i < 4; i++) 10 | a[i][0] = a[i-1][0] + a[i][0]; 11 | 12 | for (int j = 1; j < 4; j++) 13 | a[0][j] = a[0][j-1] + a[0][j]; 14 | 15 | for(int i=1;i<4;i++) 16 | { 17 | for(int j=1;j<4;j++) 18 | { 19 | a[i][j] = Math.min(a[i-1][j], a[i][j-1]) + a[i][j]; 20 | } 21 | } 22 | 23 | return a[3][3]; 24 | } 25 | public static void main(String args[]) 26 | { 27 | int a[][] = new int[4][4]; 28 | Scanner sc = new Scanner(System.in); 29 | 30 | for(int i=0;i<4;i++) 31 | { 32 | for(int j=0;j<4;j++) 33 | { 34 | a[i][j] = sc.nextInt(); 35 | } 36 | } 37 | 38 | System.out.println("The sum of the minimum path is "+minPathSum(a)); 39 | 40 | } 41 | } -------------------------------------------------------------------------------- /Dynamic Programming/binomial_coefficient.cpp: -------------------------------------------------------------------------------- 1 | // Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). 2 | // For example, our function should return 6 for n = 4 and k = 2, and it should return 10 for n = 5 and k = 2. 3 | 4 | // The idea we have used here is inspired by the pascal triangle. 5 | /* 6 | 1 7 | 1 1 8 | 1 2 2 1 9 | 1 3 4 3 1 */ 10 | 11 | #include 12 | using namespace std; 13 | 14 | int binomial(int n, int r) 15 | { 16 | if (r > n) 17 | return 0; 18 | if (r == 0 || r == n) 19 | return 1; 20 | 21 | int dp[n + 1][r + 1]; 22 | for (int i = 1; i <= n; i++) 23 | { 24 | for (int j = 1; j <= r; j++) 25 | { 26 | if (i == j || j == 0) // Base Condition 27 | dp[i][j] = 1; 28 | else 29 | { // we have taken a mod, so that higher results can be calculted too. 30 | dp[i][j] = (dp[i - 1][j - 1] + dp[i - 1][j]) % 10000007; 31 | } 32 | } 33 | } 34 | return dp[n][r]; 35 | } 36 | 37 | int main() 38 | { 39 | int n; 40 | int r; 41 | cin >> n >> r; 42 | return binomial(n, r); 43 | } -------------------------------------------------------------------------------- /Dynamic Programming/sliding_window_sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, the aim is to print the sum of the elements in a 3 | window of size k.The kth window of the input list is the integers from 4 | index k to index k + window size - 1(inclusive). 5 | */ 6 | #include 7 | 8 | using namespace std; 9 | 10 | int main() 11 | { 12 | int n, k; 13 | cin>>n; 14 | int arr[n], index, sum=0; 15 | for(index=0;index>arr[index]; 18 | } 19 | cin>>k; 20 | for(index=0;index 2 | int gcd(int num1,int num2) 3 | { 4 | int factor = 2; 5 | int gcd = 1; 6 | 7 | while(num2>=factor){ 8 | if(num1%factor == 0 && num2%factor == 0){ 9 | gcd *= factor; 10 | num1 = num1/factor; 11 | num2 = num2/factor; 12 | } 13 | else 14 | factor += 1; 15 | } 16 | return gcd; 17 | } 18 | int main(int argc, char const *argv[]) 19 | { 20 | int a,b; 21 | scanf("%d %d",&a,&b); 22 | printf("The GCD of %d and %d is: %d",a,b,gcd(a,b)); 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /GCD of two numbers/Euclid's Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | int gcd(int a,int b) // to calculate the GCD of two numbers 3 | { 4 | int r; 5 | do 6 | { 7 | r=a%b; 8 | a=b; 9 | b=r; 10 | } while (b!=0); 11 | 12 | return a; 13 | } 14 | int main(int argc, char const *argv[]) // DRIVER function 15 | { 16 | int a,b; 17 | scanf("%d %d",&a,&b); 18 | printf("The GCD of %d and %d is: %d",a,b,gcd(a,b)); 19 | return 0; 20 | } 21 | -------------------------------------------------------------------------------- /GCD of two numbers/GCD Using Recursion.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int FindGCD(int n,int m) 5 | { 6 | if(m==0) 7 | return n; 8 | return FindGCD(m,n%m); 9 | } 10 | 11 | int main() 12 | { 13 | int n,m,gcd; 14 | printf("Enter first number: "); 15 | scanf("%d",&n); 16 | printf("Enter second number: "); 17 | scanf("%d",&m); 18 | gcd=FindGCD(n,m); 19 | printf("GCD of %d and %d is: %d",n,m,gcd); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /GCD of two numbers/Normal GCD Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | int min(int a,int b) // to calculate the minimum of two numbers 3 | { 4 | if(a 17 | #include 18 | using namespace std; 19 | bool isHappy(int n) 20 | { 21 | int sum =0; 22 | while(n>0) 23 | { 24 | sum = sum + (n%10) * (n%10); 25 | n = n / 10; 26 | } 27 | if(sum==1) 28 | { 29 | return true; 30 | } 31 | else if(sum==4) { 32 | return false; 33 | } 34 | isHappy(sum); 35 | } 36 | bool isPrime(int n) 37 | { 38 | if(n==1) 39 | return false; 40 | else{ 41 | for(int i=2;i<=(int)sqrt(n);i++) 42 | { 43 | if(n%i == 0) 44 | return false; 45 | } 46 | return true; 47 | } 48 | } 49 | int main(int argc, char const *argv[]) 50 | { 51 | int a,b,count=0,n; 52 | cin>>a>>b>>n; 53 | for(int i=a;i<=b;i++) 54 | { 55 | if(isPrime(i) && isHappy(i)) 56 | { 57 | count++; 58 | } 59 | if(count == n) 60 | { 61 | cout< 15 | using namespace std; 16 | int bubbleSort(int a[],int n) 17 | { int temp; 18 | for(int i=0;i>b>>n; 35 | int z[n]; 36 | for(int i=0;i>z[i]; 39 | } 40 | bubbleSort(z,n); 41 | int flag = 1; 42 | for(int i=0;i 3 | #include 4 | #include 5 | using namespace std; 6 | bool isHeap(int arr[], int n) 7 | { 8 | // Start from root 9 | for (int i = 0; i <= (n - 2) / 2; i++) 10 | { 11 | // If left child is greater, return false 12 | if (arr[2 * i + 1] > arr[i]) 13 | return false; 14 | 15 | // If right child is greater, return false 16 | if (2 * i + 2 < n && arr[2 * i + 2] > arr[i]) 17 | return false; 18 | } 19 | return true; 20 | } 21 | // Driver program 22 | int main() 23 | { 24 | int n; 25 | cout << "Enter the number of array elements-"; 26 | cin >> n; 27 | int arr[n]; 28 | cout << "Enter the array elements-"; 29 | for (int i = 0; i < n; i++) 30 | { 31 | cin >> arr[i]; 32 | } 33 | isHeap(arr, n) ? printf("Yes, it represents a max-heap.") : printf("No"); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /General Questions/Difficult_pattern2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int main(){ 4 | int i,j,k=10,a=30,l,m,t=5; 5 | for(i=1;i<=5;i++){ 6 | for(j=i-1;j>=1;j--) 7 | printf("\t"); 8 | for(l=5;l>=i;l--){ 9 | printf("%d\t",k); 10 | k += 10; 11 | } 12 | for(m=a-t+1;m<=a;m++){ 13 | if(m==a) 14 | printf("%d",m); 15 | else 16 | printf("%d0",m); 17 | } 18 | a -= t; 19 | t -= 1; 20 | printf("\n"); 21 | } 22 | } 23 | /* 24 | Output: 25 | 10 20 30 40 50 26027028029030 26 | 60 70 80 90 22023024025 27 | 100 110 120 19020021 28 | 130 140 17018 29 | 150 16 30 | 31 | */ 32 | -------------------------------------------------------------------------------- /General Questions/Difficult_pattern3.c: -------------------------------------------------------------------------------- 1 | /* WAP to generate the given pattern 2 | 123 3 | 12345 4 | 1234567 5 | 123456789 6 | */ 7 | #include 8 | int main(){ 9 | int i,j,k; 10 | for(i=1;i<=4;i++){ 11 | for(j=1;j<=i;j++) 12 | printf("%d",j); 13 | for(k=1;k<=j;k++) 14 | printf("%d",i+k); 15 | printf("\n"); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /General Questions/Plus_One.cpp: -------------------------------------------------------------------------------- 1 | //Tawfik Yasser 2 | class Solution { 3 | public: 4 | vector plusOne(vector& digits) { 5 | for(int i = digits.size()-1 ;i>=0;i--){ 6 | if(digits[i] +1 == 10 ){ 7 | digits[i] = 0; 8 | }else{ 9 | digits[i] +=1; 10 | return digits; 11 | } 12 | } 13 | vector ds(digits.size()+1,0); 14 | ds[0] = 1; 15 | return ds; 16 | } 17 | }; 18 | 19 | /* Problem Statement 20 | 21 | Given a non-empty array of decimal digits representing a non-negative integer, increment one to the integer. 22 | 23 | The digits are stored such that the most significant digit is at the head of the list, and each element in the array contains a single digit. 24 | 25 | You may assume the integer does not contain any leading zero, except the number 0 itself. 26 | 27 | --------------------------------------------------------------------------------------------------------------------------------------------- 28 | Input: digits = [1,2,3] 29 | Output: [1,2,4] 30 | Explanation: The array represents the integer 123. 31 | 32 | */ -------------------------------------------------------------------------------- /General Questions/christmas_tree.c: -------------------------------------------------------------------------------- 1 | /* 2 | Christmas Tree Pattern 3 | 4 | input 3 5 | output 6 | * 7 | *** 8 | ***** 9 | ******* 10 | *** 11 | ***** 12 | * 13 | * 14 | 15 | We divide the problem into 3 parts: 16 | 1. Full triangle 17 | 2. Partial Triangle 18 | 3. Stand 19 | */ 20 | #include 21 | 22 | void fulltriangle(int row) 23 | { 24 | for(int i=1;i<=row;i++) 25 | { 26 | printf("%*s",row-i,""); 27 | for(int j=1;j<=(2*i-1);j++) 28 | { 29 | printf("*"); 30 | } 31 | printf("\n"); 32 | } 33 | } 34 | void partialtriangle(int row,int offset) 35 | { 36 | for(int i=1;i<=row;i++) 37 | { 38 | printf("%*s",offset,""); 39 | printf("%*s",row-i,""); 40 | for(int j=1;j<=(2*i+1);j++) 41 | { 42 | printf("*"); 43 | } 44 | printf("\n"); 45 | } 46 | } 47 | void stand(int row) 48 | { 49 | for(int i=1;i<=2;i++) 50 | { 51 | printf("%*s",row,""); 52 | printf("*\n"); 53 | } 54 | } 55 | int main(int argc, char const *argv[]) 56 | { 57 | int n,offset=1; 58 | scanf("%d",&n); 59 | fulltriangle(n+1); 60 | for(int j=n-1;j>=2;j--) 61 | { 62 | partialtriangle(j,offset); 63 | offset++; 64 | } 65 | stand(n); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /General Questions/find_pair_difference.c: -------------------------------------------------------------------------------- 1 | /* 2 | Find a pair difference k using Two Pointer method. 3 | 4 | input 5 | 6 6 | 2 7 10 15 57 246 7 | 47 8 | 9 | output 10 | 10 57 11 | 12 | We need to find the pair of numbers from the array such that their absolute difference is equal 13 | to a particular number k. The time complexity of the algorithm is O(n) compared to the brute force algorithm 14 | that has a time complexity of O(n^2). 15 | */ 16 | #include 17 | #include 18 | int main(int argc, char const *argv[]) 19 | { 20 | int n,l,r,k; 21 | scanf("%d",&n); 22 | int a[n]; 23 | for(int i=0;ik) 33 | l++; 34 | else if(abs(a[l]-a[r]) 22 | using namespace std; 23 | 24 | #define max 100 25 | 26 | void print(int a[][max], int size) 27 | { 28 | for (int i = 0; i < size; i++) { 29 | for (int j = 0; j < size; j++) { 30 | cout << a[i][j]; 31 | } 32 | cout << endl; 33 | } 34 | } 35 | 36 | void innerPattern(int n) { 37 | 38 | int size = 2 * n - 1; 39 | int front = 0; 40 | int back = size - 1; 41 | int a[max][max]; 42 | while (n != 0) 43 | { 44 | for (int i = front; i <= back; i++) { 45 | for (int j = front; j <= back; j++) { 46 | if (i == front || i == back || 47 | j == front || j == back) 48 | a[i][j] = n; 49 | } 50 | } 51 | ++front; 52 | --back; 53 | --n; 54 | } 55 | print(a, size); 56 | } 57 | 58 | int main() 59 | { 60 | int n; 61 | cin>>n; 62 | innerPattern(n); 63 | 64 | return 0; 65 | } 66 | 67 | -------------------------------------------------------------------------------- /General Questions/intersection_of_arrays.c: -------------------------------------------------------------------------------- 1 | /* 2 | Intersection of arrays using Two Pointer method 3 | 4 | input 5 | 3 6 | 10 17 57 7 | 6 8 | 2 7 10 15 57 246 9 | 10 | output 11 | 10 57 12 | 13 | We consider two pointers i,j for travsersing the array only once making the time complexity of the algoirithm 14 | to O(m+n) rather than O(m*n) for a brute force approach where m and n are the array sizes. 15 | */ 16 | #include 17 | int main(int argc, char const *argv[]) 18 | { 19 | int n,m,p=0,q=0; 20 | scanf("%d",&n); 21 | int a[n]; 22 | for(int i=0;ib[q]) 35 | q++; 36 | else if(a[p] 14 | int main(int argc, char const *argv[]) 15 | { 16 | int n,a=2,b=3; 17 | scanf("%d",&n); 18 | for (int i = 1; i <= n; i++) 19 | { 20 | printf("%*s",(n-i)*3,""); 21 | for(int j=1;j<=i;j++) 22 | { 23 | printf("%05d ",a*b); 24 | a = a + 2; 25 | b = b + 4; 26 | } 27 | printf("\n"); 28 | } 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /General Questions/longest_progressive_sequence.c: -------------------------------------------------------------------------------- 1 | /* 2 | Longest Progressive Sequence using Two Pointer method. 3 | 4 | input 5 | 10 6 | 1 1 2 1 2 3 12 13 5 10 7 | 8 | output 9 | 1 2 3 12 13 10 | 11 | We need to find the longest sequence in increasing order in the array. 12 | 13 | */ 14 | #include 15 | int main(int argc, char const *argv[]) 16 | { 17 | int n,start=0,end=0,curlen=1,maxlen=1,maxstart=0,maxend=0; 18 | scanf("%d",&n); 19 | int a[n]; 20 | for(int i=0;i=a[j-1]) 27 | { 28 | end = j; 29 | curlen = end - start + 1; 30 | if(curlen>maxlen) 31 | { 32 | maxlen = curlen; 33 | maxstart = start; 34 | maxend = end; 35 | } 36 | } 37 | else{ 38 | start = j; 39 | end = j; 40 | } 41 | } 42 | // the indices maxstart to maxend indicates the sequence. 43 | for(int i=maxstart;i<=maxend;i++) 44 | { 45 | printf("%d ",a[i]); 46 | } 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /General Questions/merge_sort.c: -------------------------------------------------------------------------------- 1 | /* 2 | Merge Sort 3 | input 4 | 4 5 | 11 22 33 44 6 | 10 20 30 40 7 | 8 | output 9 | 10 11 20 22 30 33 40 44 10 | 11 | We need to print the merged sorted arrays of the individual sorted arrays given. 12 | */ 13 | #include 14 | int main(int argc, char const *argv[]) 15 | { 16 | int n,m,ap=0,bp=0; 17 | scanf("%d",&n); 18 | int a[n]; 19 | for(int i=0;ib[bp]) 32 | { 33 | printf("%d ",b[bp]); 34 | bp++; 35 | } 36 | else if(a[ap] 15 | 16 | int main(){ 17 | int n; 18 | printf("Enter the number of rows:"); 19 | scanf("%d",&n); 20 | 21 | for(int i = 0; i 13 | 14 | int main(){ 15 | int n; 16 | printf("Enter the number of rows:"); 17 | scanf("%d",&n); 18 | 19 | for(int i = 0; i= n){ 22 | printf("*"); 23 | } 24 | else 25 | { 26 | printf(" "); 27 | } 28 | 29 | } 30 | printf("\n"); 31 | } 32 | return 0; 33 | 34 | } 35 | -------------------------------------------------------------------------------- /General Questions/pattern_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PRINT THE FOLLOWING STAR PATTERN : 3 | * 4 | ** 5 | *** 6 | **** 7 | ***** 8 | ****** 9 | ******* 10 | ******** 11 | ''' 12 | 13 | #Taking user input 14 | n = int(input()) 15 | 16 | for i in range(n,0,-1): 17 | print(' '*(i-1),end="") 18 | print('*'*(n-i+1)) 19 | -------------------------------------------------------------------------------- /General Questions/pattern_3.c: -------------------------------------------------------------------------------- 1 | /*PRINT THE FOLLOWING STAR PATTERN : 2 | * 3 | *** 4 | ***** 5 | ******* 6 | ********* 7 | *********** 8 | ************* 9 | *************** 10 | */ 11 | 12 | #include 13 | 14 | int main(){ 15 | int n; 16 | printf("Enter the number of rows:"); 17 | scanf("%d",&n); 18 | 19 | for(int i =0; in-1-i){ 22 | printf("*"); 23 | } 24 | else 25 | { 26 | printf(" "); 27 | } 28 | 29 | } 30 | printf("\n"); 31 | } 32 | return 0; 33 | } -------------------------------------------------------------------------------- /General Questions/pattern_3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PRINT THE FOLLOWING STAR PATTERN : 3 | * 4 | *** 5 | ***** 6 | ******* 7 | ********* 8 | *********** 9 | ************* 10 | *************** 11 | ''' 12 | 13 | #Taking user input 14 | n = int(input()) 15 | 16 | for i in range(n,0,-1): 17 | print(' '*(i-1),end="") 18 | print('*'*(n-(i-1)),end="") 19 | print('*'*(n-i)) -------------------------------------------------------------------------------- /General Questions/pattern_4.c: -------------------------------------------------------------------------------- 1 | /*PRINT THE FOLLOWING STAR PATTERN : 2 | ********* 3 | ******** 4 | ******* 5 | ****** 6 | ***** 7 | **** 8 | *** 9 | ** 10 | * 11 | */ 12 | 13 | #include 14 | 15 | int main(){ 16 | int n; 17 | printf("Enter the number of rows:"); 18 | scanf("%d",&n); 19 | 20 | for(int i =0; i=i){ 23 | printf("*"); 24 | } 25 | else 26 | { 27 | printf(" "); 28 | } 29 | 30 | } 31 | printf("\n"); 32 | } 33 | return 0; 34 | } -------------------------------------------------------------------------------- /General Questions/pattern_4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | PRINT THE FOLLOWING STAR PATTERN : 3 | ********* 4 | ******** 5 | ******* 6 | ****** 7 | ***** 8 | **** 9 | *** 10 | ** 11 | * 12 | ''' 13 | 14 | #Taking user input 15 | n = int(input()) 16 | 17 | for i in range(n,0,-1): 18 | print(' '*(n-i),end="") 19 | print('*'*(i)) -------------------------------------------------------------------------------- /General Questions/pattern_5.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n=9,m=1; 6 | 7 | 8 | for(int i=n;i>=1;i--) 9 | { 10 | for(int j=1;j 2 | #include 3 | 4 | int main(int argc, char const *argv[]) 5 | { 6 | int n; 7 | scanf("%d",&n); 8 | // for first half 9 | for(int i=n;i>=2;i-=2,printf("\n")) 10 | { 11 | printf("%*s",(n-i)/2,""); 12 | for(int j=1;j<=i;j++) 13 | { 14 | printf("*"); 15 | } 16 | } 17 | // for second half 18 | for(int i=2;i<=n;i+=2,printf("\n")) 19 | { 20 | printf("%*s",(n-i)/2,""); 21 | for(int j=1;j<=i;j++) 22 | { 23 | printf("*"); 24 | } 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Arithmatic_operator.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Calculate the area of a rectangle. 3 | * 4 | * length: The length of the rectangle. 5 | * width: The width of the rectangle. 6 | * 7 | * Return a number denoting the rectangle's area. 8 | **/ 9 | function getArea(length, width) { 10 | let area; 11 | // Write your code here 12 | area=length*width 13 | return area; 14 | 15 | } 16 | 17 | /** 18 | * Calculate the perimeter of a rectangle. 19 | * 20 | * length: The length of the rectangle. 21 | * width: The width of the rectangle. 22 | * 23 | * Return a number denoting the perimeter of a rectangle. 24 | **/ 25 | function getPerimeter(length, width) { 26 | let perimeter; 27 | // Write your code here 28 | perimeter=2*(length+width) 29 | return perimeter; 30 | } 31 | 32 | 33 | function main() { 34 | const length = +(readLine()); 35 | const width = +(readLine()); 36 | 37 | console.log(getArea(length, width)); 38 | console.log(getPerimeter(length, width)); 39 | } 40 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Arrays.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | /** 26 | * Return the second largest number in the array. 27 | * @param {Number[]} nums - An array of numbers. 28 | * @return {Number} The second largest number in the array. 29 | **/ 30 | function getSecondLargest(nums) { 31 | // Complete the function 32 | let first=nums[0]; 33 | let second=-1; 34 | for(let i=0;ifirst) 37 | { 38 | second=first; 39 | first=nums[i]; 40 | } 41 | if(nums[i]>second && nums[i] { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | /* 26 | * Modify and return the array so that all even elements are doubled and all odd elements are tripled. 27 | * 28 | * Parameter(s): 29 | * nums: An array of numbers. 30 | */ 31 | function modifyArray(nums) { 32 | var something=function(n){ 33 | if(n%2==0) 34 | return n*2; 35 | else 36 | return n*3; 37 | 38 | } 39 | var newArray=nums.map(something); 40 | return newArray; 41 | } 42 | 43 | 44 | function main() { 45 | const n = +(readLine()); 46 | const a = readLine().split(' ').map(Number); 47 | 48 | console.log(modifyArray(a).toString().split(',').join(' ')); 49 | } 50 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Bitwise_Operators.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | function getMaxLessThanK(n,k) 26 | { 27 | let max=0 28 | for(let i=1;imax) 34 | max=and 35 | } 36 | return max 37 | } 38 | 39 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Classes.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Implement a Polygon class with the following properties: 3 | * 1. A constructor that takes an array of integer side lengths. 4 | * 2. A 'perimeter' method that returns the sum of the Polygon's side lengths. 5 | */ 6 | class Polygon{ 7 | constructor(sides){ 8 | this.sides=sides 9 | } 10 | perimeter(){ 11 | return this.sides.reduce(function add(a,b){ return a+b;}) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Conditional_statement_(if-else).js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | function getGrade(score) { 26 | return 'FEDCBA'[parseInt((score > 0 ? score - 1 : 0) / 5)]; 27 | } 28 | 29 | 30 | 31 | function main() { 32 | const score = +(readLine()); 33 | 34 | console.log(getGrade(score)); 35 | } 36 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Conditional_statement_switch.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | function getLetter(s) { 26 | 27 | switch(s.charAt(0)) 28 | { 29 | case('a'||'e'||'i'||'o'||'u'): 30 | return 'A' 31 | case('b'||'c'||'d'||'f'||'g'): 32 | return 'B' 33 | case('h'||'j'||'k'||'l'||'m'): 34 | return 'C' 35 | case('z'||'n'||'p'||'q'||'r'||'s'||'t'||'v'||'w'||'x'||'y'): 36 | return 'D' 37 | 38 | } 39 | } 40 | 41 | 42 | function main() { 43 | const s = readLine(); 44 | 45 | console.log(getLetter(s)); 46 | } 47 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Create_Rectangle_Object.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | /* 26 | * Complete the Rectangle function 27 | */ 28 | function Rectangle(a,b) { 29 | this.length = a; 30 | this.width = b; 31 | this.perimeter = 2 * (a + b); 32 | this.area = (a * b); 33 | } 34 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Functions.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | /* 25 | * Create the function factorial here 26 | */ 27 | function factorial(n){ 28 | let finalVal=1; 29 | for (let i=n; i>1; i--){ 30 | finalVal *=i; 31 | } 32 | return finalVal; 33 | } 34 | 35 | 36 | function main() { 37 | const n = +(readLine()); 38 | 39 | console.log(factorial(n)); 40 | } 41 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Inheritance.js: -------------------------------------------------------------------------------- 1 | class Rectangle { 2 | constructor(w, h) { 3 | this.w = w; 4 | this.h = h; 5 | } 6 | } 7 | 8 | /* 9 | * Write code that adds an 'area' method to the Rectangle class' prototype 10 | */ 11 | Rectangle.prototype.area= function(){ 12 | return this.w * this.h; 13 | } 14 | /* 15 | * Create a Square class that inherits from Rectangle and implement its class constructor 16 | */ 17 | //inherit from rectangle 18 | class Square extends Rectangle { 19 | //create Square constructor 20 | constructor (a){ 21 | //call constructor from Rectangle class and insert value 22 | super (a,a); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Let_and_const.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | function main() { 26 | // Write your code here. Read input using 'readLine()' and print output using 'console.log()'. 27 | 28 | // Print the area of the circle: 29 | 30 | // Print the perimeter of the circle: 31 | let r = readLine(); 32 | const PI = Math.PI; 33 | 34 | // Print the area of the circle: 35 | console.log(PI*r*r); 36 | // Print the perimeter of the circle: 37 | console.log(PI*2*r); 38 | 39 | try { 40 | // Attempt to redefine the value of constant variable PI 41 | PI = 0; 42 | // Attempt to print the value of PI 43 | console.log(PI); 44 | } catch(error) { 45 | console.error("You correctly declared 'PI' as a constant."); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Loops.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | /* 26 | * Complete the vowelsAndConsonants function. 27 | * Print your output using 'console.log()'. 28 | */ 29 | function vowelsAndConsonants(s) { 30 | //for vowels 31 | for(let ind=0; ind { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | /* 26 | * Complete the isPositive function. 27 | * If 'a' is positive, return "YES". 28 | * If 'a' is 0, throw an Error with the message "Zero Error" 29 | * If 'a' is negative, throw an Error with the message "Negative Error" 30 | */ 31 | function isPositive(a) { 32 | if (a === 0) 33 | throw Error('Zero Error'); 34 | if (a < 0) 35 | throw Error('Negative Error'); 36 | 37 | return 'YES'; 38 | } 39 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/Try_catch_finally.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | /* 26 | * Complete the reverseString function 27 | * Use console.log() to print to stdout. 28 | */ 29 | function reverseString(s) { 30 | 31 | try{ 32 | 33 | console.log(s.split("").reverse().join("")) 34 | } 35 | catch(e){ 36 | console.log(e.message); // Use .message, or you'll get more than expected. 37 | console.log(s); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Hackerrank solutions/10 days of js/javascript_dates.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | process.stdin.resume(); 4 | process.stdin.setEncoding('utf-8'); 5 | 6 | let inputString = ''; 7 | let currentLine = 0; 8 | 9 | process.stdin.on('data', inputStdin => { 10 | inputString += inputStdin; 11 | }); 12 | 13 | process.stdin.on('end', _ => { 14 | inputString = inputString.trim().split('\n').map(string => { 15 | return string.trim(); 16 | }); 17 | 18 | main(); 19 | }); 20 | 21 | function readLine() { 22 | return inputString[currentLine++]; 23 | } 24 | 25 | // The days of the week are: "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" 26 | function getDayName(dateString) { 27 | const date = new Date(dateString); 28 | 29 | const options = { 30 | weekday: 'long' 31 | }; 32 | 33 | return new Intl.DateTimeFormat('en-Us', options).format(date); 34 | } 35 | 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Vaidhyanathan S M 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Numbers/Basic_Programs/abundant_num.c: -------------------------------------------------------------------------------- 1 | // C program to check whether a number is an abundant number or not // 2 | 3 | #include 4 | int main() 5 | { 6 | int num; 7 | int temp; 8 | scanf("%d",&num); 9 | int sum = 0; 10 | for(int i = 1; i < num; i++) 11 | { 12 | if(num % i == 0) 13 | { 14 | sum = sum + i; 15 | } 16 | } 17 | if(num < sum) 18 | printf("Abundant Number"); 19 | else 20 | printf("Not Abundant Number"); 21 | return 0; 22 | } 23 | 24 | -------------------------------------------------------------------------------- /Numbers/Basic_Programs/armstrong_number.c: -------------------------------------------------------------------------------- 1 | /* Program to check whether the given number is Armstrong or not is discussed here. A number is an Armstrong number when the sum of nth power of 2 | each digit is equal to the number itself. */ 3 | 4 | // C program to check whether the given number is Armstrong or not 5 | 6 | #include 7 | 8 | int main() 9 | { 10 | int number, temp, remainder, result = 0, n = 0; 11 | 12 | printf("Enter an integer: "); 13 | scanf("%d", &number); 14 | 15 | temp = number; 16 | 17 | // Finding the number of digits 18 | 19 | while (temp != 0) 20 | { 21 | temp /= 10; 22 | ++n; 23 | } 24 | 25 | temp = number; 26 | 27 | // Checking if the number is armstrong 28 | 29 | while (temp != 0) 30 | { 31 | remainder = temp % 10; 32 | result += pow(remainder, n); 33 | temp /= 10; 34 | } 35 | 36 | if (result == number) 37 | printf("%d is an Armstrong number\n", number); 38 | else 39 | printf("%d is not an Armstrong number\n", number); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Numbers/Basic_Programs/leap_year.c: -------------------------------------------------------------------------------- 1 | /* Write a c program, to check whether the given year is a leap year or not. A leap year is a calendar year containing one additional day (Feb 29th) 2 | added to keep the calendar year synchronized with the astronomical year.*/ 3 | 4 | #include 5 | 6 | int main() 7 | { 8 | int year; 9 | printf("Enter a year: "); 10 | scanf("% d", &year); 11 | printf("\n"); 12 | if (year % 4 == 0) 13 | { 14 | if (year % 100 == 0) 15 | { 16 | if (year % 400 == 0) 17 | printf("% d is a leap year", year); 18 | else 19 | printf("% d is not a leap year", year); 20 | } 21 | else 22 | printf("% d is a leap year", year); 23 | } 24 | else 25 | printf("% d is not a leap year", year); 26 | printf("\n"); 27 | return 0; 28 | } 29 | 30 | /* Output 31 | Input- Enter a year:2004 Output- 2004 is a leap year 32 | */ 33 | -------------------------------------------------------------------------------- /Numbers/Basic_Programs/palindrome_num.c: -------------------------------------------------------------------------------- 1 | /* Palindrome or not using iterative approach */ 2 | 3 | #include 4 | int main() 5 | { 6 | int n, reverse = 0, remainder, number; 7 | 8 | printf("Enter an integer: "); 9 | scanf("%d", &n); 10 | 11 | number = n; 12 | 13 | while( n!=0 ) 14 | { 15 | remainder = n%10; 16 | reverse = reverse*10 + remainder; 17 | n /= 10; 18 | } 19 | 20 | if (number == reverse) 21 | printf("\n%d is a palindrome\n", number); 22 | else 23 | printf("\n%d is not a palindrome\n", number); 24 | 25 | return 0; 26 | } 27 | 28 | /* Input- Enter an integer:1234321 29 | Output- 1234321 is a palindrome 30 | */ -------------------------------------------------------------------------------- /Numbers/Basic_Programs/perfect_num.c: -------------------------------------------------------------------------------- 1 | // C program to check whether the given number is a perfect number or not 2 | 3 | #include 4 | 5 | int main() 6 | { 7 | int i, num, sum = 0; 8 | 9 | printf("\nEnter a number : "); 10 | scanf("%d", &num); 11 | 12 | for(i=1; i 4 | int main() 5 | { 6 | int n, i; 7 | printf("\nEnter the number : "); 8 | scanf("%d", &n); 9 | for (i = 2; i <= n / 2; i++) 10 | { 11 | if (n % i == 0) 12 | { 13 | break; 14 | } 15 | } 16 | if (i > n / 2) 17 | printf("\n%d is a Prime Number\n", n); 18 | else 19 | printf("\n%d is not a Prime Number\n", n); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /Numbers/Basic_Programs/prime_number_using_recursion.c: -------------------------------------------------------------------------------- 1 | #include 2 | int is_prime_number(int num, int i) 3 | { 4 | if (num < 2) 5 | { 6 | printf("\nEnter numbers greater than 1\n"); 7 | exit(0); 8 | } 9 | if (i == 1) 10 | { 11 | return 1; 12 | } 13 | else 14 | { 15 | if (num % i == 0) 16 | { 17 | return 0; 18 | } 19 | else 20 | { 21 | return is_prime_number(num, i - 1); 22 | } 23 | } 24 | } 25 | int main() 26 | { 27 | int n, flag; 28 | printf("Enter a number: "); 29 | scanf("%d", &n); 30 | flag = is_prime_number(n, n / 2); 31 | if (flag == 1) 32 | { 33 | printf("\n%d is a prime number\n", n); 34 | } 35 | else 36 | { 37 | printf("\n%d is not a prime number\n", n); 38 | } 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Numbers/Basic_Programs/reverse_num.c: -------------------------------------------------------------------------------- 1 | // C program to reverse a number 2 | 3 | #include 4 | int main() 5 | { 6 | int n, rev = 0, rem; 7 | printf("\nEnter a number : "); 8 | scanf("%d", &n); 9 | printf("\nReversed Number : "); 10 | while(n != 0) 11 | { 12 | rem = n%10; 13 | rev = rev*10 + rem; 14 | n /= 10; 15 | } 16 | 17 | printf("%d\n", rev); 18 | 19 | return 0; 20 | } 21 | 22 | /* Enter a number : 12345 23 | Reversed Number : 54321 24 | */ -------------------------------------------------------------------------------- /Numbers/Basic_Programs/strong_num.c: -------------------------------------------------------------------------------- 1 | /* Program to check if a given number is a strong number or not */ 2 | 3 | #include 4 | 5 | int main() 6 | { 7 | int n,i; 8 | int fact,rem; 9 | printf("\nEnter a number : "); 10 | scanf("%d",&n); 11 | printf("\n"); 12 | int sum = 0; 13 | int temp = n; 14 | while(n) 15 | { 16 | i = 1,fact = 1; 17 | rem = n % 10; 18 | 19 | while(i <= rem) 20 | { 21 | fact = fact * i; 22 | i++; 23 | } 24 | sum = sum + fact; 25 | n = n / 10; 26 | } 27 | if(sum == temp) 28 | printf("%d is a strong number\n",temp); 29 | else 30 | printf("%d is not a strong number\n",temp); 31 | 32 | return 0; 33 | } 34 | 35 | /* Input-Enter a number:145 36 | Output-145 is a strong number 37 | */ -------------------------------------------------------------------------------- /Numbers/BinarytoDecimal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main(){ 4 | int n; 5 | cout<<"Enter number-->"; 6 | cin>>n; 7 | int temp=n,dec=0,base=1,t=1; 8 | while(temp){ 9 | t=temp%10; 10 | dec=dec+t*base; 11 | base=base*2; 12 | temp/=10; 13 | } 14 | cout<<"The binary number "< 15 | #include 16 | 17 | int main(int argc, char const *argv[]) 18 | { 19 | int n,m,res; 20 | scanf("%d %d",&n,&m); 21 | 22 | int p = n/m; 23 | 24 | int first = m * p; 25 | 26 | int next = (n*m) > 0 ? (m*(p+1)) : (m*(p-1)); 27 | 28 | if(abs(n-first) 2 | 3 | using namespace std; 4 | int main(int argc, char const *argv[]) 5 | { 6 | int n; 7 | string s; 8 | cin>>n; 9 | while(true) 10 | { 11 | s += to_string(n%2); 12 | if(n==1) break; 13 | n = n / 2; 14 | } 15 | reverse(s.begin(),s.end()); 16 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char const *argv[]) 7 | { 8 | int n; 9 | cin>>n; 10 | // since the divisors occur in pairs, it is enough to traverse till sqrt(n) 11 | for(int i=1;i<=sqrt(n);i++) 12 | { 13 | if(n%i==0) // check the divisibility 14 | { 15 | if(n/i==i) // if same number appears in the pair, for example for n =100, the number 10 occurs twice. It is enough to print 16 | // it once 17 | cout< 14 | #include 15 | 16 | using namespace std; 17 | 18 | void bfs(int x, int num) 19 | { 20 | queue q; 21 | q.push(num); 22 | 23 | while (!q.empty()) { 24 | num = q.front(); 25 | q.pop(); 26 | 27 | if (num <= x) { 28 | cout << num << " "; 29 | int last_dig = num % 10; 30 | 31 | if (last_dig == 0) 32 | q.push((num * 10) + (last_dig + 1)); 33 | 34 | else if (last_dig == 9) 35 | q.push((num * 10) + (last_dig - 1)); 36 | 37 | else { 38 | q.push((num * 10) + (last_dig - 1)); 39 | q.push((num * 10) + (last_dig + 1)); 40 | } 41 | } 42 | } 43 | } 44 | 45 | int main() 46 | { 47 | int x; 48 | cin>>x; 49 | cout << 0 << " "; 50 | for (int i = 1; i <= 9 && i <= x; i++) 51 | bfs(x, i); 52 | return 0; 53 | } -------------------------------------------------------------------------------- /Numbers/LargerNumber.cpp: -------------------------------------------------------------------------------- 1 | 2 | /* 3 | Find the larger number n greater than n2 that is divisible by n1. 4 | For eg: 5 | 4 7 6 | output: 8 7 | since 8 is the nearest larger number than 7 and it is divisible by 4. 8 | */ 9 | #include 10 | 11 | using namespace std; 12 | 13 | int main(int argc, char const *argv[]) 14 | { 15 | int n1,n2; 16 | cin>>n1>>n2; 17 | cout<<((n2/n1)+1)*n1; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /Numbers/LargerNumber.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Find the larger number n greater than n2 that is divisible by n1. 3 | For eg: 4 | 4 7 5 | output: 8 6 | since 8 is the nearest larger number than 7 and it is divisible by 4. 7 | ''' 8 | 9 | 10 | mn=input().split() 11 | 12 | m=int(mn[0]) 13 | n=int(mn[1]) 14 | 15 | print(((n//m)+1)*m) -------------------------------------------------------------------------------- /Numbers/NumberofBinDigits.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | // Find the number of binary digits in binary representation of a positive decimal number. 4 | class NumberofBinDigits { 5 | 6 | public static void main(String[] args) { 7 | int n,count=0; 8 | Scanner sc = new Scanner(System.in); 9 | 10 | n = sc.nextInt(); 11 | 12 | while(n>0) 13 | { 14 | count+=1; 15 | n = n/2; 16 | } 17 | 18 | System.out.println(count); 19 | sc.close(); 20 | } 21 | } -------------------------------------------------------------------------------- /Numbers/PerfectNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char const *argv[]) 7 | { 8 | int n,sum=0; 9 | cin>>n; 10 | 11 | for(int i=1;i=index2: 22 | total=total+index1 23 | i=i+1 24 | else: 25 | total=total-index1 26 | i=i+1 27 | 28 | else: 29 | total=total+index1 30 | i=i+1 31 | return total 32 | 33 | print("Enter the Roman Numeral") 34 | s=input() 35 | st=romanToInt(s) 36 | print("The roman to integer of the given input is: ",st) 37 | -------------------------------------------------------------------------------- /Numbers/Unique_Digits_Count.cpp: -------------------------------------------------------------------------------- 1 | /*Write a program to find the count of numbers which consists of unique digits. 2 | 3 | Input: 4 | 5 | Input consist of two Integer lower and upper value of an range 6 | 7 | 8 | Output: 9 | 10 | Output consists of single line, print the count of unique digits in given range. Else Print"No Unique Number" 11 | 12 | 13 | Solution: 14 | 15 | 16 | Input - 17 | 18 | 10 19 | 20 | 15 21 | 22 | Output: 23 | 5 24 | */ 25 | #include 26 | 27 | using namespace std; 28 | 29 | int printUniqueCount(int l, int r) 30 | { 31 | set st; 32 | int dupFound, count=0, num; 33 | for(int i=l;i<=r;i++) 34 | { 35 | dupFound = 0; 36 | num = i; 37 | while(num) 38 | { 39 | if(st.find(num%10) != st.end()) 40 | dupFound=1; 41 | else st.insert(num%10); 42 | num = num / 10; 43 | } 44 | if(dupFound!=1) 45 | count++; 46 | st.clear(); 47 | } 48 | return count; 49 | } 50 | 51 | int main() 52 | { 53 | int l,r; 54 | cin>>l>>r; 55 | cout< 9 | using namespace std; 10 | 11 | // Function to check whether the Number is Armstrong Number or Not. 12 | 13 | bool is_armstrong(int n) { 14 | if (n < 0) { 15 | return false; 16 | } 17 | int sum = 0; 18 | int var = n; 19 | int number_of_digits = floor(log10(n) + 1); 20 | while (var > 0) { 21 | int rem = var % 10; 22 | sum = sum + pow(rem, number_of_digits); 23 | var = var / 10; 24 | } 25 | return n == sum; 26 | } 27 | 28 | int main() { 29 | cout << "Enter the Number to check whether it is Armstrong Number or Not:" << endl; 30 | int n; 31 | cin >> n; 32 | if (is_armstrong(n)) 33 | cout << n << " is Armstrong Number." << endl; 34 | else 35 | cout << n << " is Not Armstrong Number." << endl; 36 | return 0; 37 | } 38 | 39 | /* 40 | Time Complexity: O(log(n)) 41 | Space Complexity: O(1) 42 | */ 43 | -------------------------------------------------------------------------------- /Numbers/factorial_of_a_number.c: -------------------------------------------------------------------------------- 1 | /* Program to find the factorial of a number using functions*/ 2 | 3 | #include 4 | int factorial_of_a_number(int n) 5 | { 6 | int fact = 1, i; 7 | if (n == 0) 8 | return 1; 9 | else 10 | for (i = 1; i <= n; i++) 11 | { 12 | fact = fact * i; 13 | } 14 | return fact; 15 | } 16 | int main() 17 | { 18 | int n; 19 | printf("Enter the number : "); 20 | scanf("%d", &n); 21 | if (n < 0) 22 | printf("Invalid output"); 23 | else 24 | printf("Factorial of the number %d is %d", n, factorial_of_a_number(n)); 25 | return 0; 26 | } 27 | 28 | /*Input- Enter the number:5 29 | Output- Factorial of the number 5 is 120 30 | */ 31 | -------------------------------------------------------------------------------- /Numbers/factorial_of_a_number.py: -------------------------------------------------------------------------------- 1 | '''Program to find the factorial of a number using recursion''' 2 | 3 | #Taking number from user and finding its factorial using loop 4 | n = int(input()) 5 | fact=1 6 | for i in range(1,n+1): 7 | fact*=i 8 | 9 | print(fact) -------------------------------------------------------------------------------- /Numbers/factorial_of_a_number_recursion.c: -------------------------------------------------------------------------------- 1 | /*Program to find the factorial of a number using recursion*/ 2 | 3 | #include 4 | int factorial_of_a_number(int n) 5 | { 6 | if (n == 0) 7 | return 1; 8 | else 9 | return (n * factorial_of_a_number(n - 1)); 10 | } 11 | int main() 12 | { 13 | int n; 14 | printf("Enter the number : "); 15 | scanf("%d", &n); 16 | if (n < 0) 17 | printf("Invalid input"); 18 | else 19 | printf("Factorial of the number %d is %d", n, factorial_of_a_number(n)); 20 | return 0; 21 | } 22 | 23 | /*Input- Enter the number:5 24 | Output- Factorial of the number 5 is 120 25 | */ 26 | -------------------------------------------------------------------------------- /Numbers/factorial_of_a_number_recursion.py: -------------------------------------------------------------------------------- 1 | '''Program to find the factorial of a number using recursion''' 2 | 3 | def factorial_of_a_number(n): 4 | if n<=1: 5 | return 1 6 | else: 7 | return n * factorial_of_a_number(n-1) 8 | 9 | #Taking number from user and passing it to the function 10 | 11 | n = int(input()) 12 | print(factorial_of_a_number(n)) -------------------------------------------------------------------------------- /Numbers/fibonacci_series.c: -------------------------------------------------------------------------------- 1 | // C program to generate fibonacci series upto n value 2 | 3 | #include 4 | int main() 5 | { 6 | int sum = 0, n; 7 | int a = 0; 8 | int b = 1; 9 | printf("Enter the nth value: "); 10 | scanf("%d", &n); 11 | printf("Fibonacci series: "); 12 | while (sum <= n) 13 | { 14 | printf("%d ", sum); 15 | a = b; // swap elements 16 | b = sum; 17 | sum = a + b; // next term is the sum of the last two terms 18 | } 19 | return 0; 20 | } 21 | 22 | /* 23 | Output 24 | Input- Enter the nth value: 1000 25 | Output- Fibonacci series: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 26 | */ 27 | -------------------------------------------------------------------------------- /Numbers/fibonacci_series.py: -------------------------------------------------------------------------------- 1 | '''Fibonacci series upto n value''' 2 | 3 | # taking user input-1 4 | n = int(input()) 5 | 6 | a=0 7 | b=1 8 | 9 | if(a<=n): 10 | print(a," ",end="") 11 | if(b<=n): 12 | print(b," ",end="") 13 | c=a+b 14 | while(c<=n): 15 | print(c," ",end="") 16 | a=b 17 | b=c 18 | c=a+b 19 | else: 20 | print("None of the values in fibonacci series are less than",n) -------------------------------------------------------------------------------- /Numbers/lucky_number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | A number is considered lucky if it contains either 3 or 4 or 3 and 4 both in it. Write a program 3 | to print the nth lucky number. First few numbers in the number system are: 3, 4, 33, 34, 43, 44, 4 | 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444, … 5 | 6 | Input 7 | 3 8 | 9 | Output 10 | 33 11 | 12 | */ 13 | #include 14 | using namespace std; 15 | void find(int n) 16 | { 17 | string arr[n+1]; 18 | arr[0] = ""; 19 | 20 | int size = 1, m = 1; 21 | 22 | while (size <= n) 23 | { 24 | 25 | for (int i=0; i>n; 41 | find(n); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Numbers/num to words step 2 as a function.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | // AND 5 | // 11 - 19 6 | // 10, 20,30,40,50,60,70,80,90 7 | // rest are combinations 8 | 9 | void twoDigit_words(int num, char res[]); 10 | int main() 11 | { 12 | 13 | char res[200]; 14 | twoDigit_words(18, res); 15 | printf("%s", res); 16 | 17 | return 0; 18 | } 19 | 20 | void twoDigit_words( int num, char res[]) 21 | { 22 | char unit_words [ 10 ] [ 6 ] = {"ZERO","ONE","TWO","THREE","FOUR","FIVE","SIX",\ 23 | "SEVEN","EIGHT","NINE" }; 24 | char tens_words [ 10] [10] = { "", "TEN", "TWENTY ", "THIRTY ","FOURTY ","FIFTY ","SIXTY "\ 25 | ,"SEVENTY ", "EIGHTY ","NINETY "}; 26 | char eleven_nineteen [10] [ 20] = { "", "ELEVEN","TWELVE","THIRTEEN","FOURTEEN",\ 27 | "FIFTEEN","SIXTEEN","SEVENTEEN","EIGHTEEN","NINETEEN"}; 28 | int N, ud, td; 29 | char num_in_words[100]=""; 30 | // scanf("%d", &N); 31 | // for( N= 0; N < 100; N++, num_in_words[0]='\0') 32 | N = num; 33 | { 34 | 35 | ud = N % 10; 36 | td = N / 10; 37 | if(N < 10) 38 | strcpy(num_in_words , unit_words [ N ]); 39 | else if ( N > 10 && N < 20) 40 | strcpy(num_in_words, eleven_nineteen [ ud ]); 41 | else{ 42 | 43 | strcpy(num_in_words, tens_words [ td]); 44 | if(ud > 0) 45 | strcat(num_in_words, unit_words[ud]); 46 | } 47 | 48 | strcpy(res, num_in_words); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Numbers/powers_of_two.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Write a Program to find the minimum number of powers (sum of all those numbers) that are 3 | required to form the given input number and print those numbers. 4 | 5 | */ 6 | #include 7 | #include 8 | using namespace std; 9 | int main(int argc, char const *argv[]) 10 | { 11 | int n = 20,count=0,flag=0; 12 | int powers[n],res=0,j,k; 13 | for(int i=1;i<=10;i++) 14 | { 15 | powers[count++]= pow(2,i); 16 | } 17 | for(j=0;j 0) 20 | { 21 | r = num % 10; 22 | if(r == 0) 23 | { 24 | flag = false; 25 | break; 26 | } 27 | if(k % r != 0) 28 | flag = false; 29 | num /= 10; 30 | } 31 | return flag; 32 | } 33 | vector selfDividingNumbers(int left, int right) { 34 | vector res; 35 | cout << isSelfDividing(21); 36 | for(int num = left ; num <= right ; num++) 37 | { 38 | if(isSelfDividing(num)) 39 | res.push_back(num); 40 | } 41 | return res; 42 | } 43 | }; -------------------------------------------------------------------------------- /OOPs/Polymorphism/operator_overloading.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Complex 6 | { 7 | int real, imag; 8 | 9 | public: 10 | Complex(int r = 0, int i = 0) 11 | { 12 | real = r; 13 | imag = i; 14 | } 15 | Complex operator+(Complex &obj) 16 | { 17 | Complex res; 18 | res.real = real + obj.real; 19 | res.imag = imag + obj.imag; 20 | 21 | return res; 22 | } 23 | void print() 24 | { 25 | cout << real << " + i" << imag; 26 | } 27 | }; 28 | 29 | int main() 30 | { 31 | Complex c1(3, 4), c2(4, 3); 32 | Complex c3 = c1 + c2; 33 | c3.print(); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Searching Algorithms/binary_search.c: -------------------------------------------------------------------------------- 1 | /* 2 | Binary Search 3 | 4 | input 5 | 5 6 | 1 2 3 4 5 7 | 3 8 | 9 | output 10 | 2 11 | 12 | For binary search algorithm to work, the array should be in a sorted order. This search algorithm returns 13 | the index of the element that is found. If the element is not found it returns -1. 14 | 15 | */ 16 | #include 17 | 18 | int binarySearch(int a[],int n,int k) 19 | { 20 | int first = 0; 21 | int last = n-1; 22 | while(first <= last) 23 | { 24 | int mid = (first + last)/2; 25 | if(a[mid]>k) 26 | last = mid -1; 27 | else if(a[mid] k) last = mid - 1; 14 | else if (arr[mid] < k) first = mid + 1; 15 | } 16 | return -1; 17 | } 18 | -------------------------------------------------------------------------------- /Searching Algorithms/jump_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int JumpSearch(int arr[],int x,int n){ 4 | int step = sqrt(n); 5 | int prev=0; 6 | 7 | while (arr[min(step,n)-1]=n) 12 | return -1; 13 | } 14 | 15 | while(arr[prev]>n; 33 | int arr[n]; 34 | cout<<"Enter elements: "<<"\n"; 35 | for(int i=0;i>arr[i]; 37 | } 38 | int r; 39 | cout<<"Enter element to search: "; 40 | cin>>r; 41 | int index = JumpSearch(arr,r,n); 42 | cout<<"Number "< 2 | 3 | using namespace std; 4 | 5 | int linearSearch(int arr[], int N, int k); 6 | 7 | int main(int argc, char const *argv[]) 8 | { 9 | int N, k; 10 | cin >> N; 11 | int arr[N], index; 12 | for (index = 0; index < N; index++) 13 | { 14 | cin >> arr[index]; 15 | } 16 | // key element to be searched 17 | cin >> k; 18 | int res = linearSearch(arr, N, k); 19 | if (res != -1) 20 | cout << "Element found at position:" << res; 21 | else 22 | cout << "Element Not Found!"; 23 | return 0; 24 | } 25 | 26 | int linearSearch(int arr[], int N, int k) 27 | { 28 | for (int index = 0; index < N; index++) 29 | { 30 | if (arr[index] == k) 31 | return index; 32 | } 33 | return -1; 34 | } -------------------------------------------------------------------------------- /Searching Algorithms/linear_search.js: -------------------------------------------------------------------------------- 1 | var n = 5, 2 | k = 5; 3 | var arr = [1, 2, 3, 4, 5]; 4 | 5 | console.log(linearSearch(arr, n, k)); 6 | 7 | function linearSearch(arr, n, k) { 8 | for (var index = 0; index < n; index++) { 9 | if (arr[index] == k) return index; 10 | } 11 | return -1; 12 | } 13 | -------------------------------------------------------------------------------- /Sorting Algorithms/Bucket Sort.py: -------------------------------------------------------------------------------- 1 | def insertionSort(b): 2 | for i in range(1, len(b)): 3 | up = b[i] 4 | j = i - 1 5 | while j >= 0 and b[j] > up: 6 | b[j + 1] = b[j] 7 | j -= 1 8 | b[j + 1] = up 9 | return b 10 | 11 | def bucketSort(x): 12 | arr = [] 13 | slot_num = 10 # 10 means 10 slots, each 14 | # slot's size is 0.1 15 | for i in range(slot_num): 16 | arr.append([]) 17 | 18 | # Put array elements in different buckets 19 | for j in x: 20 | index_b = int(slot_num * j) 21 | arr[index_b].append(j) 22 | 23 | # Sort individual buckets 24 | for i in range(slot_num): 25 | arr[i] = insertionSort(arr[i]) 26 | 27 | # concatenate the result 28 | k = 0 29 | for i in range(slot_num): 30 | for j in range(len(arr[i])): 31 | x[k] = arr[i][j] 32 | k += 1 33 | return x 34 | 35 | # Driver Code 36 | x = [0.897, 0.565, 0.656, 37 | 0.1234, 0.665, 0.3434] 38 | print("Sorted Array is") 39 | print(bucketSort(x)) -------------------------------------------------------------------------------- /Sorting Algorithms/bubble_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, the elements of the array are to be arranged in an increasing order. 3 | 4 | Algorithm: 5 | 1. Traverse the array, compare each element with the adjacent element, 6 | 2. swap them if(cur_element > next_element) else continue the traversal 7 | 3. Repeat the above step till the array is completely sorted. 8 | 9 | Input: 10 | 5 1 4 2 3 11 | 12 | Output: 13 | 1 2 3 4 5 14 | 15 | */ 16 | 17 | #include 18 | 19 | using namespace std; 20 | 21 | void bubbleSort(int arr[], int size) 22 | { 23 | int temp; 24 | for(int i=0;iarr[j+1]) 29 | { 30 | temp = arr[j]; 31 | arr[j] = arr[j+1]; 32 | arr[j+1] = temp; 33 | } 34 | } 35 | } 36 | } 37 | 38 | int main(int argc, char const *argv[]) 39 | { 40 | int arr[] = {5, 1, 4, 2, 3}; 41 | 42 | int size; 43 | 44 | size = sizeof(arr)/sizeof(arr[0]); 45 | bubbleSort(arr,size); 46 | 47 | for(int ind=0;ind arr[j + 1] : 16 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 17 | 18 | arr = [] 19 | n=int(input("Enter size of array: ")) 20 | for i in range(n): 21 | e=int(input()) 22 | arr.append(e) 23 | bubbleSort(arr) 24 | print ("Sorted array is:") 25 | for i in range(len(arr)): 26 | print(arr[i]) 27 | 28 | #Time complexity - O(n^2) 29 | #Space complexity - O(1) 30 | -------------------------------------------------------------------------------- /Sorting Algorithms/counting_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | void countingSort(int arr[], int n) 7 | { 8 | int k = *max_element(arr, arr + n); 9 | int countArr[k + 1]; 10 | int sortedArr[n]; 11 | for (int i = 0; i < k + 1; i++) 12 | countArr[i] = 0; 13 | for (int i = 0; i < n; i++) 14 | countArr[arr[i]]++; 15 | for (int i = 1; i <= k; i++) 16 | countArr[i] = countArr[i] + countArr[i - 1]; 17 | for (int i = n - 1; i >= 0; i--) 18 | sortedArr[--countArr[arr[i]]] = arr[i]; 19 | for (int i = 0; i < n; i++) 20 | arr[i] = sortedArr[i]; 21 | } 22 | 23 | //Print the sorted array 24 | void printSortedArray(int arr[], int n) 25 | { 26 | for (int i = 0; i < n; i++) 27 | { 28 | cout << arr[i] << endl; 29 | } 30 | } 31 | int main() 32 | { 33 | int arr[] = {9, 3, 7, 5, 6, 4, 8, 2, 9, 0, 1, 1, 6, 12, 9}; // Unsorted Array 34 | int arr_size = sizeof(arr) / sizeof(arr[0]); //Getting array size 35 | countingSort(arr, arr_size); // Send the array to countingSort 36 | printSortedArray(arr, arr_size); // Print the sorted array 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /Sorting Algorithms/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given an array, the elements of the array needs to be arranged in an increasing order. 3 | 4 | Algorithm: 5 | 1. Traverse the array and keep track of the element to be inserted at each stage. 6 | 2. Store the element to be inserted in a varible. 7 | 3. Shift the elements accordingly to make the array sorted. 8 | 9 | Input: 10 | 5 3 2 4 1 11 | Output: 12 | 1 2 3 4 5 13 | 14 | */ 15 | 16 | #include 17 | 18 | using namespace std; 19 | 20 | int main(int argc, char const *argv[]) 21 | { 22 | int arr[] = {10, 20 ,30 , 40, 50, 60, 70, 80, 24, 44, 90}; 23 | 24 | int size,safe,poi,shift; 25 | 26 | size = sizeof(arr)/sizeof(arr[0]); 27 | 28 | for(int addon = 1; addonarr[poi];poi++); 32 | 33 | safe = arr[addon]; 34 | 35 | for(shift=addon-1; shift>=poi; shift--) 36 | { 37 | arr[shift+1] = arr[shift]; 38 | } 39 | 40 | arr[poi] = safe; 41 | 42 | } 43 | for(int ind=0;ind= 0 and temp < alist[j]): 14 | alist[j+1] = alist[j] 15 | j -= 1 16 | alist[j+1] = temp 17 | 18 | 19 | #{ 20 | # Driver Code Starts 21 | if __name__=="__main__": 22 | t=int(input()) 23 | for i in range(t): 24 | n=int(input()) 25 | arr=list(map(int,input().split())) 26 | 27 | Solution().insertionSort(arr,n) 28 | 29 | for i in range(n): 30 | print(arr[i],end=" ") 31 | 32 | print() 33 | # } Driver Code Ends -------------------------------------------------------------------------------- /Sorting Algorithms/quick_sort.py: -------------------------------------------------------------------------------- 1 | # function to find the partition position 2 | 3 | def partition(array, low, high): 4 | pivot = array[high] #pivot element 5 | 6 | #index of smaller element 7 | i = low - 1 8 | 9 | # traverse through all elements 10 | # compare each element with pivot 11 | for j in range(low, high): 12 | if array[j] <= pivot: 13 | # if current element smaller than pivot is found 14 | #increment index of smaller element 15 | i = i + 1 16 | 17 | # swapping element at i with element at j 18 | (array[i], array[j]) = (array[j], array[i]) 19 | 20 | # swap the pivot element with the greater element specified by i 21 | (array[i + 1], array[high]) = (array[high], array[i + 1]) 22 | 23 | # return the position from where partition is done 24 | return i + 1 25 | 26 | # quicksort function 27 | def quickSort(array, low, high): 28 | if low < high: 29 | #pi is partitioning index 30 | pi = partition(array, low, high) 31 | 32 | # Separately sort elements before partition and after partition 33 | quickSort(array, low, pi - 1) 34 | quickSort(array, pi + 1, high) 35 | 36 | 37 | size= int(input("Enter number of elements ")) 38 | data=list(map(int,input("\nEnter the numbers: ").strip().split()))[:size] 39 | print("Unsorted Array") 40 | print(data) 41 | quickSort(data, 0, size - 1) 42 | print('Sorted Array in Ascending Order:') 43 | print(data) 44 | -------------------------------------------------------------------------------- /Sorting Algorithms/radix_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | void countingSort(int arr[],int n,int pos){ 6 | int countArr[10]; 7 | int sortedArr[n]; 8 | for(int i = 0 ; i < 10 ; i++) 9 | countArr[i] = 0; 10 | for(int i = 0 ; i < n ; i++) 11 | countArr[(arr[i]/pos)%10]++; 12 | for(int i = 1 ; i < n ; i++) 13 | countArr[i] = countArr[i] + countArr[i-1]; 14 | for(int i = n - 1 ; i >= 0 ; i--) 15 | sortedArr[--countArr[(arr[i]/pos)%10]] = arr[i]; 16 | for(int i = 0 ; i < n ; i++) 17 | arr[i] = sortedArr[i]; 18 | } 19 | 20 | void radixSort(int arr[],int n){ 21 | 22 | int maxElement = *max_element(arr, arr + n); 23 | for(int pos = 1 ; maxElement/pos > 0 ; pos*=10){ 24 | countingSort(arr,n,pos); 25 | } 26 | 27 | } 28 | 29 | //Print the sorted array 30 | void printSortedArray(int arr[],int n){ 31 | for(int i=0;i 2 | 3 | using namespace std; 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | void selectionSort(int arr[], int n) 13 | { 14 | int i, j, min_index; 15 | 16 | for (i = 0; i < n - 1; i++) 17 | { 18 | // Find the minimum element in unsorted array 19 | min_index = i; 20 | for (j = i + 1; j < n; j++) 21 | if (arr[j] < arr[min_index]) 22 | min_index = j; 23 | 24 | // Swap the minimum element found with the first element 25 | swap(&arr[min_index], &arr[i]); 26 | } 27 | } 28 | 29 | int main(int argc, char const *argv[]) 30 | { 31 | int N; 32 | cin >> N; 33 | int arr[N], index; 34 | for (index = 0; index < N; index++) 35 | { 36 | cin >> arr[index]; 37 | } 38 | selectionSort(arr, N); 39 | // printing the array elements 40 | for (index = 0; index < N; index++) 41 | { 42 | cout << arr[index] << " "; 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Sorting Algorithms/selection_sort.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | def select(self, arr, i): 4 | 5 | minimum = i 6 | j = i + 1 7 | for j in range(j , n): 8 | if(arr[j] < arr[minimum]): 9 | minimum = j 10 | return minimum 11 | 12 | 13 | def selectionSort(self, arr,n): 14 | 15 | for i in range(0 , n): 16 | minimum = self.select(arr , i) 17 | if(minimum != i): 18 | arr[i] , arr[minimum] = arr[minimum] , arr[i] 19 | 20 | 21 | #{ 22 | # Driver Code Starts 23 | 24 | 25 | if __name__ == '__main__': 26 | t = int(input()) 27 | for _ in range(t): 28 | n = int(input()) 29 | arr = list(map(int, input().strip().split())) 30 | Solution().selectionSort(arr, n) 31 | for i in range(n): 32 | print(arr[i],end=" ") 33 | print() 34 | # } Driver Code Ends -------------------------------------------------------------------------------- /Sorting Algorithms/shell_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void display(int *array,int size){ 5 | for(int i=0;i0;gap=gap/2){ 21 | for(j=gap;j=0;k-=gap){ 23 | if(arr[k+gap]>=arr[k]) 24 | break; 25 | else 26 | swapping(arr[k+gap],arr[k]); 27 | } 28 | } 29 | 30 | } 31 | 32 | } 33 | 34 | int main(){ 35 | int n; 36 | cout<<"Enter the number of elements: "; 37 | cin>>n; 38 | int arr[n]; 39 | cout<<"Enter elements: "<<"\n"; 40 | for(int i=0;i>arr[i]; 42 | } 43 | cout<<"Array before Sorting: "; 44 | display(arr,n); 45 | shellSort(arr,n); 46 | cout<<"Array after Sorting: "; 47 | display(arr,n); 48 | 49 | 50 | } 51 | -------------------------------------------------------------------------------- /Standard Template Library/collecting_candies.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Collecting Candies 3 | 4 | To find the minimum number of seconds that will be taken to collect the 5 | candies and place them inside a single box. Where the number of seconds is equivalent 6 | to the number of candies in each individual box. 7 | 8 | 9 | */ 10 | #include 11 | #include 12 | using namespace std; 13 | int main(int argc, char const *argv[]) 14 | { 15 | priority_queue , greater > pq; 16 | int n,i,min1,min2,sum,sec,e; 17 | cin>>n; 18 | for(int i=0;i>e; 21 | pq.push(e); 22 | } 23 | min1=min2=sum=sec=0; 24 | while(pq.size()>1) 25 | { 26 | min1 = pq.top(); 27 | pq.pop(); 28 | min2 = pq.top(); 29 | pq.pop(); 30 | sum = min1 + min2; 31 | pq.push(sum); 32 | sec = sec + sum; 33 | } 34 | pq.pop(); 35 | cout< 14 | #include 15 | using namespace std; 16 | int main(int argc, char const *argv[]) 17 | { 18 | int n,e; 19 | queue q; 20 | cin>>n; 21 | for(int i=0;i>e; 24 | q.push(e); 25 | } 26 | cout<pq; 32 | pq.push(10); 33 | pq.push(200); 34 | pq.push(30); 35 | cout< 9 | #include 10 | using namespace std; 11 | int main(int argc, char const *argv[]) 12 | { 13 | stack s; 14 | int n,e; 15 | cin>>n; 16 | for(int i=0;i>e; 19 | s.push(e); 20 | } 21 | cout< al=new ArrayList<>(); 7 | ArrayList bl=new ArrayList<>(); 8 | 9 | for(int i=0;i |string2|). 6 | */ 7 | 8 | // Initial template for C++ 9 | #include 10 | using namespace std; 11 | 12 | class Solution 13 | { 14 | public: 15 | bool isPresent(string string2, char ch) 16 | { 17 | for (int i = 0; i < string2.length(); i++) 18 | { 19 | if (string2[i] == ch) 20 | { 21 | return true; 22 | } 23 | } 24 | return false; 25 | } 26 | string removeChars(string string1, string string2) 27 | { 28 | string res = ""; 29 | for (int i = 0; i < string1.length(); i++) 30 | { 31 | if (!isPresent(string2, string1[i])) 32 | res += string1[i]; 33 | } 34 | return res; 35 | } 36 | }; 37 | 38 | int main() 39 | { 40 | int t; 41 | cin >> t; 42 | while (t--) 43 | { 44 | string string1, string2; 45 | cin >> string1; 46 | cin >> string2; 47 | Solution ob; 48 | cout << ob.removeChars(string1, string2) << endl; 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Strings/reverse_words_in_a_string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given a String S, reverse the string without reversing its individual words. Words are separated by dots. 3 | */ 4 | 5 | #include 6 | using namespace std; 7 | string reverseWords(string s); 8 | int main() 9 | { 10 | int t; 11 | cin >> t; 12 | while (t--) 13 | { 14 | string s; 15 | cin >> s; 16 | cout << reverseWords(s) << endl; 17 | } 18 | } 19 | 20 | string reverseWords(string s) 21 | { 22 | 23 | string res = ""; 24 | reverse(s.begin(), s.end()); 25 | int k = 0; 26 | for (int ind = 0; ind < s.length(); ind++) 27 | { 28 | if (s[ind] == '.') 29 | { 30 | for (int ctr = ind - 1; ctr >= k; ctr--) 31 | res += s[ctr]; 32 | res += '.'; 33 | k = ind + 1; 34 | } 35 | } 36 | for (int ctr = s.length() - 1; ctr >= k; ctr--) 37 | res += s[ctr]; 38 | return res; 39 | } -------------------------------------------------------------------------------- /Strings/string_anagram.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Given two strings a and b consisting of lowercase characters. The task is to check whether two given strings are an 3 | anagram of each other or not. An anagram of a string is another string that contains the same characters, only the 4 | order of characters can be different. For example, “act” and “tac” are an anagram of each other. 5 | */ 6 | 7 | #include 8 | 9 | using namespace std; 10 | 11 | int main() 12 | { 13 | int t; 14 | cin >> t; 15 | while (t--) 16 | { 17 | string a, b; 18 | cin >> a >> b; 19 | unsigned long int lena = a.length(); 20 | unsigned long int lenb = b.length(); 21 | 22 | if (lena != lenb) 23 | { 24 | cout << "NO\n"; 25 | } 26 | else 27 | { 28 | signed int cnt[26] = {0}; 29 | for (int i = 0; i < lena; i++) 30 | { 31 | cnt[a[i] - 'a']++; 32 | } 33 | for (int i = 0; i < lenb; i++) 34 | { 35 | cnt[b[i] - 'a']--; 36 | } 37 | 38 | if (count(cnt, cnt + 26, 0) == 26) 39 | { 40 | cout << "YES\n"; 41 | } 42 | else 43 | cout << "NO\n"; 44 | } 45 | } 46 | return 0; 47 | } -------------------------------------------------------------------------------- /Strings/string_halves_are_alike.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Src : LeetCode 3 | -------------- 4 | 5 | You are given a string s of even length. Split this string into two halves of equal lengths, and let a be the first half and b 6 | be the second half. 7 | 8 | Two strings are alike if they have the same number of vowels ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'). Notice that s 9 | contains uppercase and lowercase letters. 10 | 11 | Return true if a and b are alike. Otherwise, return false. 12 | */ 13 | 14 | class Solution 15 | { 16 | public: 17 | bool isVowel(char ch) 18 | { 19 | switch (ch) 20 | { 21 | case 'a': 22 | case 'A': 23 | case 'e': 24 | case 'E': 25 | case 'i': 26 | case 'I': 27 | case 'o': 28 | case 'O': 29 | case 'u': 30 | case 'U': 31 | return true; 32 | default: 33 | return false; 34 | } 35 | } 36 | bool halvesAreAlike(string s) 37 | { 38 | int count1 = 0, count2 = 0; 39 | int n = s.length(); 40 | int half = n / 2; 41 | for (int i = 0; i < half; i++) 42 | { 43 | if (isVowel(s[i])) 44 | count1++; 45 | } 46 | for (int i = half; i < n; i++) 47 | { 48 | if (isVowel(s[i])) 49 | count2++; 50 | } 51 | return count1 == count2; 52 | } 53 | }; -------------------------------------------------------------------------------- /Strings/string_rotation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | String Rotation 3 | 4 | input 5 | 6 | career 7 | 3 8 | L 2 9 | R 3 10 | L 2 11 | 12 | output 13 | NO 14 | 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | using namespace std; 21 | string shiftLeft(char* s) 22 | { 23 | int len = strlen(s); 24 | std::string st = ((string)s).substr(1, len-1); 25 | return st+s[0]; 26 | } 27 | string shiftRight(char* s) 28 | { 29 | int len = strlen(s); 30 | std::string st = ((string)s).substr(0, len-1); 31 | return s[len-1]+st; 32 | 33 | } 34 | int main() { 35 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 36 | char str[200],ch; 37 | int q,m; 38 | string firstchar=""; 39 | cin>>str; 40 | cin>>q; 41 | for(int i=0;i>ch>>m; 44 | if(ch=='L') 45 | { 46 | for(int j=0;j 9 | #include 10 | using namespace std; 11 | 12 | string shiftLeft(string s,int c) 13 | { 14 | return s.substr(c) + s.substr(0,c); 15 | } 16 | string shiftRight(string s,int c) 17 | { 18 | return s.substr(c+1) + s.substr(0,c+1); 19 | } 20 | int main(int argc, char const *argv[]) 21 | { 22 | cout< 14 | #include 15 | using namespace std; 16 | int isSubstring(string s1, string s2) 17 | { int temp,j; 18 | for(int i=0;s1[i]!='\0';i++) 19 | { 20 | j=0; 21 | if(s1[i]==s2[j]) 22 | { 23 | temp=i+1; 24 | while(s1[i]==s2[j]) 25 | { 26 | i++; 27 | j++; 28 | } 29 | if(s2[j]=='\0') 30 | { 31 | return temp-1; 32 | } 33 | else 34 | { 35 | i=temp; 36 | temp=0; 37 | } 38 | } 39 | } 40 | if(temp==0) 41 | return -1; 42 | } 43 | 44 | int main(int argc, char const *argv[]) 45 | { 46 | string s1,s2; 47 | getline(cin,s1); 48 | getline(cin,s2); 49 | int res = isSubstring(s1,s2); 50 | if(res==-1) 51 | cout< 14 | #include 15 | using namespace std; 16 | int main(int argc, char const *argv[]) 17 | { 18 | char str[200] = "abbcccdddd"; 19 | int len = strlen(str); 20 | int arr[26]; 21 | for(int i=0;i<26;i++) 22 | { 23 | arr[i]=0; 24 | } 25 | int flag = 1; 26 | for(int i=0;i