├── .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 ├── 2D Arrays ├── Set Matrix Zero.cpp ├── StairCaseSearch.py ├── Strassen's_Algo.c ├── 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 ├── matrices.java ├── matrix_find_string_row_wise.c ├── matrix_rotation.cpp ├── matrix_spiral.cpp ├── rotate_by_90.cpp ├── search_2d_matrix.cpp ├── search_2d_matrix2.cpp ├── sort_matrix_diagonally.py ├── sum_of_all_submatrices.cpp ├── sum_of_all_submatrices_2.cpp ├── sum_of_all_submatrices_3.cpp ├── sum_of_matrix_Q_queries.cpp ├── transpose.java ├── transpose_of_matrix.cpp └── wave_print.cpp ├── Arrays ├── Array Reversal.c ├── Array Reversal.py ├── Average_Calculator.py ├── Binary_Numbers.py ├── CommonElements.cpp ├── CommonElements.py ├── CommonElementsOptimal.cpp ├── Divisor_Sum.py ├── Fair Playoff.cpp ├── Hourglass_Sum.py ├── KLargestpairs.py ├── Kadane's_Algorithm.cpp ├── Kadane's_Algorithm.py ├── Kth_smallest_element_in_an_array_using_heap.cpp ├── Leap_Year.py ├── LeftRightSumEqual.cpp ├── Max_XOR_of_Two_Array.cpp ├── Max_diff_in_array.c ├── Maximum_Difference.py ├── Median_of_two_Sorted_arrays_of_different_size.cpp ├── Median_of_two_sorted_array.java ├── Min_Max_Sum.py ├── Minimize_the_height.cpp ├── Minimum_XOR_Value.cpp ├── Missing_integer.cpp ├── N_unique_numbers_sum_upto_zero.cpp ├── PeakElement.java ├── QueryingArray.cpp ├── Rotate Array (LeetCode)-Top Interview Que-Easy Level.cpp ├── RunningSumOf1dArray.cpp ├── ShortestContinuousSubarray.py ├── ShuffleTheArray.cpp ├── TwoSum.cpp ├── containerWithMostWater.cpp ├── duplicates_in_array.cpp ├── duplicates_in_array.py ├── element_left_smaller_right_greater.cpp ├── findMinimumInRotatedSortedArray.cpp ├── first_missing_positive.cpp ├── index_of_an_extra_element.cpp ├── integer.c ├── kadane's_algorithm.c ├── kadanes.java ├── largest_sum_subarray.java ├── leaders_in_an_array.cpp ├── leap.java ├── left_rotate_by_d_brute_force.cpp ├── left_rotate_by_d_extra_space.cpp ├── left_rotate_by_d_no_extra_space.cpp ├── max_and_min_element.cpp ├── max_prod_of_two_elements.cpp ├── merge_two_sorted_arrays.cpp ├── missing_number_in_array.cpp ├── move_zeroes_end_1traversal.cpp ├── move_zeroes_end_2traversal.cpp ├── negative_number_shuffle.cpp ├── peek_element.cpp ├── remove_duplicates_from_sorted_array.cpp ├── remove_duplicates_from_sorted_array.py ├── replace_elements_with_greatest_element_on_right.cpp ├── searchInRotatedSortedArray.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_all_subarrays.cpp ├── sum_of_elements_to_right.cpp ├── sum_of_other_elements.cpp ├── sum_of_three_values.c++ ├── sum_positions.cpp ├── trapping_rain_water_brute_force.cpp ├── trapping_rain_water_extra_space.cpp ├── trapping_rain_water_two_pointer.cpp ├── trappingrainwater.cpp ├── triplet_sum.cpp └── zero_sum_subarray.java ├── Backtracking ├── Cryptarithmetic_Problem.py ├── Graph_Coloring_Problem.py ├── Hamiltonian_Cycle.py ├── Knight's_Tour.java ├── Knight's_Tour.py ├── N-Queen Problem.cpp ├── N_Queens Problem.c ├── N_Queens.py ├── Subset_Sum.py ├── Sudoku.py ├── backtracking_rat_in_a_maze.cpp ├── eightQueen.c ├── graph_coloring.c ├── rat_maze.cpp ├── sudoku.c ├── tic_tac_toe_game.py └── water_jug_problem.py ├── Bit Manipulation ├── Bit_Difference.cpp ├── Bitwise_AND.py ├── 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_Set_using_Bit_Manipulation.cpp ├── Power_of_2.cpp ├── max_subset_XOR.cpp └── rotate_bits.cpp ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CONTRIBUTORS.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 ├── Codechef Problems ├── Cricket_Ranking.c ├── DSA Learning Series │ ├── Alternative Square Pattern.java │ ├── Buy Please.c │ ├── Factors Finding.c │ ├── Find Second Largest.c │ ├── Find me.c │ ├── Is both or not.c │ ├── Raju and his trip.c │ ├── Range odd.c │ ├── Reverse Star Pattern.c │ ├── Reverse me.c │ ├── TriangleEverywhere.cpp │ └── Valid traingle or not.c ├── Food_Chain.c ├── Red_alert.c ├── Richie Rich.c └── TheLeadGame.cpp ├── Cryptography └── Caesar_Cipher.py ├── DSA 450 GFG ├── reverse_an_array.cpp ├── ActivitySelection.py ├── AllocateMinimumNumberOfPages.cpp ├── BTtoBST.py ├── BuyandSell.py ├── CountAndSay.py ├── DeleteNodeinBST.py ├── DiameterOfBinTree.py ├── HeightOfBinTree.py ├── InOrderTraversal-rec.py ├── InorderTraversal-Iterative.py ├── LongestCommonPrefix.py ├── LongestPalindromicSubstring.py ├── PreOrder-recursive.py ├── PreOrder_iterative.py ├── PrintAnagrams.py ├── TowerOfHanoi.cpp ├── TrapRainWater.py ├── Union_Arrays.cpp ├── WordBreak.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 ├── merge_without_extra_space.cpp ├── mirror_tree.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 ├── reverse_linked_list_iterative.py ├── reverse_linked_list_rec.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 ├── tower_of_hanoi.py └── vertical_order_traversal.py ├── Data Structures ├── Graphs │ ├── Bellman Ford.c │ ├── Boruvka_algorithm_for_finding_MST.cpp │ ├── Bridge_edge_in_graph.cpp │ ├── Center_Of_Star_Graph.cpp │ ├── Dijkstra.c │ ├── Khan_algo.py │ ├── Representation │ │ ├── Adjacency_List.cpp │ │ ├── adjacency_list.cpp │ │ └── adjacency_matrix.cpp │ ├── RottenOranges.cpp │ ├── Topological_Sort.cpp │ ├── Traversal │ │ ├── BFS.py │ │ ├── BFSTraversal.cpp │ │ ├── DFS.py │ │ ├── DFSTraversal.cpp │ │ └── in.txt │ ├── WarshallAlgorithm.py │ ├── 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 │ │ ├── d_linkedlist.py │ │ ├── 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 │ ├── Remove_all_Duplicates_from_Linnkedlist.cpp │ └── Singly Linked List │ │ ├── .DS_Store │ │ ├── Delete_node_without_head_pointer.cpp │ │ ├── Flattening_a_link_list.cpp │ │ ├── Intersection_Of_Two_LinkedList.cpp │ │ ├── Reverse_Nodes_in_K_Groups.cpp │ │ ├── SLL insertion.cpp │ │ ├── SLL.cpp │ │ ├── Single-linked-list-operations.py │ │ ├── Swap_nodes.py │ │ ├── add_one_to_number_represented_by_linkedlist.cpp │ │ ├── binary_number_linkedlist_integer.cpp │ │ ├── check_if_linkedlist_is_a_palindrome.cpp │ │ ├── check_linkedlist_palindrome.cpp │ │ ├── compare_two_linkedlist.py │ │ ├── cycle-detection-using-java.java │ │ ├── detect_loop_in_linkedlist.cpp │ │ ├── merge_k_sorted_linkedlist.cpp │ │ ├── merge_two_sorted_linkedlist.cpp │ │ ├── merge_two_sorted_linkedlist.py │ │ ├── middle_of_linkedlist.cpp │ │ ├── nth_node_from_last.cpp │ │ ├── oddEvenLinkedList.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 │ │ └── simple_linkedlist_operations.cpp ├── Queues │ ├── Truck_tour.cpp │ ├── circular_queue.c │ ├── priority_queue_max.cpp │ └── priority_queue_min.cpp ├── Stacks │ ├── BalancedParantheses.cpp │ ├── BalancedParenthesis.java │ ├── Check redundant brackets.py │ ├── Largest_rectangle_area_under_histogram.cpp │ ├── Next_Greater_Element.cpp │ ├── Palindrome_Checker.py │ ├── Previous_Greater_Element.cpp │ ├── Sort_stack_using_recursion.cpp │ ├── balanced_parentheses.py │ ├── infix_to_postfix_conversion.py │ ├── maximum_size_of_balanced_bracket_sequence.cpp │ ├── merge_intervals.cpp │ ├── postfix_evaluation.c │ ├── redundant_braces.cpp │ ├── simplify_directory_path.cpp │ └── stack.c ├── Trees │ ├── AVL_Tree_or_not.cpp │ ├── BST.py │ ├── BST_Level_Order_Traversal.py │ ├── BinaryTree_Maximum_Path_Sum.cpp │ ├── Construct_Binary_Tree_from_Preorder_and_Inorder_Traversal.cpp │ ├── Diameter_Binary_Tree.cpp │ ├── Flatten_BinaryTree_to_LinkedList.cpp │ ├── Height_of_BST.py │ ├── Maximum_Element_of_Binary_Tree.cpp │ ├── binary_search_tree.cpp │ ├── binary_tree_right_side_view.py │ ├── binary_tree_to_bst.cpp │ ├── binary_tree_to_dll.py │ ├── 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 │ ├── expression_tree_evaluation.py │ ├── invert_a_binary_tree.cpp │ ├── level_order_traversal.cpp │ ├── lowest_common_ancestor_binary_tree.cpp │ ├── lowest_common_ancestor_binary_tree.py │ ├── lowest_common_ancestor_bst.cpp │ ├── merge_two_binary_trees.cpp │ ├── min_bs.cpp │ ├── normal_tree.py │ ├── path_to_node_binary_tree.py │ ├── red_black_tree_insertion_and_deletion.cpp │ ├── segment_tree_range_sum_and_update_query.py │ ├── sum_tree.cpp │ ├── top_view_binary_tree.cpp │ └── tree_from_postorder_and_inorder.cpp └── Trie │ ├── Implement_trie.cpp │ └── Trie_add_Search_using_dict.py ├── Divide and Conquer ├── ClosestPairOfPoints.py ├── DCPower.java ├── PowerMem.java ├── PowerofN.java └── Powerofnumber.cpp ├── Dynamic Programming ├── Buy_And_Sell_Stocks.cpp ├── ClimbingStairs_bottom_up.py ├── ClimbingStairs_memoization.py ├── CoinChange.py ├── Coin_Change.cpp ├── Collinearity_of_three_points.cpp ├── Edit_distance.cpp ├── FibonacciMem.java ├── FibonacciTab.java ├── FibonacciTabEff.java ├── Floyed- Warshall.c ├── Klee's Algorithm.cpp ├── Knapsack_01_TabulationMethod.cpp ├── Knapsack_greedyMethod.c ├── LCS_Memoization.c ├── LCS_Recursion.c ├── LCS_Tabulation.c ├── Longest_common_substring.cpp ├── Matrix_chain_multiplication.c ├── MinPathSum.java ├── MirrorOfBinTree.py ├── Square_brackets.cpp ├── Unbounded_Knapsack.cpp ├── binomial_coefficient.cpp ├── job_sequencing_greedyMethod.c ├── knapsack_01.cpp ├── minimum_diffrenece subset.cpp ├── sliding_window_sum.cpp ├── sum_of_subsets.c └── zigzag_conversion.java ├── 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 ├── AP_GP.cpp ├── CLL SLL Wipro.c ├── Checking-if-given-array-is-max-heap.cpp ├── Common_elements_in_all_rows_of_a_given_matrix.cpp ├── Difficult_pattern.c ├── Difficult_pattern2.c ├── Difficult_pattern3.c ├── Difficult_pattern4.c ├── Dutch_national_flag2.java ├── Josepheus_problem.cpp ├── Longest_Common_Prefix.py ├── Nearest_point.cpp ├── Plus_One.cpp ├── Polynomial_Verification.py ├── Round-Robin-Algorithm.c ├── SilverAndGold.java ├── Sorted-array-to-BST.py ├── christmas_tree.c ├── circle_and_point.c ├── combinational_sum.py ├── 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 ├── possible no from word.cpp └── 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 ├── 30 days Of Code │ ├── Day0- Hello World.c │ ├── Day1-DataTypes.c │ ├── Day10-BinaryNumbers.c │ ├── Day11-2D_arrays.c │ ├── Day12-Inheritance.java │ ├── Day2-Operators.c │ ├── Day3-IntroToConditionalStatements.c │ ├── Day4-ClassVSInstance.c │ ├── Day5-Loops.c │ ├── Day6-Let's Review.c │ ├── Day7-Arrays.c │ ├── Day8-Dictionaries_and_Maps.c │ └── Day9-Recursion3.c └── the_minion_game.py ├── Hashing ├── IsomorphicStrings.java ├── chef_and_subarrays.cpp ├── sequence_pair_weight.cpp └── sort_elements_by_frequency.cpp ├── LICENSE ├── Library ├── Java │ ├── Screenshot 2021-07-12 121030.png │ ├── Screenshot 2021-07-12 132104.png │ ├── Screenshot 2021-07-12 132959.png │ ├── photo_2019-07-03_00-02-44.jpg │ ├── photo_2019-07-20_23-56-04.jpg │ ├── photo_2020-06-29_16-39-21.jpg │ ├── photo_2020-08-17_18-03-24.jpg │ ├── photo_2020-08-29_16-30-42.jpg │ ├── photo_2020-09-17_13-31-29.jpg │ ├── photo_2020-09-18_18-24-45.jpg │ └── s └── a ├── 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 ├── Complex_numbers.cpp ├── DecimaltoBinary.cpp ├── FindDivisors.cpp ├── FindDivisors.py ├── JumpingNumbers.cpp ├── LargerNumber.cpp ├── LargerNumber.py ├── MaxMin.cpp ├── NumberofBinDigits.java ├── PerfectNumber.cpp ├── Prime_Numbers.py ├── Roman_to_Integer.java ├── RomantoInteger.py ├── Sieve-of-Eratosthenes.cpp ├── Sieve.c ├── SquareRoot.java ├── 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 ├── Abstraction │ └── Abstraction_cpp.cpp ├── Constructor │ ├── Constructor_Overloading_cpp.cpp │ ├── Copy_Constructor_cpp.cpp │ ├── Deep_Copy_Constructor_cpp.cpp │ ├── Default_Constructor_cpp.cpp │ ├── Parameterized_Constructor_cpp.cpp │ └── Shallow_Copy_Constructor_cpp.cpp ├── Destructor │ └── Destructor_cpp.cpp ├── Encapsulation │ └── Encapsulation_cpp.cpp ├── Friend Class & Function │ └── Friend_Class_cpp.cpp ├── Inheritance │ ├── HierarchicalInheritance.java │ ├── Hierarchical_Inheritance_cpp.cpp │ ├── Hybrid_Inheritance _cpp.cpp │ ├── MultiLevel_Inheritance.java │ ├── Multilevel_Inheritance_cpp.cpp │ ├── Multiple_Inheritance_cpp.cpp │ ├── Private_Inheritance_cpp.cpp │ ├── Protected_Inheritance_cpp.cpp │ ├── Public_Inheritance_cpp.cpp │ ├── Single_Inheritance.java │ └── Single_Inheritance_cpp.cpp └── Polymorphism │ ├── Method_Overloading.java │ ├── Method_Overriding.java │ ├── function_overloading.cpp │ └── operator_overloading.cpp ├── Passwords ├── 1d_password.cpp ├── 2d_password.cpp └── password_strength_checker.py ├── README.md ├── Recursion ├── All_indices_of_element.cpp ├── Last_index_of_element_in_array.cpp ├── Possible_Words_From_Phone_Digits.cpp ├── first_index_of_element_in_array.cpp ├── remove_duplicates.cpp ├── subsets.cpp ├── subsets2.cpp └── towerOfHanoi.java ├── Searching Algorithms ├── 8_Puzzle_Problem_using_A_star_Algorithm.py ├── 8_Puzzle_Problem_using_BFS.py ├── Binary_search.java ├── Jump_search.c ├── Ternary_search.c ├── binary_search.c ├── binary_search.cpp ├── binary_search.js ├── binary_search.py ├── jump_search.cpp ├── linear_search.cpp ├── linear_search.js └── linear_search.py ├── Sorting Algorithms ├── Bubble_Sort.java ├── Bubble_sort.c ├── Bucket Sort.py ├── HeapSortinC.C ├── InsertionSort.java ├── SelectionSort.js ├── bubble_sort.cpp ├── bubble_sort.py ├── bucket_sort.cpp ├── counting_sort.cpp ├── counting_sort.py ├── heap_sort.cpp ├── heap_sort.py ├── insertion_sort.cpp ├── insertion_sort.py ├── merge_sort.cpp ├── quick_sort.cpp ├── quick_sort.py ├── radix_sort.cpp ├── selection_sort.cpp ├── selection_sort.java ├── selection_sort.py ├── shell_sort.cpp ├── shell_sort.py └── wavesort.cpp ├── Standard Template Library ├── STL.cpp ├── balancedparenthesis_stl.cpp ├── collecting_candies.cpp ├── queue_example.cpp └── stack_example.cpp ├── Strings ├── Bad_String.py ├── Capitalizing.py ├── ConvertToPalindrome_Strings.cpp ├── Count_word.c ├── CustomSortString.java ├── Extract_the_Number_from_String.cpp ├── KMP_Algorithm.cpp ├── KMP_Algorithm.py ├── Longest_Substring_Without_Repeating_Characters.cpp ├── Longest_Substring_with_AtLeast_K_Repeating_Characters.cpp ├── Rabin_Karp.py ├── Rabin_Karp_Algorithm.cpp ├── Reverse_vowels_of_a_string.cpp ├── Stuck Keyboard │ ├── .DS_Store │ ├── StuckKeyboard.py │ └── stuck_keyboard.cpp ├── Validate_IP_address.cpp ├── alternating_characters.c ├── characters_or_sum_digits.cpp ├── check_if_strings_are_rotation_of_eachother.cpp ├── check_password.cpp ├── cyclic_palindrome .png ├── decrypt_string_alpha_to_int_mapping.cpp ├── findAndReplacePattern.cpp ├── integer_to_roman.cpp ├── isomorphic_strings.cpp ├── length_of_longest_substring_without_repeat_char.cpp ├── removePalindromicSubsequences.java ├── remove_character.cpp ├── reverse_words_in_a_string.cpp ├── smallestdistinctwindow.cpp ├── string_anagram.cpp ├── string_halves_are_alike.cpp ├── string_permutations.cpp ├── string_rotation.cpp ├── string_shift_operations.cpp ├── substring_index.cpp ├── super_ascii_checker .png ├── super_ascii_checker.cpp └── zigZagConversion.cpp ├── Techgig Code Gladiators 2021 ├── Readme.md ├── open round │ ├── prime_game.md │ ├── prime_game.py │ ├── virus_outbreak.md │ └── virus_outbreak.py └── semifinals │ ├── JazzyAndCricketBalls.cpp │ ├── jazzy and cricket balls.md │ └── jazzy and cricket balls.py ├── _config.yml └── images ├── cpqb.jpg └── 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 | 9 | 10 | ### Have you read the [Contributing Guidelines on Pull Requests](https://github.com/smv1999/CompetitiveProgrammingQuestionBank/blob/master/CONTRIBUTING.md)? 11 | 12 | (Write your answer here.) 13 | 14 | ### Description 15 | 16 | (Write your answer here.) 17 | 18 | ### Checklist 19 | 20 | - [ ] I've read the contribution guidelines. 21 | - [ ] I've checked the issue list before deciding what to submit. 22 | 23 | ## Related Issues or Pull Requests 24 | 25 | (Write your answer here.) 26 | 27 | ## Fill up the DCP form 28 | 29 | If you are a part of DCP 21, fill up this [form](https://docs.google.com/forms/d/e/1FAIpQLSeRAJnHE4eAa_W0IUeNZgheiy5POX3I3tQB7DtFsiB13D5w2g/viewform) after the PR is merged. 30 | 31 | 32 | ### The links provided in the form will be checked thoroughly, if someone tries fooling around, strict actions will be taken against the individual. -------------------------------------------------------------------------------- /.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 -------------------------------------------------------------------------------- /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_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/matrix_find_string_row_wise.c: -------------------------------------------------------------------------------- 1 | /* 2 | A character matrix of size N*N and a string S are given as input.The program must check if the string is present 3 | in the matrix row-wise and print the row number of the rows with the given string in it. 4 | 5 | Input: 6 | 4 7 | h e l l 8 | k t h e 9 | a t c k 10 | k t h e 11 | the 12 | 13 | Output: 14 | 2 15 | 4 16 | */ 17 | #include 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 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/sort_matrix_diagonally.py: -------------------------------------------------------------------------------- 1 | def sortDiagonal(a, M, N): 2 | 3 | # Loop to find the ith minimum 4 | # element from the major diagonally 5 | for i in range(M): 6 | sm = a[i][i] 7 | pos = i 8 | 9 | # Loop to find the minimum 10 | # element from the unsorted matrix 11 | for j in range(i + 1 , N): 12 | if (sm > a[j][j]): 13 | sm = a[j][j] 14 | pos = j 15 | 16 | # Swap to put the minimum 17 | # element at the beginning of 18 | # the major diagonal of matrix 19 | a[i][i], a[pos][pos] = a[pos][pos] , a[i][i] 20 | 21 | # Loop to print the matrix 22 | for i in range(M): 23 | for j in range(N): 24 | print(a[i][j],end=" ") 25 | print() 26 | 27 | # Driven Code 28 | a = [[4, 2],[3, 1]] 29 | 30 | # Sort the major Diagonally 31 | sortDiagonal(a, 2, 2) -------------------------------------------------------------------------------- /2D Arrays/transpose_of_matrix.cpp: -------------------------------------------------------------------------------- 1 | //Write a program to find the transpose of a square matrix of size N*N. The transpose of a matrix is obtained by changing rows to columns and columns to rows. 2 | 3 | #include 4 | using namespace std; 5 | 6 | //Function to find transpose of a matrix. 7 | void transpose(vector > &matrix, int n) 8 | { 9 | for(int i=0; i< n; i++) 10 | { 11 | 12 | for(int j=i; j< n; j++) 13 | { 14 | swap(matrix[i][j], matrix[j][i]); 15 | } 16 | } 17 | } 18 | 19 | int main() 20 | { 21 | 22 | int t; 23 | cin>>t; 24 | 25 | while(t--) 26 | { 27 | int n; 28 | cin>>n; 29 | vector > matrix(n); 30 | 31 | for(int i=0; i>matrix[i][j]; 37 | } 38 | } 39 | 40 | transpose(matrix,n); 41 | for (int i = 0; i < n; ++i) 42 | { 43 | for (int j = 0; j < n; ++j) 44 | cout< 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 O(1) 30 | Space Complexity -> O(N) 31 | 32 | Sample Input: 33 | Enter numbers: 5 3 1 2 3 4 5 34 | 35 | Sample Output: 36 | Average is: 3.0 37 | 38 | Explanation: 39 | All unique integers --> 1 2 3 4 5 40 | Total count --> 5 41 | Average --> (1+2+3+4+5)/5 = 3.0 42 | 43 | ''' -------------------------------------------------------------------------------- /Arrays/CommonElements.py: -------------------------------------------------------------------------------- 1 | '''Finding common elements between two arrays in which the elements are distinct. 2 | Eg: 3 | 4 | 1 2 3 4 5 12 8 5 | 6 7 3 4 2 9 11 6 | 7 | 8 | O/P: 9 | 2 3 4 ''' 10 | 11 | # Taking array input 12 | l1=input().split() 13 | l2=input().split() 14 | 15 | #Creating array of common elements 16 | r=[] 17 | for i in l1: 18 | if i in l2: 19 | r.append(i) 20 | 21 | print(r) 22 | 23 | -------------------------------------------------------------------------------- /Arrays/Divisor_Sum.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Aim: Calculate the sum of all the divisors of the entered number and display it. 3 | 4 | ''' 5 | 6 | # function to find out all divisors and add them up 7 | def divisorSum(n): 8 | temp = [] 9 | for i in range(1, n+1): 10 | # condition for finding factors 11 | if n%i == 0: 12 | temp.append(i) 13 | # adding all divisors 14 | return sum(temp) 15 | 16 | # getting the input 17 | n = int(input()) 18 | # printing the result 19 | print(divisorSum(n)) 20 | 21 | ''' 22 | 23 | COMPLEXITY: 24 | 25 | Time Complexity -> O(N) 26 | Space Complexity -> O(1) 27 | 28 | Sample Input: 29 | 6 30 | Sample Output: 31 | 12 32 | 33 | Explaination: 34 | Divisors/Factors of 6 are --> 1,2,3 and 6. 35 | Adding them up --> 1+2+3+6 = 12. 36 | 37 | ''' -------------------------------------------------------------------------------- /Arrays/Kadane's_Algorithm.py: -------------------------------------------------------------------------------- 1 | #Kadane's Algorithm 2 | 3 | def kadaneAlgo(arr): 4 | maxSumSoFar = arr[0] 5 | max_sum = arr[0] 6 | for ele in arr[1:]: 7 | maxSumSoFar = max(ele, ele + maxSumSoFar) #current maximum sum so far 8 | max_sum = max(max_sum, maxSumSoFar) #maximum sum so far 9 | return max_sum 10 | 11 | l = list(map(int, input().split())) 12 | max_sm = kadaneAlgo(l) 13 | print(max_sm) 14 | -------------------------------------------------------------------------------- /Arrays/Leap_Year.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Aim: To check if the entered year is a leap year or not. 3 | 4 | ''' 5 | 6 | def is_leap(year): 7 | # a year is a leap one if it's divisible by 4 and if it's not 8 | # divisible by 100 or is divisible by 400 9 | print((year%4==0 and (year%100!=0 or year%400==0))) 10 | 11 | # getting the input 12 | year = int(input().strip()) 13 | # displaying the result 14 | is_leap(year) 15 | 16 | ''' 17 | 18 | COMPLEXITY: 19 | 20 | Time Complexity -> O(1) 21 | Space Complexity -> O(1) 22 | 23 | Sample Input: 24 | 2000 25 | 26 | Sample Output: 27 | True 28 | 29 | Explanation: 30 | 2000 % 400 = 0 31 | 2000 % 4 = 0 32 | Hence, 2000 was a leap year. 33 | 34 | ''' -------------------------------------------------------------------------------- /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/PeakElement.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | public class PeakElement { 3 | // TC : O(logn) 4 | // SC : O(1) 5 | public static void main(String args[])throws IOException 6 | { 7 | InputStreamReader read=new InputStreamReader(System.in); 8 | BufferedReader in=new BufferedReader(read); 9 | int n,i; 10 | System.out.println("Enter the size of the array"); 11 | n=Integer.parseInt(in.readLine()); 12 | int nums[]=new int[n]; 13 | System.out.println("Enter the elements of the array"); 14 | for(i=0;imax_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/move_zeroes_end_1traversal.cpp: -------------------------------------------------------------------------------- 1 | //Move all zeros to End 2 | //Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements. 3 | //Approach 2 4 | //O(n) O(1) 5 | 6 | 7 | // i/p: n=5, 0 1 0 3 12 8 | // o/p: 1 3 12 0 0 9 | 10 | // Here we replace another loop with count 11 | 12 | #include 13 | using namespace std; 14 | void moveToEnd(int arr[],int n) 15 | { 16 | int count=0; 17 | for(int i=0;i>n; 35 | int arr[n]; 36 | cout<<"Enter the elements in array\n"; 37 | for(i=0;i>arr[i]; 39 | moveToEnd(arr,n); 40 | cout<<"Array having zeroes at end\n"; 41 | for(i=0;i 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/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_all_subarrays.cpp: -------------------------------------------------------------------------------- 1 | /* Q. Given an integer array ‘arr[]’ of size n, find sum of all sub-arrays of given array. 2 | Input : a[] = {1, 2, 3} 3 | Output: 20 4 | 5 | Explanation: We have to generate all the subarrays using two for loops and then compute their sum. 6 | subarrays --> {1} {12} {123} {2} {23} {3} 7 | subarrays sum --> 1 + 3 + 6 + 2 + 5 + 3 --> 20 8 | 9 | Time Complexity: O(n^2) 10 | */ 11 | 12 | #include 13 | using namespace std; 14 | int main() 15 | { 16 | int n, sum=0, result = 0; 17 | cin>>n; 18 | int a[n]; 19 | for( int i=0; i>a[i]; 22 | } 23 | 24 | for( int i=0; i 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 6 | using namespace std; 7 | 8 | int main(){ 9 | int arr[]={1,8,6,2,5,4,8,3,7}; //array of diff heights 10 | int l=0,n=sizeof(arr)/sizeof(int),r=n-1; 11 | int max_area=0,h,a,b; 12 | //2 pointers algorithm 13 | 14 | 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< 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"< 6 | 7 | 8 | 9 | 🚀 **Contributions** of any kind is welcome! 10 | -------------------------------------------------------------------------------- /CodeVita Problems/Image segmentation.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/CodeVita Problems/Image segmentation.pdf -------------------------------------------------------------------------------- /CodeVita Problems/codu loves sum.c: -------------------------------------------------------------------------------- 1 | #include 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 24 | 25 | int main(void) { 26 | 27 | int a,b,x,y; 28 | scanf("%d %d %d %d",&a,&b,&x,&y); 29 | int pen_cost= a*x; 30 | int pencil_cost=b*y; 31 | int total=pen_cost+pencil_cost; 32 | printf("%d",total); 33 | 34 | return 0; 35 | 36 | } 37 | -------------------------------------------------------------------------------- /Codechef Problems/DSA Learning Series/Factors Finding.c: -------------------------------------------------------------------------------- 1 | /* You are given a number N and find all the distinct factors of N. 2 | 3 | Input: 4 | First-line will contain the number N. 5 | Output: 6 | In the first line print number of distinct factors of N. 7 | In the second line print all distinct factors in ascending order separated by space. 8 | Constraints 9 | 1≤N≤106 10 | Sample Input 1: 11 | 4 12 | Sample Output 1: 13 | 3 14 | 1 2 4 15 | Sample Input 2: 16 | 6 17 | Sample Output 2: 18 | 4 19 | 1 2 3 6 20 | EXPLANATION: 21 | In the first example, all factors of 4 are 1, 2, 4. 22 | In the second example, all factors of 6 are 1, 2, 3, 6. */ 23 | 24 | #include 25 | 26 | int main(void) { 27 | 28 | int n; 29 | scanf("%d",&n); 30 | int c=0; 31 | int a[n]; 32 | 33 | for(int i=1;i<=n;i++) 34 | { 35 | if(n%i==0) 36 | { 37 | a[c]=i; 38 | c++; 39 | } 40 | } 41 | printf("%d \n",c); 42 | for(int i=0;i 26 | 27 | int main(void) { 28 | 29 | int n,k; 30 | scanf("%d %d",&n,&k); 31 | int a[n]; 32 | int c=0; 33 | for(int i=1; i<=n; i++) 34 | { 35 | scanf("%d ",&a[i]); 36 | if(a[i]==k) 37 | { 38 | c=1; 39 | } 40 | } 41 | 42 | if(c==1) 43 | { 44 | printf("1"); 45 | } 46 | else 47 | { 48 | printf("-1"); 49 | } 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Codechef Problems/DSA Learning Series/Is both or not.c: -------------------------------------------------------------------------------- 1 | /* You're given a number N. If N is divisible by 5 or 11 but not both then print "ONE"(without quotes). If N is divisible by both 5 and 11 then print "BOTH"(without quotes). If N is not divisible by 5 or 11 then print "NONE"(without quotes). 2 | 3 | Input: 4 | First-line will contain the number N. 5 | Output: 6 | Print the answer in a newline. 7 | 8 | Constraints 9 | 1≤N≤103 10 | Sample Input 1: 11 | 50 12 | Sample Output 1: 13 | ONE 14 | Sample Input 2: 15 | 110 16 | Sample Output 2: 17 | BOTH 18 | Sample Input 2: 19 | 16 20 | Sample Output 2: 21 | NONE 22 | EXPLANATION: 23 | In the first example, 50 is divisible by 5, but not 11. 24 | In the second example, 110 is divisible by both 5 and 11. 25 | In the third example, 16 is not divisible by 5 or 11. */ 26 | 27 | #include 28 | 29 | int main(void) { 30 | 31 | int n; 32 | scanf("%d",&n); 33 | if((n%5==0)&&(n%11==0)) 34 | { 35 | printf("BOTH"); 36 | } 37 | else if((n%5==0)||(n%11==0)) 38 | { 39 | printf("ONE"); 40 | } 41 | else 42 | { 43 | printf("NONE"); 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Codechef Problems/DSA Learning Series/Range odd.c: -------------------------------------------------------------------------------- 1 | /* You're given two numbers L and R. Print all odd numbers between L and R (both inclusive) in a single line separated by space, in ascending (increasing) order. 2 | 3 | Input: 4 | First-line will contain two numbers L and R. 5 | Output: 6 | Print all odd numbers in a single line separated by space, in ascending (increasing) order. 7 | 8 | Constraints 9 | 1≤L 23 | 24 | int main(void) { 25 | 26 | int start , end; 27 | scanf("%d %d",&start,&end); 28 | int a[end]; 29 | int x=0; 30 | for(int i=start;i<=end;i++) 31 | { 32 | 33 | if(i%2!=0) 34 | { 35 | a[x]=i; 36 | x++; 37 | } 38 | } 39 | 40 | for (int y=0;y 33 | 34 | int main(void) { 35 | 36 | int t; 37 | scanf("%d",&t); 38 | 39 | for(int i=1;i<=t;i++) 40 | { 41 | for(int j=t;j>i;j--) 42 | printf(" "); 43 | for(int k=1;k<=i;k++) 44 | printf("*"); 45 | printf("\n"); 46 | } 47 | 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Codechef Problems/DSA Learning Series/Reverse me.c: -------------------------------------------------------------------------------- 1 | /* You are given a list of N integers and you need to reverse it and print the reversed list in a new line. 2 | 3 | Input: 4 | First-line will contain the number N. 5 | Second line will contain N space-separated integers. 6 | Output: 7 | Print the reversed list in a single line. 8 | 9 | Constraints 10 | 1≤N,Ai≤105 11 | Sample Input 1: 12 | 4 13 | 1 3 2 4 14 | Sample Output 1: 15 | 4 2 3 1 16 | Sample Input 2: 17 | 2 18 | 9 8 19 | Sample Output 2: 20 | 8 9 21 | EXPLANATION: 22 | In the first example, the reverse of the [1,3,2,4] is [4,2,3,1]. 23 | In the second example, the reverse of [9,8] is [8,9]. */ 24 | 25 | #include 26 | 27 | int main(void) { 28 | 29 | int n; 30 | scanf("%d",&n); 31 | int a[n]; 32 | 33 | for(int i=1;i<=n;i++) 34 | { 35 | scanf("%d ",&a[i]); 36 | 37 | } 38 | 39 | for(int i=n;i>=1;i--) 40 | { 41 | printf("%d ",a[i]); 42 | 43 | } 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /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/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/LongestPalindromicSubstring.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/longest-palindromic-substring/ 2 | 3 | class Solution(object): 4 | def longestPalindrome(self, s): 5 | """ 6 | :type s: str 7 | :rtype: str 8 | """ 9 | 10 | # result to store palindrome 11 | res = "" 12 | 13 | for i in range(len(s)): 14 | 15 | # for odd len strings 16 | # Eg : "racecar" 17 | tmp = self.helper(i, i, s) 18 | if len(res) < len(tmp): 19 | res = tmp 20 | 21 | # for even len strings 22 | # Eg: "aaaabbaa" 23 | tmp = self.helper(i, i + 1, s) 24 | if len(res) < len(tmp): 25 | res = tmp 26 | 27 | 28 | return res 29 | 30 | def helper(self, l, r, s): 31 | # Helper function to check if the left pointer and right pointer are equal 32 | # if inbound and palindrome, move left left and right right 33 | 34 | while (l >= 0 and r < len(s) and s[l] == s[r]): 35 | l -= 1 36 | r += 1 37 | 38 | 39 | return s[l + 1: r] -------------------------------------------------------------------------------- /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/WordBreak.py: -------------------------------------------------------------------------------- 1 | 2 | # Link : https://leetcode.com/problems/word-break/submissions/ 3 | 4 | # Reference : https://www.youtube.com/watch?v=Sx9NNgInc3A 5 | 6 | # TC : O(mn) 7 | 8 | # Approach : https://somber-approval-8f1.notion.site/DSA-Solutions-34100a8ab92f42029011dcf591668343 9 | 10 | 11 | class Solution(object): 12 | def wordBreak(self, s, wordDict): 13 | """ 14 | :type s: str 15 | :type wordDict: List[str] 16 | :rtype: bool 17 | """ 18 | 19 | dp = [False] * (len(s) + 1) 20 | dp[len(s)] = True 21 | 22 | for i in range(len(s) - 1 , -1 , -1): 23 | for w in wordDict: 24 | if((i + len(w)) <= len(s) and s[i : i + len(w)] == w): 25 | dp[i] = dp[i + len(w)] 26 | 27 | if(dp[i]): 28 | break 29 | 30 | return dp[0] 31 | 32 | -------------------------------------------------------------------------------- /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/reverse_linked_list_iterative.py: -------------------------------------------------------------------------------- 1 | #https://leetcode.com/problems/reverse-linked-list/ 2 | 3 | # Iterative method 4 | #Approach : 5 | 6 | # Store the head in a temp variable called current . 7 | 8 | # curr = head , prev = null 9 | 10 | # Now for a normal linked list , the current will point to the next node and so on till null 11 | # For reverse linked list, the current node should point to the previous node and the first node here will point to null 12 | 13 | # Keep iterating the linkedlist until the last node and keep changing the next of the current node to prev node and also 14 | # update the prev node to current node and current node to next node 15 | 16 | 17 | # class ListNode: 18 | # def __init__(self, val=0, next=None): 19 | # self.val = val 20 | # self.next = next 21 | 22 | class Solution: 23 | 24 | def reverseList(self, head): 25 | curr = head 26 | prev = None 27 | while(curr != None): 28 | next = curr.next 29 | curr.next = prev 30 | prev = curr 31 | curr = next 32 | 33 | return prev 34 | -------------------------------------------------------------------------------- /DSA 450 GFG/reverse_linked_list_rec.py: -------------------------------------------------------------------------------- 1 | # Approach : 2 | # Divide the linked list to two halved 3 | # First half is head and the remaining as rest 4 | # The head points to the rest in a normal linked list 5 | # In the reverse linked list , the next of current points to the prev node and the head node should point to NULL 6 | # Keep continuing this process till the last node 7 | 8 | 9 | # Definition for singly-linked list. 10 | # class ListNode: 11 | # def __init__(self, val=0, next=None): 12 | # self.val = val 13 | # self.next = next 14 | 15 | 16 | class Solution: 17 | def reverseList(self, head): 18 | if head is None or head.next is None: 19 | return head 20 | rest = self.reverseList(head.next) 21 | head.next.next = head 22 | head.next = None 23 | return rest -------------------------------------------------------------------------------- /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/tower_of_hanoi.py: -------------------------------------------------------------------------------- 1 | # we have to transfer n disks from rod A to C using the auxilliary rod B 2 | def tower_of_hanoi(n, A, B, C): 3 | if(n>0): 4 | tower_of_hanoi(n-1, A, C, B) 5 | print("Moving disk ",n," from rod ", A, " to rod ", C) 6 | tower_of_hanoi(n-1, B, A, C) 7 | 8 | n= int(input()) 9 | tower_of_hanoi(n, 'A','B','C') 10 | -------------------------------------------------------------------------------- /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/Representation/adjacency_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main(int argc, char const *argv[]) 7 | { 8 | int n, m; 9 | cin >> n >> m; 10 | 11 | vector adj_list[n + 1]; 12 | 13 | while (m--) 14 | { 15 | int u, v; 16 | cin >> u >> v; 17 | 18 | adj_list[u].push_back(v); 19 | adj_list[v].push_back(u); 20 | 21 | } 22 | 23 | for(int i=1; i 2 | 3 | using namespace std; 4 | 5 | int main(int argc, char const *argv[]) 6 | { 7 | int n, m; 8 | cin >> n >> m; 9 | 10 | int adj[n + 1][n + 1]; 11 | 12 | while (m--) 13 | { 14 | int u, v; 15 | cin >> u >> v; 16 | adj[u][v] = 1; 17 | adj[v][u] = 1; 18 | } 19 | for (int i = 0; i < n + 1; i++) 20 | { 21 | for (int j = 0; j < n + 1; j++) 22 | { 23 | cout << adj[i][j] << "\t\t"; 24 | } 25 | cout << "\n"; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /Data Structures/Graphs/Traversal/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/Traversal/in.txt: -------------------------------------------------------------------------------- 1 | 6 5 2 | 1 2 3 | 2 3 4 | 3 1 5 | 2 6 6 | 4 5 7 | -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Doubly Linked List/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Data Structures/Linked Lists/Doubly Linked List/.DS_Store -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Singly Linked List/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Data Structures/Linked Lists/Singly Linked List/.DS_Store -------------------------------------------------------------------------------- /Data Structures/Linked Lists/Singly Linked List/SLL.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | An SLL is a type of linked list in which each node consists of only two fields viz., data field and the address field. 3 | The address field is a pointer containing the address of the next node in the list. 4 | */ 5 | #include 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/Stacks/balanced_parentheses.py: -------------------------------------------------------------------------------- 1 | ## Python code to Check for 2 | # balanced parentheses in an expression 3 | 4 | 5 | #Function to check parentheses 6 | def validparentheses(s): 7 | open_brace=["{","[","("] 8 | closed_brace=["}","]",")"] 9 | stack=[] 10 | for i in s: 11 | if i in open_brace: 12 | stack.append(i) 13 | elif i in closed_brace: 14 | p=closed_brace.index(i) 15 | if len(stack)>0 and open_brace[p]==stack[len(stack)-1]: 16 | stack.pop() 17 | else: 18 | return False 19 | if(len(stack)==0): #return true if given expression is balanced 20 | return True 21 | else: 22 | return False #return false is not balanced 23 | 24 | s=input("Enter the Expression to be evaluated:") 25 | if(validparentheses(s)): 26 | print("Expression is Balanced") 27 | else: 28 | print("Expression is Unbalanced") -------------------------------------------------------------------------------- /Data Structures/Trees/binary_tree_right_side_view.py: -------------------------------------------------------------------------------- 1 | # Python program to print right view of Binary Tree 2 | 3 | # A binary tree node 4 | class Node: 5 | # A constructor to create a new Binary tree Node 6 | def __init__(self, val=0, left=None, right=None): 7 | self.val = val 8 | self.left = left 9 | self.right = right 10 | 11 | #Function to print right view of Binary Tree 12 | def rightSideView(root): 13 | ans=[] 14 | # Base Case 15 | if not root: 16 | return ans 17 | else: 18 | l = [] 19 | l.append(root) 20 | while l: 21 | for i in range(len(l)): 22 | node = l.pop(0) 23 | if node.left != None: 24 | l.append(node.left) 25 | if node.right != None: 26 | l.append(node.right) 27 | ans.append(node.val) 28 | return ans 29 | 30 | root = Node(1) 31 | root.left = Node(2) 32 | root.right = Node(3) 33 | root.left.left = Node(None) 34 | root.left.right = Node(5) 35 | root.right.left = Node(None) 36 | root.right.right = Node(4) 37 | 38 | print(rightSideView(root)) 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /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 | }; -------------------------------------------------------------------------------- /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 | } -------------------------------------------------------------------------------- /Divide and Conquer/Powerofnumber.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | using namespace std; 5 | int powerofnumber(int a,int n) 6 | {int mid=0,c=0,b=0; 7 | if(n==1) 8 | { 9 | return a; 10 | } 11 | else 12 | { 13 | mid=n/2; 14 | b=powerofnumber(a,mid); 15 | c=b*b; 16 | if(n%2==0) 17 | { 18 | return c; 19 | } 20 | else 21 | { 22 | return a*c; 23 | } 24 | } 25 | } 26 | int main() 27 | { int num=0,ans=0,power=0; 28 | cout<<"Power of n element\n"; 29 | cout<<"\nEnter the Number\t=\t";cin>>num; 30 | cout<<"Enter the power\t=\t";cin>>power; 31 | ans= powerofnumber(num,power); 32 | cout<<"Answer\t=\t"< 8 | using namespace std; 9 | int main() 10 | { 11 | int n; 12 | cin >> n; // it represent the number of days 13 | int arr[n]; // this array contains the prices of stock on that day 14 | for (int i = 0; i < n; i++) 15 | cin >> arr[i]; 16 | int lsf = 9999999; //least so far 17 | int op = 0; //overall profit 18 | int pist = 0; 19 | for (int i = 0; i < n; i++) 20 | { 21 | if (arr[i] < lsf) 22 | { 23 | lsf = arr[i]; 24 | } 25 | int pist = arr[i] - lsf; // if stock is sold today 26 | if (pist > op) 27 | { 28 | op = pist; 29 | } 30 | } 31 | cout << op << endl; 32 | } 33 | 34 | /* sample input values are 35 | 9 36 | 11 37 | 6 38 | 7 39 | 19 40 | 4 41 | 1 42 | 6 43 | 18 44 | 4 45 | */ 46 | 47 | /*sample output value for the upper input 48 | 17 49 | */ 50 | -------------------------------------------------------------------------------- /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/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/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 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/Josepheus_problem.cpp: -------------------------------------------------------------------------------- 1 | // Given the total number of persons n and a number k, 2 | // which indicates that k-1 persons are skipped and kth person is killed in circle in a fixed direction. 3 | 4 | // The task is to choose the safe place in the circle so that when you perform these operations starting from 1st place in the circle, 5 | // you are the last one remaining and survive. 6 | 7 | #include 8 | using namespace std; 9 | 10 | void solve(vector vec, int index, int k, int &ans) 11 | { // Base Case 12 | if (vec.size() == 1) 13 | { 14 | ans = vec[0]; 15 | return; 16 | } 17 | 18 | index = (index + k) % vec.size(); // covering the case when index overflows the array. 19 | vec.erase(vec.begin() + index); // removing the Kth element 20 | solve(vec, index, k, ans); // Recursive call 21 | } 22 | 23 | int main() 24 | { 25 | int n = 3, k = 2; 26 | vector v; 27 | k--; 28 | int ans; 29 | for (int i = 1; i <= n; i++) 30 | { 31 | v.push_back(i); 32 | } 33 | solve(v, 0, k, ans); 34 | cout << ans; 35 | return ans; 36 | } -------------------------------------------------------------------------------- /General Questions/Longest_Common_Prefix.py: -------------------------------------------------------------------------------- 1 | #Longest Common Prefix in python 2 | #Implementation of python program to find the longest common prefix amongst the given list of strings. 3 | #If there is no common prefix then returning 0. 4 | 5 | #define the function to evaluate the longest common prefix 6 | def longestCommonPrefix(s): 7 | p = '' #declare an empty string 8 | for i in range(len(min(s, key=len))): 9 | f = s[0][i] 10 | for j in s[1:]: 11 | if j[i] != f: 12 | return p 13 | p += f 14 | return p #return the longest common prefix 15 | 16 | 17 | n = int(input("Enter the number of names in list for input:")) 18 | print("Enter the Strings:") 19 | s = [input() for i in range(n)] 20 | if(longestCommonPrefix(s)): 21 | print("The Common Prefix is:" ,longestCommonPrefix(s)) 22 | else: 23 | print("There is no common prefix for the given list of strings, hence the answer is:", 0) -------------------------------------------------------------------------------- /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/Polynomial_Verification.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Aim: Given a polynomial P of a single indeterminate (or variable), x. Also, 3 | given the values of x and k. The task is to verify if P(x) = k. 4 | 5 | ''' 6 | 7 | # taking the space separated input 8 | x_and_k = input().split() 9 | # the very first number denotes 'x' 10 | x = int(x_and_k[0]) 11 | # eval is used to evaluate any expression 12 | # here if the evaluated expression results in the value of k, it would mean that it is valid 13 | # the value of k is second in the entered string x_and_k, we have selected it using indicing 14 | print(eval(input()) == int(x_and_k[1])) 15 | 16 | ''' 17 | 18 | COMPLEXITY: 19 | 20 | Time Complexity -> O(1) 21 | Space Complexity -> O(1) 22 | 23 | Sample Input: 24 | 1 4 25 | x**3 + x**2 + x + 1 26 | 27 | Sample Output: 28 | True 29 | 30 | Explanation: 31 | x = 1 32 | k = 4 33 | P(x) = x**3 + x**2 + x + 1 34 | P(1) = 1**3 + 1**2 + 1 + 1 35 | = 1 + 1 + 1 + 1 36 | = 4 37 | = k 38 | Hence, the polynomial is a valid one. 39 | 40 | ''' -------------------------------------------------------------------------------- /General Questions/Sorted-array-to-BST.py: -------------------------------------------------------------------------------- 1 | # Python program to convert sorted array into Binary Search Tree 2 | # Definition for a binary tree node. 3 | class Node: 4 | def __init__(self, d): 5 | self.data = d 6 | self.left = None 7 | self.right = None 8 | 9 | def sortedArrayToBST(nums): 10 | if not nums: 11 | return None 12 | 13 | mid = (len(nums)) // 2 14 | 15 | root = Node(nums[mid]) # make the middle element the root 16 | 17 | root.left = sortedArrayToBST(nums[:mid]) # all values < nums[mid] 18 | 19 | root.right = sortedArrayToBST(nums[mid + 1:]) # all values > nums[mid] 20 | return root 21 | 22 | def preOrder(node): # function to print the tree 23 | if not node: 24 | return None 25 | 26 | print(node.data) 27 | preOrder(node.left) 28 | preOrder(node.right) 29 | 30 | # driver program 31 | nums = [5,6,7,8,9,10,11] 32 | root = sortedArrayToBST(nums) 33 | print("PreOrder Traversal of constructed BST ") 34 | preOrder(root) 35 | -------------------------------------------------------------------------------- /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 traversing 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/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/Throw.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 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 | -------------------------------------------------------------------------------- /Hackerrank solutions/30 days Of Code/Day10-BinaryNumbers.c: -------------------------------------------------------------------------------- 1 | /* 2 | Sample Input 1 3 | 4 | 5 5 | Sample Output 1 6 | 7 | 1 8 | Sample Input 2 9 | 10 | 13 11 | Sample Output 2 12 | 13 | 2 14 | 15 | 16 | Input Format 17 | 18 | A single integer,n . 19 | 20 | Output Format 21 | 22 | Print a single base-10 integer that denotes the maximum number of consecutive 1's in the binary representation of n. */ 23 | 24 | 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include 30 | #include 31 | #include 32 | #include 33 | #include 34 | 35 | int main() 36 | { 37 | int n; 38 | scanf("%d",&n); 39 | 40 | int rem = 0; 41 | int curr = 0; 42 | int max = 0; 43 | 44 | 45 | while(n > 0) { 46 | rem = n % 2; 47 | if(rem == 1) { 48 | curr++; 49 | if(curr >= max) { 50 | max = curr; 51 | } 52 | } else { 53 | curr = 0; 54 | } 55 | n = n / 2; 56 | } 57 | 58 | printf("%d\n", max); 59 | 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Hackerrank solutions/30 days Of Code/Day5-Loops.c: -------------------------------------------------------------------------------- 1 | /* Sample Input 2 | 3 | 2 4 | Sample Output 5 | 6 | 2 x 1 = 2 7 | 2 x 2 = 4 8 | 2 x 3 = 6 9 | 2 x 4 = 8 10 | 2 x 5 = 10 11 | 2 x 6 = 12 12 | 2 x 7 = 14 13 | 2 x 8 = 16 14 | 2 x 9 = 18 15 | 2 x 10 = 20 */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | char* readline(); 28 | 29 | 30 | 31 | int main() 32 | { 33 | int i; 34 | scanf("%d",&i); 35 | int n=1; 36 | for(;n<=10;n++) 37 | printf("%d x %d = %d\n",i,n,i*n); 38 | } 39 | -------------------------------------------------------------------------------- /Hackerrank solutions/30 days Of Code/Day6-Let's Review.c: -------------------------------------------------------------------------------- 1 | /* Sample Input 2 | 3 | 2 4 | Hacker 5 | Rank 6 | Sample Output 7 | 8 | Hce akr 9 | Rn ak 10 | 11 | space separates the even indexed characters and odd indexed characters */ 12 | 13 | #include 14 | #include 15 | #include 16 | #include 17 | 18 | int main() { 19 | int n; 20 | scanf("%d",&n);char s[50000]; 21 | for(int i=0;i 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | int main() 22 | { 23 | 24 | int n; int temp; 25 | scanf("%d",&n); 26 | int a[n]; 27 | for(int i=0;i=0;i--) 32 | printf("%d ",a[i]); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Hackerrank solutions/the_minion_game.py: -------------------------------------------------------------------------------- 1 | #Kevin and Stuart want to play the 'The Minion Game'. 2 | 3 | #Game Rules 4 | 5 | #Both players are given the same string S . 6 | #Both players have to make substrings using the letters of the string S. 7 | #Stuart has to make words starting with consonants. 8 | #Kevin has to make words starting with vowels. 9 | #The game ends when both players have made all possible substrings. 10 | 11 | #Scoring 12 | #A player gets +1 point for each occurrence of the substring in the string S. 13 | 14 | #Function to find the winner 15 | def the_minion_game(s): 16 | 17 | vowels = 'AEIOU' 18 | kevin = 0 19 | stuart = 0 20 | for i in range(len(s)): 21 | if s[i] in vowels: 22 | kevin += (len(s)-i) 23 | else: 24 | stuart += (len(s)-i) 25 | 26 | if kevin > stuart: 27 | print ("Kevin won the game with score:", kevin) 28 | elif kevin < stuart: 29 | print ("Stuart won the game with score:", stuart) 30 | else: 31 | print ("Draw") 32 | 33 | 34 | s = input("Enter the String: ") 35 | the_minion_game(s) -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /Library/Java/Screenshot 2021-07-12 121030.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/Screenshot 2021-07-12 121030.png -------------------------------------------------------------------------------- /Library/Java/Screenshot 2021-07-12 132104.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/Screenshot 2021-07-12 132104.png -------------------------------------------------------------------------------- /Library/Java/Screenshot 2021-07-12 132959.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/Screenshot 2021-07-12 132959.png -------------------------------------------------------------------------------- /Library/Java/photo_2019-07-03_00-02-44.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2019-07-03_00-02-44.jpg -------------------------------------------------------------------------------- /Library/Java/photo_2019-07-20_23-56-04.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2019-07-20_23-56-04.jpg -------------------------------------------------------------------------------- /Library/Java/photo_2020-06-29_16-39-21.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2020-06-29_16-39-21.jpg -------------------------------------------------------------------------------- /Library/Java/photo_2020-08-17_18-03-24.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2020-08-17_18-03-24.jpg -------------------------------------------------------------------------------- /Library/Java/photo_2020-08-29_16-30-42.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2020-08-29_16-30-42.jpg -------------------------------------------------------------------------------- /Library/Java/photo_2020-09-17_13-31-29.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2020-09-17_13-31-29.jpg -------------------------------------------------------------------------------- /Library/Java/photo_2020-09-18_18-24-45.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Library/Java/photo_2020-09-18_18-24-45.jpg -------------------------------------------------------------------------------- /Library/Java/s: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Library/a: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /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< 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/MaxMin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define Max 1000 4 | int main() 5 | { int i=0,n=0,max=0,min=0; 6 | 7 | int a[Max]; 8 | cout<<"Program to find Maximum and Minimum from array element\n"; 9 | cout<<"Enter the size of array\t=\t";cin>>n; 10 | cout<<"Enter array element\n"; 11 | for(i=0;i>a[i]; 14 | } 15 | 16 | max=a[0]; 17 | min=a[0]; 18 | for(i=1;ia[i]) 25 | { 26 | min=a[i]; 27 | } 28 | } 29 | cout<<"Maximum Element\t=\t"<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 map = new HashMap(); 4 | map.put("I",1); 5 | map.put("V",5); 6 | map.put("X",10); 7 | map.put("L",50); 8 | map.put("C",100); 9 | map.put("D",500); 10 | map.put("M",1000); 11 | int sum = 0; 12 | for (int i = 0 ; i < s.length()-1; i++){ 13 | int temp = map.get(s.substring(i,i+1)); 14 | int next = map.get(s.substring(i+1,i+2)); 15 | if (temp < next){ 16 | sum += (next-temp); 17 | } 18 | else{ 19 | sum += temp; 20 | } 21 | } 22 | sum += map.get(s.substring(s.length()-1)); 23 | return sum; 24 | } 25 | } 26 | 27 | // Example Test cases 28 | // Input: s = "IV" 29 | // Output: 4 30 | // 31 | // 32 | // Input: s = "IX" 33 | // Output: 9 34 | -------------------------------------------------------------------------------- /Numbers/RomantoInteger.py: -------------------------------------------------------------------------------- 1 | # To convert Roman numeral to its equivalent integer 2 | 3 | def romanToInt(s): 4 | romanToNum={ 5 | 'I':1, 6 | 'V':5, 7 | 'X':10, 8 | 'L':50, 9 | 'C':100, 10 | 'D':500, 11 | 'M':1000 12 | } 13 | 14 | total=0 15 | i=0 # to iterate through each letter of the roman numeral 16 | 17 | while 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/Sieve-of-Eratosthenes.cpp: -------------------------------------------------------------------------------- 1 | // Sieve of Eratosthenes 2 | //time complexity = O(n* log(logn)) 3 | 4 | #include 5 | #define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); 6 | using namespace std; 7 | typedef long long int ll; 8 | const ll N= 10e6; 9 | vector Prime(N+1,true); 10 | using namespace std; 11 | 12 | void sieve(){ 13 | ll i,j; 14 | Prime[0]=Prime[1]=false; 15 | 16 | //adding this optimization will reduce n/2 computations 17 | //since even no.s are not prime 18 | for(i=2;i 2 | 3 | int main() 4 | { 5 | int number,i,j; 6 | printf("Enter the number\n"); 7 | scanf("%d",&number); 8 | 9 | int primes[number+1]; 10 | 11 | //populating array with naturals numbers 12 | for(i = 2; i<=number; i++) 13 | primes[i] = i; 14 | 15 | i = 2; 16 | while ((i*i) <= number) 17 | { 18 | if (primes[i] != 0) 19 | { 20 | for(j=2; j number) 23 | break; 24 | else 25 | // Instead of deleteing , making elemnets 0 26 | primes[primes[i]*j]=0; 27 | } 28 | } 29 | i++; 30 | } 31 | printf("The prime numbers are\n"); 32 | for(i = 2; i<=number; i++) 33 | { 34 | //If number is not 0 then it is prime 35 | if (primes[i]!=0) 36 | printf("%d\t",primes[i]); 37 | } 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /Numbers/SquareRoot.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | public class SquareRoot 3 | { 4 | /* Time Comeplexity:-O(lg(n)) 5 | Space Complexity:- O(1)**/ 6 | public static void main(String args[])throws IOException 7 | { 8 | InputStreamReader read=new InputStreamReader(System.in); 9 | BufferedReader in=new BufferedReader(read); 10 | System.out.println("Enter your number"); 11 | int n=Integer.parseInt(in.readLine()); 12 | int x=n; 13 | if(x<=1) 14 | System.out.println(x); 15 | int sqrt=x/2; 16 | int quotient=x/sqrt; 17 | while(sqrt>quotient) 18 | { 19 | sqrt=(sqrt+quotient)>>1;//bitwise operator used to make the process faster 20 | quotient=x/sqrt; 21 | } 22 | System.out.println("The square root of the number "+n+" is = "+sqrt); 23 | } 24 | } -------------------------------------------------------------------------------- /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/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 6 | using namespace std; 7 | 8 | // class with a Copy Constructor 9 | class Person{ 10 | private: 11 | string name; 12 | int age; 13 | public: 14 | // Default Constructor 15 | Person(){ 16 | name="abc"; 17 | age=20; 18 | } 19 | // Copy Constructor 20 | Person(const Person &p1){ 21 | name=p1.name; 22 | age=p1.age; 23 | } 24 | void display(){ 25 | cout<<"Name : "< 7 | using namespace std; 8 | 9 | // class with Parameterized Constructor 10 | class Person{ 11 | private: 12 | string name; 13 | int age; 14 | public: 15 | Person(string iname,int iage){ 16 | name=iname; 17 | age=iage; 18 | } 19 | void display(){ 20 | cout<<"Name : "< 7 | using namespace std; 8 | 9 | // class with Destructor 10 | class Person{ 11 | private: 12 | string name; 13 | int age; 14 | public: 15 | Person(string iname,int iage){ 16 | name=iname; 17 | age=iage; 18 | } 19 | void display(){ 20 | cout<<"Name : "< 7 | using namespace std; 8 | 9 | // class with Friend class 10 | class Person{ 11 | private: 12 | string name; 13 | int age; 14 | public: 15 | Person(string iname,int iage){ 16 | name=iname; 17 | age=iage; 18 | } 19 | // class Introduce is a friend of class Person 20 | friend class Introduce; 21 | }; 22 | 23 | // Friend class 24 | class Introduce{ 25 | public: 26 | void display(Person& x){ 27 | cout<<"Name : "< 7 | using namespace std; 8 | 9 | // base class 10 | class Animal{ 11 | public: 12 | void eat(){ 13 | cout<<"I can eat!"< 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 | -------------------------------------------------------------------------------- /Recursion/Last_index_of_element_in_array.cpp: -------------------------------------------------------------------------------- 1 | /*Program to find first index of a number in array*/ 2 | #include 3 | using namespace std; 4 | int lastIndex(int arr[],int n,int x){ 5 | if(n==0){ 6 | return -1; // if size of array is 0 then we return -1 7 | } 8 | int ans=lastIndex(arr+1,n-1,x);//recursion call to the next element of array. 9 | if(ans==-1){ //if we cannot find the element in the remaining part of array 10 | if(arr[0]==x){//We check for 1st element. 11 | return 0; 12 | } 13 | else{ 14 | return -1;//else we return -1 15 | } 16 | } 17 | 18 | 19 | return ans+1; 20 | 21 | } 22 | 23 | int main() { 24 | int n,x,a[200]; 25 | cin>>n; 26 | for(int i=0;i>a[i]; 28 | } 29 | cin>>x; 30 | cout< 3 | using namespace std; 4 | int firstIndex(int arr[],int n,int x){ 5 | if(n==0){ //if size of array is 0 6 | return -1; 7 | } 8 | if(arr[0]==x){ //if the element is found on first index 9 | return 0; 10 | } 11 | int ans=firstIndex(arr+1,n-1,x);//recursion 12 | if(ans==-1){ 13 | return -1; 14 | } 15 | else{ 16 | return ans+1; 17 | } 18 | } 19 | 20 | int main() { 21 | int n,x,a[200]; 22 | cin>>n; 23 | for(int i=0;i>a[i]; 25 | } 26 | cin>>x; 27 | cout< 3 | #include 4 | using namespace std; 5 | void removeduplicates(char input[]){ 6 | if(input[0]=='\0'){ 7 | return ;//if it is empty string 8 | } 9 | if(input[0]==input[1]){//checking for consecutive duplicate 10 | for(int i=0;input[i]!='\0';i++){ 11 | input[i]=input[i+1];//shift to left 12 | } 13 | removeduplicates(input); 14 | }else{ 15 | removeduplicates(input+1); 16 | } 17 | } 18 | 19 | int main() { 20 | char input[1000]; 21 | cin.getline(input,1000); 22 | removeduplicates(input); 23 | cout< 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 | -------------------------------------------------------------------------------- /Searching Algorithms/linear_search.py: -------------------------------------------------------------------------------- 1 | #Linear Search in python 2 | #Linear Search is one of the easiest searching algorithm. The main aim of a searching algorithm is to search for a desired element in the whole array. Linear Search sequentially searches for an element in an array. 3 | #algorithm 4 | #In Linear Search, we start from the 0th index of the array, we compare each element with the key (desired element). 5 | #If the key is same as the element of array ,we return the index of that element. 6 | #If the key does not match any element then ,we return -1. 7 | def search(arr, x): 8 | for i in range(len(arr)): 9 | if arr[i] == x: 10 | return i 11 | return -1 12 | 13 | 14 | n=int(input("Enter Size of array: ")) 15 | arr=[] 16 | print("Enter array elements: ") 17 | for i in range(n): 18 | e=int(input()) 19 | arr.append(e) 20 | x=int(input("Enter element to be searched: ")) 21 | ans=search(arr,x) 22 | if ans==-1: 23 | print("Element not found ") 24 | else: 25 | print("Element found at ",ans) 26 | -------------------------------------------------------------------------------- /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.py: -------------------------------------------------------------------------------- 1 | 2 | #Bubble sort is a sorting algorithm. Sorting algorithms are used to arrange the array in particular order.In,Bubble sort larger elements are pushed at the end of array in each iteration.It works by repeatedly swapping the adjacent elements if they are in wrong order. 3 | 4 | def bubbleSort(a): 5 | n = len(a) 6 | # Traverse through all array elements 7 | 8 | for i in range(n-1): 9 | # Last i elements are already in place 10 | for j in range(0, n-i-1): 11 | 12 | # traverse the array from 0 to n-i-1 13 | # Swap if the element found is greater 14 | # than the next element 15 | if arr[j] > 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/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 variable. 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/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 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 | -------------------------------------------------------------------------------- /Sorting Algorithms/shell_sort.py: -------------------------------------------------------------------------------- 1 | #function to implement the shell sort 2 | def shellsort(arr,n): 3 | 4 | #calculate gap which is half of the length 5 | gap=n//2 6 | 7 | # Do a gapped insertion sort for this gap size. 8 | # The first gap elements a[0..gap-1] are already in gapped 9 | # order keep adding one more element until the entire array 10 | # is gap sorted 11 | while(gap>0): 12 | 13 | #Loop iterating from gap to n-1 14 | for i in range(gap,n): 15 | temp=arr[i] #value in arr[i] is assigned to temporary variable 16 | j=i 17 | 18 | while j>=gap and arr[j-gap]>temp: 19 | arr[j]=arr[j-gap] #value of arr[j-gap] is assigned to arr[j] 20 | j=j-gap 21 | arr[j]=temp #After loop terminates temporary value is assigned to arr[j] 22 | gap=gap//2 23 | 24 | 25 | 26 | n=int(input("Enter the no of elements:")) 27 | arr=list(map(int,input("Enter the elements:").split())) 28 | print("Before Shell Sort") 29 | print(arr) 30 | shellsort(arr,n) 31 | print("After Shell Sort") 32 | print(arr) -------------------------------------------------------------------------------- /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< O(1) 21 | Space Complexity -> O(1) 22 | 23 | Sample Input 1: 24 | 3 25 | Sample Output 1: 26 | 3 27 | Sample Input 2: 28 | SB 29 | Sample Output 2: 30 | Bad String 31 | 32 | Explaination: 33 | '3' as a string can be converted into the integer 3, whereas SB can't be 34 | converted to an integer hence the 'except' block is executed and 'Bad String' 35 | is printed. 36 | 37 | ''' -------------------------------------------------------------------------------- /Strings/Capitalizing.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Aim: To replace the first character of all the words with their upper case characters. 3 | 4 | ''' 5 | 6 | # Complete the solve function below. 7 | def solve(s): 8 | # splitting the string into words 9 | for x in s[:].split(): 10 | # replacing the character with it's capital form 11 | s = s.replace(x, x.capitalize()) 12 | print('Updated string:',s) 13 | 14 | # getting the input 15 | s = input('Enter string: ') 16 | # calling function to compute the result 17 | solve(s) 18 | 19 | ''' 20 | 21 | COMPLEXITY: 22 | 23 | Time Complexity -> O(N) 24 | Space Complexity -> O(N) 25 | 26 | Sample Input: 27 | Enter string: summer of code 28 | 29 | Sample Output: 30 | Updated string: Summer Of Code 31 | 32 | Explanation: 33 | All the initial characters of the words are capitalized. 34 | 35 | ''' -------------------------------------------------------------------------------- /Strings/Stuck Keyboard/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/Strings/Stuck Keyboard/.DS_Store -------------------------------------------------------------------------------- /Strings/check_if_strings_are_rotation_of_eachother.cpp: -------------------------------------------------------------------------------- 1 | /*************************************************************************** 2 | 3 | A Program to check if strings are rotations of each other or not. 4 | 5 | ***************************************************************************/ 6 | 7 | //SOLUTION (in C++): 8 | 9 | //Suppose there are two strings s1 = "devincept" and s2 = "vinceptde", 10 | 11 | //to check if s2 is rotation of s1, what we can do is, add s1 to itself 12 | 13 | // Assign it to another string s3 = s1 + s1 14 | 15 | //If s2 is a substring of s1, it is rotation of s1. 16 | 17 | 18 | 19 | #include 20 | 21 | using namespace std; 22 | 23 | int main() 24 | { 25 | string s1, s2, s3; 26 | cout<<"Enter the strings"<>s1; 28 | cin>>s2; 29 | s3 = s1 + s1; 30 | if(s3.find(s2) != -1 && s1 != s2)//if s2 is not a substringof s1 then find returns -1 31 | { 32 | cout< freq(128,0); 5 | int si=0,ei=0,n=s.length(),maxlen=INT_MIN,count=0; 6 | while(ei 0) 8 | count++; 9 | 10 | while(count>0){ //if freq of char at ei in the chosen substring is greater than 2 11 | if(freq[s[si++]]-- >1) //iterate till the freq becomes 1 12 | count--; 13 | } 14 | 15 | if(ei-si>maxlen) //each time compare length of obtained substr with unique char to the maximum length 16 | maxlen=ei-si; 17 | } 18 | return maxlen; 19 | } -------------------------------------------------------------------------------- /Strings/removePalindromicSubsequences.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class Main{ 3 | public static int removePalindromeSub(String s) { 4 | 5 | char[] c=new char[s.length()]; 6 | ArrayList al=new ArrayList<>(); 7 | ArrayList bl=new ArrayList<>(); 8 | 9 | for(int i=0;i 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_permutations.cpp: -------------------------------------------------------------------------------- 1 | // Problem: Print all permutations of string 2 | 3 | // Input: ABC 4 | // Output: ABC ACB BAC BCA CBA CAB 5 | 6 | // Concept: Backtracking 7 | 8 | #include 9 | #define fl(i,a,b) for(i=a;i permutations; 14 | 15 | vector permute(string str, ll l, ll r) 16 | { 17 | if(l==r) 18 | { 19 | permutations.push_back(str); 20 | return permutations; 21 | } 22 | for(ll i=l; i<=r; i++) 23 | { 24 | swap(str[l], str[i]); 25 | permute(str, l+1, r); 26 | swap(str[l], str[i]); 27 | } 28 | return permutations; 29 | } 30 | 31 | int main() 32 | { 33 | fast; 34 | 35 | string str; 36 | cin>>str; 37 | 38 | vector ans= permute(str, 0, str.length()-1); 39 | 40 | for(auto x: ans) 41 | cout< 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 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;iVirus Outbreak 10 | 11 | * Prime Game 12 | 13 | * Semi Finals Round: 14 | 15 | * Jazzy And Cricket Balls 16 | -------------------------------------------------------------------------------- /Techgig Code Gladiators 2021/open round/prime_game.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | 3 | T = int(input()) 4 | def isprime(n): 5 | if n<=1: 6 | return False 7 | for i in range(2,n): 8 | if n%i ==0: 9 | return False 10 | return True 11 | 12 | # to run each testcase 13 | while testCase >0: 14 | LR = list(map(int,input().strip().split())) 15 | L = LR[0] 16 | R = LR[1] 17 | f = 0 18 | l = 0 19 | for i in range(L,R+1): 20 | if f ==0: 21 | if isprime(i): 22 | f=i 23 | else: 24 | i = i+1 25 | if l==0: 26 | if isprime(R): 27 | l=R 28 | else: 29 | R -=1 30 | if f!=0 and l!=0: 31 | break 32 | 33 | if f!=0 and l!=0: 34 | print(l-f) 35 | else: 36 | print(-1) 37 | 38 | T -=1 39 | 40 | main() 41 | -------------------------------------------------------------------------------- /Techgig Code Gladiators 2021/open round/virus_outbreak.py: -------------------------------------------------------------------------------- 1 | 2 | def isSubsequence(V,B): 3 | list_v = [] 4 | list_b = [] 5 | for c in V: 6 | list_v.append(c) 7 | 8 | for j in B: 9 | list_b.append(j) 10 | 11 | vindex = 0 12 | bindex = 0 13 | while vindex < len(list_v) and bindex < len(list_b): 14 | if list_v[vindex] == list_b[bindex]: 15 | bindex += 1 16 | vindex += 1 17 | 18 | if bindex == len(list_b): 19 | return True 20 | return False 21 | 22 | V = str(input()) 23 | N = int(input()) 24 | for i in range(N): 25 | B = str(input()) 26 | result = isSubsequence(V,B) 27 | if result == True: 28 | print("POSITIVE") 29 | else: 30 | -------------------------------------------------------------------------------- /Techgig Code Gladiators 2021/semifinals/JazzyAndCricketBalls.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | #define IO ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); 5 | ll value(ll a){ 6 | 7 | ll count=a; 8 | while(a%2==0){ 9 | a/=2; 10 | count+=a; 11 | } 12 | for(ll i=3;i*i2) count+=1; 22 | 23 | return count; 24 | } 25 | 26 | 27 | int main() 28 | { 29 | /* code */ 30 | IO 31 | 32 | ll a,n,sum=0; 33 | cin>>n; 34 | 35 | for(int i=0;i> a; 38 | sum+= value(a); 39 | } 40 | cout<2: 17 | move+=1 18 | return move 19 | 20 | # input the number of packets 21 | b=int(input()) 22 | # input the number of balls in the packet 23 | j=list(map(int,input().strip().split(" "))) 24 | k=0 25 | # call the function moves for balls in every packet 26 | for w in j: 27 | k+=movess(w) 28 | print(k) 29 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /images/cpqb.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/images/cpqb.jpg -------------------------------------------------------------------------------- /images/devincept.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/smv1999/CompetitiveProgrammingQuestionBank/8b7e0170d2f639754184a51f3536983bb900800a/images/devincept.gif --------------------------------------------------------------------------------