├── 1 - Data Structures.md ├── 1.1 - Binary Search Tree.md ├── 1.2 - Binary Heap.md ├── 1.3 - Trie.java ├── 2 - Algorithms.md ├── 2.1 - Search Algorithms.md ├── 2.2 - Sorting Algorithms.md ├── 2.3 - Tree & Graph Traversal Algorithms.md ├── 3 - OOP.md ├── 4 - Miscellaneous.md ├── Algorithms ├── array │ ├── bitonic_search.py │ ├── count_duplicate.py │ ├── first_and_last_occurence_in_sorted_array.py │ └── majority_element.py ├── backtrack │ ├── __init__.py │ ├── knights_tour.py │ ├── n_queen.py │ ├── rat_in_maze.py │ └── sudoku.py ├── binary_search_tree │ ├── bst.py │ └── lowest_common_ancestor_bst.py ├── binary_tree │ ├── __init__.py │ ├── binary_tree.py │ ├── binary_tree_diameter.py │ ├── binary_tree_to_doubly_link_list.py │ ├── boundary_traversal.py │ ├── check_if_all_leaves_are_at_same_level.py │ ├── check_if_bst.py │ ├── check_if_child_sum_property.py │ ├── check_if_tree_is_complete_tree.py │ ├── check_if_tree_is_subtree_of_another.py │ ├── check_if_tree_is_sumtree.py │ ├── connect_nodes.py │ ├── connect_nodes_extending_level_order_traversal.py │ ├── construct_binary_tree_from_linked_list.py │ ├── construct_special_tree_from_inorder.py │ ├── construct_special_tree_from_preorder.py │ ├── construct_tree_from_inorder_preorder.py │ ├── construct_tree_from_preorder.py │ ├── construct_tree_from_preorder_postorder.py │ ├── construct_tree_from_sorted_array.py │ ├── convert_binary_tree_to_circular_doubly_linked_list.py │ ├── convert_to_children_sum_property.py │ ├── convert_to_sumtree.py │ ├── convert_tree_to_linked_list.py │ ├── count_leaf_nodes.py │ ├── deepest_left_leaf_node.py │ ├── diameter.py │ ├── double_tree.py │ ├── duplicate_subtree_in_binary_tree.py │ ├── extract_leaves_of_binary_tree.py │ ├── find_the_closest_leaf_in_binary_tree.py │ ├── foldable_binary_tree.py │ ├── half_tree.py │ ├── identical_trees.py │ ├── inorder_successor.py │ ├── inorder_without_recursion.py │ ├── is_height_balanced_tree.py │ ├── isomorphic_trees.py │ ├── iterative_postorder_traversal_using_two_stacks.py │ ├── iterative_preorder.py │ ├── iteratively_search_element_in_binary_tree.py │ ├── left_leaves_sum.py │ ├── left_view_of_tree.py │ ├── level_of_node.py │ ├── level_order_traversal.py │ ├── level_order_traversal_line_by_line.py │ ├── lowest_common_ancestor_binary_tree.py │ ├── max_width.py │ ├── max_width_non_recursive.py │ ├── maximum_sum_root_to_leaf_path.py │ ├── mirror_binary_tree.py │ ├── morris_traversal_inorder.py │ ├── morris_traversal_preorder.py │ ├── print_all_ancestors_of_node.py │ ├── print_all_nodes_at_k_distance.py │ ├── print_tree_vertical_order.py │ ├── reverse_alternate_levels.py │ ├── reverse_level_order_traversal.py │ ├── root_to_leaf_path.py │ ├── root_to_leaf_pathsum_equal_to_a_given_number.py │ ├── spiral_order_traversal.py │ └── vertical_sum.py ├── cracking_the_coding_interview │ ├── .DS_Store │ ├── __init__.py │ ├── array_and_string │ │ ├── .DS_Store │ │ ├── README.md │ │ ├── check_permutation_of_palindrome.py │ │ ├── check_permutation_strings.py │ │ ├── isSubstring.py │ │ ├── is_unique_characters.py │ │ ├── oneEditAway.py │ │ ├── rotate_matrix_by_90.py │ │ ├── string_compression.py │ │ ├── urlify.py │ │ └── zeroMatrix.py │ ├── linked_list │ │ ├── README.md │ │ ├── __init__.py │ │ ├── delete_middle_node.py │ │ ├── detect_loop.py │ │ ├── detect_palindrome.py │ │ ├── intersection_linked_lists.py │ │ ├── kth_from_end.py │ │ ├── linked_list.py │ │ ├── partition.py │ │ ├── remove_duplicates.py │ │ └── sum_linked_lists.py │ ├── moderate_problems │ │ ├── intersection.py │ │ ├── smallest_difference.py │ │ └── word_frequencies.py │ ├── recursion_and_dynamic_programming │ │ ├── coins.py │ │ ├── magic_index.py │ │ ├── robot_in_a_grid.py │ │ ├── step_count.py │ │ └── tower_of_hanoi.py │ ├── sorting_helper │ │ ├── __init__.py │ │ └── bubble_sort.py │ ├── stack_and_queue │ │ ├── README.md │ │ ├── queue.py │ │ ├── queue_via_stack.py │ │ ├── sort_stack.py │ │ ├── stack.py │ │ └── stack_min.py │ └── trees_and_graphs │ │ ├── .DS_Store │ │ ├── BSTSequence.py │ │ ├── README.md │ │ ├── __init__.py │ │ ├── adjacency_list_graph.py │ │ ├── binary_search_tree.py │ │ ├── binary_tree.py │ │ ├── build_order.py │ │ ├── check_balanced_tree.py │ │ ├── check_if_bst.py │ │ ├── first_common_ancestor.py │ │ ├── flood_fill.py │ │ ├── graph.py │ │ ├── inorder_successor.py │ │ ├── level_tree.py │ │ ├── linked_list.py │ │ ├── min_heap.py │ │ ├── minimal_tree.py │ │ ├── path_between_two_nodes.py │ │ ├── prims_minimum_spanning_tree.py │ │ ├── queue.py │ │ ├── random_node.py │ │ └── tree.py ├── data_structures │ ├── __init__.py │ ├── abstract_syntax_tree.py │ ├── adjacency_list_graph.py │ ├── binary_search_tree.py │ ├── binary_tree.py │ ├── graph.py │ ├── linked_list.py │ ├── queue.py │ └── stack.py ├── dynamic_programming │ ├── 0_1_knapsack.py │ ├── binomial_coefficient.py │ ├── coin_change.py │ ├── cutting_a_rod.py │ ├── edit_distance.py │ ├── egg_dropping_puzzle.py │ ├── floyd_warshall.py │ ├── largest_independent_set_dynamic.py │ ├── largest_independent_set_recursive.py │ ├── longest_common_subsequence.py │ ├── longest_increasing_subsequence.py │ ├── longest_palindromic_subsequence.py │ ├── matrix_chain_multiplication.py │ ├── max_length_chain_of_pairs.py │ ├── max_square_sub_matrix_all_1.py │ ├── maximum_sum_increasing_subsequence.py │ ├── min_cost_path.py │ ├── minimum_jumps_to_reach_end.py │ ├── nth_stairs_problem.py │ ├── optimal_binary_search_tree.py │ ├── palindromic_partitioning.py │ ├── partition_problem.py │ └── subset_sum.py ├── graph │ ├── .DS_Store │ ├── Boruvka_mst.py │ ├── __init__.py │ ├── algorithms │ │ ├── __init__.py │ │ ├── bellman_ford.py │ │ ├── breadth_first_search.py │ │ ├── depth_first_traversal.py │ │ ├── dijkstra_algorithm.py │ │ ├── hamiltonian_path.py │ │ ├── kruskal_minimum_spanning_tree.py │ │ ├── topological_sort.py │ │ └── union_find_algorithm.py │ ├── check_bipartitie.py │ ├── cycle_detection_in_directed_graph.py │ ├── detect_cycle_direct_graph_using_colors.py │ ├── detect_cycle_in_undirected_graph.py │ ├── detect_cycle_in_undirected_graph_union_find.py │ ├── eulerian_path.py │ ├── graph_coloring_problem.py │ ├── hamiltonian_cycle.py │ ├── iterative_depth_first_traversal.py │ ├── longest_path.py │ ├── min_heap.py │ ├── mother_vertex.py │ ├── strongly_connected_components.py │ └── transitive_closure_of_a_graph.py ├── linked_list │ ├── README.mdown │ ├── __init__.py │ ├── add_two_numbers_in_linked_list.py │ ├── alternate_merge.py │ ├── check_if_linklist_is_palindrome.py │ ├── common_intersection_of_two_linked_list.py │ ├── delete_alternate_nodes.py │ ├── delete_m_after_n.py │ ├── detect_and_remove_loop.py │ ├── find_intersection_of_two_linked_list.py │ ├── initialize.py │ ├── kth_node_from_end.py │ ├── linked_list.py │ ├── reverse_alternate_k_nodes.py │ ├── rotate_linked_list.py │ ├── swap_alternate_nodes.py │ └── swap_k_beginning_and_k_end.py ├── pattern_matching │ ├── kmp_algorithm.py │ └── naive_pattern_search.py ├── practise_2018 │ ├── google.py │ └── merge_sort_linked_list.py ├── random_problems │ ├── LRUCache.py │ ├── alien_dictionary.py │ ├── flatten_dict.py │ ├── isValidSudoku.py │ ├── island_count.py │ ├── n_chocolates.py │ ├── pattern_matching.py │ ├── points_on_a_straight_line.py │ ├── smallest_permutation_larger_than_original_number.py │ └── smallest_sequence_with_given_primes.py ├── searching │ ├── __init__.py │ ├── binary_search.py │ └── ternary_search.py ├── sorting │ ├── __init__.py │ ├── bubble_sort.py │ ├── bucket_sort.py │ ├── counting_sort.py │ ├── heap_sort.py │ ├── insertion_sort.py │ ├── merge_sort.py │ ├── quick_sort.py │ ├── radix_sort.py │ └── selection_sort.py └── string │ ├── anagram.py │ ├── check_if_string_formed_from_interleavings.py │ ├── check_if_strings_are_anagrams.py │ ├── interleavings_of_two_strings.py │ ├── kmp_pattern_searching.py │ ├── longest_common_subsequence.py │ ├── longest_common_substring.py │ ├── longest_palindrome_substring.py │ ├── min_edit_distance.py │ ├── most_occuring_element_in_string.py │ ├── remove_duplicates.py │ └── sentence_reverse.py ├── Company ├── Airbnb │ ├── addTwoNumbers.java │ ├── boggle_game.cpp │ ├── convertSortedArrayToBinarySearchTree.java │ ├── csv_parser.cpp │ ├── file_system.cpp │ ├── find_case_combinations_of_a_string.cpp │ ├── find_median_in_large_file_of_integers.cpp │ ├── hilbert_curve.cpp │ ├── houseRobber.java │ ├── implement_queue_with_fixed_size_of_array.cpp │ ├── ip_to_cidr.cpp │ ├── k_edit_distance.cpp │ ├── list_of_list_iterator.cpp │ ├── meeting_time.cpp │ ├── mergeKSortedLists.java │ ├── minimum_vertices_to_traverse_directed_graph.cpp │ ├── number_of_intersected_rectangles.cpp │ ├── regularExpressionMatching.java │ ├── regular_expression.cpp │ ├── round_prices.cpp │ ├── ten_wizards.cpp │ ├── twoSum.java │ └── validParentheses.java ├── Amazon │ ├── 3Sum.java │ ├── addTwoNumbers.java │ ├── bestTimeToBuyAndSellStock.java │ ├── binaryTreeLevelOrderTraversal.java │ ├── groupAnagrams.java │ ├── kthLargestElementInAnArray.java │ ├── letterCombinationsOfAPhoneNumber.java │ ├── lowestCommonAncestorOfABinaryTree.java │ ├── mergeKSortedLists.java │ ├── numberOfIslands.java │ ├── palindromeLinkedList.java │ ├── productOfArrayExceptSelf.java │ ├── reverseLinkedList.java │ ├── rotateImage.java │ ├── subsets.java │ ├── trappingRainWater.java │ ├── twoSum.java │ ├── validParentheses.java │ ├── validateBinarySearchTree.java │ └── wordBreak.java ├── Company.iml ├── Facebook │ ├── 3Sum.java │ ├── addAndSearchWordDataStructureDesign.java │ ├── addBinary.java │ ├── bestTimeToBuyAndSellStock.java │ ├── binarySearchTreeIterator.java │ ├── binaryTreeLevelOrderTraversal.java │ ├── binaryTreePaths.java │ ├── binaryTreeVerticalOrderTraversal.java │ ├── cloneGraph.java │ ├── combinationSumIV.java │ ├── countAndSay.java │ ├── decodeWays.java │ ├── expressionAddOperators.java │ ├── findTheCelebrity.java │ ├── firstBadVersion.java │ ├── flattenNestedListIterator.java │ ├── groupAnagrams.java │ ├── hammingDistance.java │ ├── implementTrie.java │ ├── inorderSuccessorInBST.java │ ├── insertInterval.java │ ├── integerToEnglishWords.java │ ├── kthLargestElementInAnArray.java │ ├── letterCombinationsOfAPhoneNumber.java │ ├── longestConsecutiveSequence.java │ ├── lowestCommonAncestorOfABinaryTree.java │ ├── maximumSizeSubarraySumEqualsK.java │ ├── meetingRooms.java │ ├── mergeIntervals.java │ ├── mergeKSortedLists.java │ ├── mergeSortedArray.java │ ├── minimumSizeSubarraySum.java │ ├── minimumWindowSubstring.java │ ├── moveZeros.java │ ├── multiplyStrings.java │ ├── numberOfIslands.java │ ├── oneEditDistance.java │ ├── paintHouseII.java │ ├── palindromeLinkedList.java │ ├── pow(x,n).java │ ├── productOfArrayExceptSelf.java │ ├── regularExpressionMatching.java │ ├── removeDuplicatesFromSortedArray.java │ ├── removeInvalidParentheses.java │ ├── reverseLinkedList.java │ ├── romanToInteger.java │ ├── searchInRotatedSortedArray.java │ ├── sortColors.java │ ├── sparseMatrixMultiplication.java │ ├── sqrt(x).java │ ├── subsets.java │ ├── subsetsII.java │ ├── sumOfLeftLeaves.java │ ├── twoSum.java │ ├── validPalindrome.java │ ├── validParentheses.java │ ├── validateBinarySearchTree.java │ ├── wallsAndGates.java │ ├── wordBreak.java │ └── wordSearch.java ├── Google │ ├── 3SumSmaller.java │ ├── androidUnlockPatterns.java │ ├── binarySearchTreeIterator.java │ ├── binaryTreePaths.java │ ├── binaryTreeVerticalOrderTraversal.java │ ├── binaryWatch.java │ ├── bombEnemy.java │ ├── cloneGraph.java │ ├── closestBinarySearchTreeValue.java │ ├── combinationSumIV.java │ ├── decodeString.java │ ├── expressionAddOperators.java │ ├── findTheDifference.java │ ├── flattenNestedListIterator.java │ ├── gameOfLife.java │ ├── generalizedAbbreviation.java │ ├── groupShiftedStrings.java │ ├── guessNumberHigherOrLower.java │ ├── implementTrie.java │ ├── insertInterval.java │ ├── islandPerimeter.java │ ├── letterCombinationsOfAPhoneNumber.java │ ├── loggerRateLimiter.java │ ├── longestConsecutiveSequence.java │ ├── longestSubstringWithAtMostKDistinctCharacters.java │ ├── maximumProductOfWordLengths.java │ ├── mergeIntervals.java │ ├── missingRanges.java │ ├── movingAverageFromDataStream.java │ ├── numberOfIslands.java │ ├── pacificAtlanticWaterFlow.java │ ├── paintFence.java │ ├── plusOneLinkedList.java │ ├── pow(x,n).java │ ├── regularExpressionMatching.java │ ├── reverseVowelsOfAString.java │ ├── sentenceScreenFitting.java │ ├── shortestDistanceFromAllBuildings.java │ ├── strobogrammaticNumber.java │ ├── summaryRanges.java │ ├── trappingRainWater.java │ ├── uniqueWordAbbreviation.java │ ├── utf-8Validation.java │ ├── validParentheses.java │ ├── wallsAndGates.java │ ├── wiggleSort.java │ ├── wordBreak.java │ ├── wordSquares.java │ └── zigzagIterator.java ├── LinkedIn │ ├── binarySearchTreeIterator.java │ ├── binaryTreeLevelOrderTraversal.java │ ├── findTheCelebrity.java │ ├── houseRobber.java │ ├── insertInterval.java │ ├── lowestCommonAncestorOfABinaryTree.java │ ├── maximumDepthOfABinaryTree.java │ ├── maximumProductSubarray.java │ ├── maximumSubarray.java │ ├── mergeIntervals.java │ ├── mergeKSortedLists.java │ ├── minimumWindowSubstring.java │ ├── pow(x,n).java │ ├── productOfArrayExceptSelf.java │ ├── searchInRotatedSortedArray.java │ ├── sparseMatrixMultiplication.java │ ├── symmetricTree.java │ └── twoSum.java ├── Twitter │ ├── flattenNestedListIterator.java │ ├── implementTrie.java │ ├── lowestCommonAncestorOfABinaryTree.java │ ├── mergeIntervals.java │ ├── mergeKSortedLists.java │ ├── multiplyStrings.java │ ├── oneEditDistance.java │ ├── regularExpressionMatching.java │ ├── reverseLinkedList.java │ ├── trappingRainWater.java │ └── validParentheses.java └── Uber │ ├── bestTimeToBuyAndSellStock.java │ ├── cloneGraph.java │ ├── decodeWays.java │ ├── groupAnagrams.java │ ├── groupShiftedStrings.java │ ├── implementTrie.java │ ├── letterCombinationsOfAPhoneNumber.java │ ├── maximumDepthOfABinaryTree.java │ ├── mergeKSortedLists.java │ ├── minimumWindowSubstring.java │ ├── oneEditDistance.java │ ├── palindromePermutation.java │ ├── regularExpressionMatching.java │ ├── reverseLinkedList.java │ ├── romanToInteger.java │ ├── searchInRotatedSortedArray.java │ ├── subsets.java │ ├── twoSum.java │ ├── validPalindrome.java │ └── wordBreak.java ├── CrackingTheCodingInterview ├── Chapter1ArraysAndStrings │ ├── DeleteDups.java │ ├── IsRotation.java │ ├── IsUniqueChars.java │ ├── NthToLast.java │ ├── Permutation.java │ └── ReplaceSpaces.java ├── Chapter2LinkedLists │ ├── DeleteDups.java │ ├── DeleteNode.java │ ├── FindBeginning.java │ ├── IsPalindrome.java │ ├── NthToLast.java │ └── Partition.java ├── Chapter3StacksAndQueues │ ├── BinaryTreeIsBalanced.java │ ├── MyQueue.java │ ├── QueueUsingTwoStacks.java │ ├── SetOfStacks.java │ ├── SortStack.java │ ├── StackWithMin.java │ ├── ThreeStacks.java │ └── TowersOfHanoi.java ├── Chapter4TreesAndGraphs │ ├── BinaryTreeIsBalanced.java │ ├── CreateBinarySearchTree.java │ ├── CreateLinkedListForEachLevel.java │ ├── FindPath.java │ ├── IsSubtree.java │ ├── PrintPaths.java │ └── ValidBinarySearchTree.java ├── Chapter5BitManipulation │ ├── BinaryRepresentation.java │ ├── FindMissingInteger.java │ ├── InsertMIntoN.java │ └── SwapBits.java ├── Chapter7MathematicsAndProbability │ ├── Operations.java │ └── WouldIntersect.java ├── Chapter9RecursionAndDynamicProgramming │ ├── AllPermutations.java │ ├── AllSubsets.java │ ├── EightQueens.java │ ├── MagicIndex.java │ ├── RepresentingNCents.java │ ├── StackBoxes.java │ └── Staircase.java └── CrackingTheCodingInterview.iml ├── HackerRank ├── 2d-array.cpp ├── 3DSurfaceArea.py ├── 3d-surface-area.cpp ├── ACMICPCTeam.py ├── AbsolutePermutation.py ├── AppendAndDelete.py ├── AppleAndOrange.py ├── BeautifulDaysAtTheMovies.py ├── BiggerIsGreater.py ├── BirthdayChocolate.py ├── BonAppetit.py ├── BreakingRecords.py ├── BreautifulTriplets.py ├── CatAndMouse.py ├── CavityMap.py ├── ChocolateFeast.py ├── CircularArrayRotation.py ├── ClimbingTheLeaderboard.py ├── Contests │ └── UniversityCodesprint5 │ │ ├── ArrayTriplets.py │ │ └── ExceedingTheSpeedLimit.py ├── CountingValleys.py ├── CutTheSticks.py ├── DayOfTheProgrammer.py ├── DesignerPDFViewer.py ├── DivisibleSumPairs.py ├── DrawingBook.py ├── ElectronicsShop.py ├── EmasSupercomputer.py ├── Encyption.py ├── EqualizeTheArray.py ├── ExtraLongFactorials.py ├── FairRations.py ├── FindDigits.py ├── FlatlandSpaceStations.py ├── GradingStudents.py ├── HalloweenSale.py ├── HappyLadybugs.py ├── JumpingOnTheClouds.py ├── JumpingTheClouds.py ├── Kangaroo.py ├── LibraryFine.py ├── LisasWorkbook.py ├── MagicSquare.py ├── MagicSquareForming.py ├── ManasaAndStones.py ├── MigratoryBirds.py ├── MiniMaxi.py ├── MinimumDistances.py ├── ModifiedKarpekarNumber.py ├── Non-DivisibleSubset.py ├── OrganizingContainersOfBalls.py ├── PickingNumbers.py ├── QueenAttack.java ├── QueensAttack.py ├── README.md ├── RepeatedString.py ├── SaveThePrisoner.py ├── SequenceEquation.py ├── ServiceLane.py ├── SherlockAndSquares.py ├── SockMerchant.py ├── StrangeCounter.py ├── TaumAndBday.py ├── TheGridSearch.py ├── TheHurdleRace.py ├── TheTimeInWords.py ├── TimeConversion.py ├── ViralAdertising.py ├── a-chessboard-game-1.cpp ├── a-very-big-sum.cpp ├── abbr.cpp ├── absolute-permutation.cpp ├── abstract-classes.cpp ├── acm-icpc-team.cpp ├── alice-and-bobs-silly-game.cpp ├── almost-sorted.cpp ├── an-interesting-game-1.cpp ├── and-xor-or.cpp ├── angry-professor.cpp ├── aorb.cpp ├── append-and-delete.cpp ├── apple-and-orange.cpp ├── arithmetic-expressions.cpp ├── array-rotation-2.cpp ├── array-splitting.cpp ├── arrays_ds.cpp ├── baby-step-giant-step.cpp ├── balanced-parentheses.cpp ├── bear-and-steady-gene.cpp ├── bear-and-workbook.cpp ├── beautiful-3-set.cpp ├── beautiful-binary-string.cpp ├── beautiful-days-at-the-movies.cpp ├── beautiful-pairs.cpp ├── beautiful-path.cpp ├── beautiful-triplets.cpp ├── best-divisor.cpp ├── between-two-sets.cpp ├── big-sorting.cpp ├── bigger-is-greater.cpp ├── bike-racers.cpp ├── binary-search-tree-insertion.cpp ├── binary-search-tree-lowest-common-ancestor.cpp ├── birthday-cake-candles.cpp ├── bob-and-ben.cpp ├── bomber-man.cpp ├── bon-appetit.cpp ├── breaking-best-and-worst-records.cpp ├── bricks-game.cpp ├── caesar-cipher-1.cpp ├── camelcase.cpp ├── castle-on-the-grid.cpp ├── cats-and-a-mouse.cpp ├── cavity-map.cpp ├── chessboard-game-again-1.cpp ├── chocolate-feast.cpp ├── class-vs-instance.cpp ├── climbing-the-leaderboard.cpp ├── closest-numbers.cpp ├── compare-the-triplets.cpp ├── compare-two-linked-lists.cpp ├── components_in_graph.cpp ├── connected-cell-in-a-grid.cpp ├── contacts.cpp ├── correctness-invariant.cpp ├── count-luck.cpp ├── counting-valleys.cpp ├── countingsort1.cpp ├── countingsort2.cpp ├── countingsort3.cpp ├── countingsort4.cpp ├── crossword-puzzle.cpp ├── ctci-connected-cell-in-a-grid.cpp ├── ctci-ice-cream-parlor.cpp ├── ctci-lonely-integer.cpp ├── ctci-making-anagrams.cpp ├── ctci-merge-sort.cpp ├── cube-summation.cpp ├── cut-the-sticks.cpp ├── cut-the-tree.cpp ├── delete-a-node-from-a-linked-list.cpp ├── delete-duplicate-value-nodes-from-a-sorted-linked-list.cpp ├── designer-pdf-viewer.cpp ├── detect-whether-a-linked-list-contains-a-cycle.cpp ├── diagonal-difference.cpp ├── divisible-sum-pairs.cpp ├── dorsey-thief.cpp ├── down-to-zero-ii.cpp ├── drawing-book.cpp ├── dynamic-array.cpp ├── electronics-shop.cpp ├── encryption.cpp ├── equal-stacks.cpp ├── equality-in-a-array.cpp ├── extra-long-factorials.java ├── fair-rations.cpp ├── find-digits.cpp ├── find-median-1.cpp ├── find-median.cpp ├── find-the-merge-point-of-two-joined-linked-lists.cpp ├── find_median_1.cpp ├── flatland-space-stations.cpp ├── flipping-the-matrix.cpp ├── fraudulent-activity-notifications.cpp ├── fun-game1.cpp ├── game-of-stones-1.cpp ├── game-of-two-stacks.cpp ├── game-with-cells.cpp ├── get-the-value-of-the-node-at-a-specific-position-from-the-tail.cpp ├── grading.cpp ├── grid-challenge.cpp ├── gridland-metro.cpp ├── hackerland-radio-transmitters.cpp ├── hackerrank-in-a-string.cpp ├── halloween-sale.cpp ├── happy-ladybugs.cpp ├── hexagonal-grid.cpp ├── hr-city.cpp ├── hyperspace-travel.cpp ├── icecream-parlor.cpp ├── inheritance.cpp ├── insert-a-node-at-a-specific-position-in-a-linked-list.cpp ├── insert-a-node-at-the-head-of-a-linked-list.cpp ├── insert-a-node-at-the-tail-of-a-linked-list.cpp ├── insert-a-node-into-a-sorted-doubly-linked-list.cpp ├── insertion-sort.cpp ├── insertionsort1.cpp ├── insertionsort2.cpp ├── is-binary-search-tree.cpp ├── jesse-and-cookies.cpp ├── johnland.cpp ├── jumping-on-the-clouds-revisited.cpp ├── jumping-on-the-clouds.cpp ├── k-factorization.cpp ├── kangaroo.cpp ├── kaprekar-numbers.cpp ├── kitty-and-katty.cpp ├── knightl-on-chessboard.cpp ├── largest-rectangle.cpp ├── larrys-array.cpp ├── lazy-sorting.cpp ├── leonardo-and-prime.cpp ├── library-fine.cpp ├── linkedin-practice-binary-numbers.cpp ├── linkedin-practice-bitwise-and.cpp ├── linkedin-practice-caesar-cipher.cpp ├── linkedin-practice-divisible-sum-pairs.cpp ├── linkedin-practice-nested-logic.cpp ├── lonely-integer-fill-the-key-line.cpp ├── lonely-integer.cpp ├── lowest-triangle.cpp ├── luck-balance.cpp ├── magic-square-forming.cpp ├── make-it-anagram-mglines.cpp ├── manasa-and-stones.cpp ├── mandragora.cpp ├── marcs-cakewalk.cpp ├── mars-exploration.cpp ├── matrix-rotation-algo.cpp ├── maximise-sum.cpp ├── maximum-element.cpp ├── maximum-perimeter-triangle.cpp ├── median.cpp ├── merge-two-sorted-linked-lists.cpp ├── merging_communities.cpp ├── migratory-birds.cpp ├── mini-max-sum.cpp ├── minimum-absolute-difference-in-an-array.cpp ├── minimum-average-waiting-time.cpp ├── minimum-distances.cpp ├── minimum-loss.cpp ├── misere-nim-1.cpp ├── missing-numbers.cpp ├── most-distant.cpp ├── new-year-chaos.cpp ├── nim-game-1.cpp ├── nimble-game-1.cpp ├── no-prefix-set.cpp ├── non-divisible-subset.cpp ├── organizing-containers-of-balls.cpp ├── p1-paper-cutting.cpp ├── pairs.cpp ├── password-cracker.cpp ├── permutation-equation.cpp ├── picking-numbers.cpp ├── playing_with_number.cpp ├── plus-minus.cpp ├── points-on-a-line.cpp ├── points-on-rectangle.cpp ├── poisonous-plants.cpp ├── poker-nim-1.cpp ├── print-the-elements-of-a-linked-list-in-reverse.cpp ├── print-the-elements-of-a-linked-list.cpp ├── pylons.cpp ├── pythagorean-triple.cpp ├── qheap1.cpp ├── queries-with-fixed-length.cpp ├── queue-using-two-stacks.cpp ├── quicksort1.cpp ├── quicksort2.cpp ├── quicksort3.cpp ├── quicksort4.cpp ├── recursive-digit-sum.cpp ├── reduced-string.cpp ├── repeat-k-sums.cpp ├── repeated-string.cpp ├── reverse-a-doubly-linked-list.cpp ├── reverse-a-linked-list.cpp ├── richie-rich.cpp ├── runningtime.cpp ├── save-the-prisoner.cpp ├── self-balancing-tree.cpp ├── separate-the-numbers.cpp ├── service-lane.cpp ├── sherlock-and-array.cpp ├── sherlock-and-pairs.cpp ├── sherlock-and-squares.cpp ├── sherlock-and-the-beast.cpp ├── sherlock-and-valid-string.cpp ├── sherlock-and-watson.cpp ├── similarpair.cpp ├── simple-array-sum.cpp ├── simple-text-editor.cpp ├── smart-number.cpp ├── sock-merchant.cpp ├── solve-me-first.cpp ├── sparse-arrays.cpp ├── staircase.cpp ├── stone-division-2.cpp ├── stone-division.cpp ├── strange-advertising.cpp ├── strange-code.cpp ├── string-construction.cpp ├── string-similarity.cpp ├── strings-xor.cpp ├── strong-password.cpp ├── sum-vs-xor.cpp ├── swap-nodes-algo.cpp ├── task-scheduling.cpp ├── taum-and-bday.cpp ├── the-birthday-bar.cpp ├── the-chosen-one.cpp ├── the-great-xor.cpp ├── the-hurdle-race.cpp ├── the-power-sum.cpp ├── the-time-in-words.cpp ├── time-conversion.cpp ├── torque-and-development.cpp ├── tower-breakers-1.cpp ├── tower-breakers-again-1.cpp ├── tree-height-of-a-binary-tree.cpp ├── tree-huffman-decoding.cpp ├── tree-inorder-traversal.cpp ├── tree-level-order-traversal.cpp ├── tree-postorder-traversal.cpp ├── tree-preorder-traversal.cpp ├── tree-top-view.cpp ├── truck-tour.cpp ├── tutorial-intro.cpp ├── tutzki-and-lcs.cpp ├── two-characters.cpp ├── utopian-tree.cpp ├── waiter.cpp ├── walking-the-approximate-longest-path.cpp ├── weighted-uniform-string.cpp ├── wet-shark-and-42.cpp ├── whats-next.cpp ├── xor-se.cpp ├── xrange-and-pizza.cpp └── yet-another-minimax-problem.cpp ├── Images ├── BST.png ├── Complete.png ├── Full.png ├── Perfect.png ├── bellman-ford.gif ├── bigO.png ├── bigOmega.png ├── bucketsort.png ├── dfsbfs.gif ├── dijkstra.gif ├── fenwickTree.png ├── graph.png ├── hash.png ├── heap.png ├── kruskal.gif ├── mergesort.gif ├── prim.gif ├── quicksort.gif ├── segmentTree.png ├── theta.png └── trie.png ├── LeetCode ├── Array │ ├── bestTimeToBuyAndSellStock.java │ ├── findTheCelebrity.java │ ├── gameOfLife.java │ ├── increasingTripletSubsequence.java │ ├── insertInterval.java │ ├── longestConsecutiveSequence.java │ ├── maximumProductSubarray.java │ ├── maximumSubarray.java │ ├── mergeIntervals.java │ ├── missingRanges.java │ ├── productOfArrayExceptSelf.java │ ├── rotateImage.java │ ├── searchInRotatedSortedArray.java │ ├── spiralMatrixII.java │ ├── subsets.java │ ├── subsetsII.java │ ├── summaryRanges.java │ ├── wiggleSort.java │ └── wordSearch.java ├── Backtracking │ ├── androidUnlockPatterns.java │ ├── generalizedAbbreviation.java │ └── letterCombinationsOfAPhoneNumber.java ├── BinarySearch │ ├── closestBinarySearchTreeValue.java │ ├── firstBadVersion.java │ ├── guessNumberHigherOrLower.java │ ├── pow(x,n).java │ └── sqrt(x).java ├── BitManipulation │ ├── binaryWatch.java │ ├── countingBits.java │ ├── hammingDistance.java │ ├── maximumProductOfWordLengths.java │ ├── numberOf1Bits.java │ ├── sumOfTwoIntegers.java │ └── utf-8Validation.java ├── BreadthFirstSearch │ ├── binaryTreeLevelOrderTraversal.java │ ├── cloneGraph.java │ ├── pacificAtlanticWaterFlow.java │ ├── removeInvalidParentheses.java │ ├── shortestDistanceFromAllBuildings.java │ ├── symmetricTree.java │ └── wallsAndGates.java ├── DepthFirstSearch │ ├── balancedBinaryTree.java │ ├── battleshipsInABoard.java │ ├── convertSortedArrayToBinarySearchTree.java │ ├── maximumDepthOfABinaryTree.java │ ├── numberOfIslands.java │ ├── populatingNextRightPointersInEachNode.java │ └── sameTree.java ├── Design │ └── zigzagIterator.java ├── DivideAndConquer │ ├── expressionAddOperators.java │ └── kthLargestElementInAnArray.java ├── DynamicProgramming │ ├── bombEnemy.java │ ├── climbingStairs.java │ ├── combinationSumIV.java │ ├── countingBits.java │ ├── editDistance.java │ ├── houseRobber.java │ ├── paintFence.java │ ├── paintHouseII.java │ ├── regularExpressionMatching.java │ ├── sentenceScreenFitting.java │ ├── uniqueBinarySearchTrees.java │ └── wordBreak.java ├── HashTable │ ├── binaryTreeVerticalOrderTraversal.java │ ├── findTheDifference.java │ ├── groupAnagrams.java │ ├── groupShiftedStrings.java │ ├── islandPerimeter.java │ ├── loggerRateLimiter.java │ ├── maximumSizeSubarraySumEqualsK.java │ ├── minimumWindowSubstring.java │ ├── sparseMatrixMultiplication.java │ ├── strobogrammaticNumber.java │ ├── twoSum.java │ └── uniqueWordAbbreviation.java ├── LinkedList │ ├── README.md │ ├── addTwoNumbers.java │ ├── deleteNodeInALinkedList.java │ ├── mergeKSortedLists.java │ ├── palindromeLinkedList.java │ ├── plusOneLinkedList.java │ └── reverseLinkedList.java ├── Queue │ └── movingAverageFromDataStream.java ├── README.md ├── Sort │ ├── meetingRooms.java │ └── meetingRoomsII.java ├── Stack │ ├── binarySearchTreeIterator.java │ ├── decodeString.java │ ├── flattenNestedListIterator.java │ └── trappingRainWater.java ├── String │ ├── README.md │ ├── addBinary.java │ ├── countAndSay.java │ ├── decodeWays.java │ ├── editDistance.java │ ├── integerToEnglishWords.java │ ├── longestPalindrome.java │ ├── longestSubstringWithAtMostKDistinctCharacters.java │ ├── minimumWindowSubstring.java │ ├── multiplyStrings.java │ ├── oneEditDistance.java │ ├── palindromePermutation.java │ ├── reverseVowelsOfAString.java │ ├── romanToInteger.java │ ├── validPalindrome.java │ └── validParentheses.java ├── Tree │ ├── binaryTreeMaximumPathSum.java │ ├── binaryTreePaths.java │ ├── inorderSuccessorInBST.java │ ├── invertBinaryTree.java │ ├── lowestCommonAncestorOfABinaryTree.java │ ├── sumOfLeftLeaves.java │ └── validateBinarySearchTree.java ├── Trie │ ├── addAndSearchWordDataStructureDesign.java │ ├── implementTrie.java │ └── wordSquares.java ├── TwoPointers │ ├── 3Sum.java │ ├── 3SumSmaller.java │ ├── mergeSortedArray.java │ ├── minimumSizeSubarraySum.java │ ├── moveZeros.java │ ├── removeDuplicatesFromSortedArray.java │ ├── reverseString.java │ └── sortColors.java ├── leetcode_01-matrix.cpp ├── leetcode_1-bit-and-2-bit-characters.cpp ├── leetcode_132-pattern.cpp ├── leetcode_2-keys-keyboard.cpp ├── leetcode_24-game.cpp ├── leetcode_3SumSmaller.cpp ├── leetcode_3sum_smaller.cpp ├── leetcode_4-keys-keyboard.cpp ├── leetcode_4sum-ii.cpp ├── leetcode_SudokuSolver.cpp ├── leetcode_accounts-merge.cpp ├── leetcode_add-bold-tag-in-string.cpp ├── leetcode_add-one-row-to-tree.cpp ├── leetcode_add-strings.cpp ├── leetcode_adddigits.cpp ├── leetcode_addtwonumbers.cpp ├── leetcode_alien-dictionary.cpp ├── leetcode_all-oone-data-structure.cpp ├── leetcode_all-paths-from-source-to-target.cpp ├── leetcode_ambiguous-coordinates.cpp ├── leetcode_anagrams.cpp ├── leetcode_arithmetic-slices-ii-subsequence.cpp ├── leetcode_arithmetic-slices.cpp ├── leetcode_arranging-coins.cpp ├── leetcode_array-partition-i.cpp ├── leetcode_assign-cookies.cpp ├── leetcode_average-of-levels-in-binary-tree.cpp ├── leetcode_backspace-string-compare.cpp ├── leetcode_balancedbinarytree.cpp ├── leetcode_base-7.cpp ├── leetcode_baseball-game.cpp ├── leetcode_basic-calculator-ii.cpp ├── leetcode_basic-calculator-iii.cpp ├── leetcode_basic-calculator.cpp ├── leetcode_battleships-in-a-board.cpp ├── leetcode_beautiful-arrangement.cpp ├── leetcode_best-meeting-point.cpp ├── leetcode_best-time-to-buy-and-sell-stock-with-cooldown.cpp ├── leetcode_best-time-to-buy-and-sell-stock.cpp ├── leetcode_besttimetobuyandsellstockII.cpp ├── leetcode_besttimetobuyandsellstockIII.cpp ├── leetcode_binary-gap.cpp ├── leetcode_binary-number-with-alternating-bits.cpp ├── leetcode_binary-search-tree-iterator.cpp ├── leetcode_binary-search.cpp ├── leetcode_binary-tree-inorder-traversal.cpp ├── leetcode_binary-tree-longest-consecutive-sequence-ii.cpp ├── leetcode_binary-tree-maximum-path-sum.cpp ├── leetcode_binary-tree-paths.cpp ├── leetcode_binary-tree-pruning.cpp ├── leetcode_binary-tree-tilt.cpp ├── leetcode_binary-tree-vertical-order-traversal.cpp ├── leetcode_binary-watch.cpp ├── leetcode_binarytreelevelordertraversal.cpp ├── leetcode_binarytreelevelordertraversalII.cpp ├── leetcode_binarytreepreordertraversal.cpp ├── leetcode_binarytreezigzaglevelordertraversal.cpp ├── leetcode_bold-words-in-string.cpp ├── leetcode_bomb-enemy.cpp ├── leetcode_boundary-of-binary-tree.cpp ├── leetcode_brick-wall.cpp ├── leetcode_buddy-strings.cpp ├── leetcode_bulb-switcher.cpp ├── leetcode_bulls-and-cows.cpp ├── leetcode_burst-balloons.cpp ├── leetcode_bus-routes.cpp ├── leetcode_can-i-win.cpp ├── leetcode_can-place-flowers.cpp ├── leetcode_candy.cpp ├── leetcode_car-fleet.cpp ├── leetcode_cheapest-flights-within-k-stops.cpp ├── leetcode_climbing-stairs.cpp ├── leetcode_climbingstairs.cpp ├── leetcode_clone-graph.cpp ├── leetcode_closest-binary-search-tree-value.cpp ├── leetcode_closest-leaf-in-a-binary-tree.cpp ├── leetcode_coin-change-2.cpp ├── leetcode_coin-change.cpp ├── leetcode_coin-path.cpp ├── leetcode_combination-sum-iv.cpp ├── leetcode_combination-sum.cpp ├── leetcode_combinations.cpp ├── leetcode_complex-number-multiplication.cpp ├── leetcode_concatenated-words.cpp ├── leetcode_construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── leetcode_construct-binary-tree-from-preorder-and-postorder-traversal.cpp ├── leetcode_construct-binary-tree-from-string.cpp ├── leetcode_construct-quad-tree.cpp ├── leetcode_construct-string-from-binary-tree.cpp ├── leetcode_construct-the-rectangle.cpp ├── leetcode_container-with-most-water.cpp ├── leetcode_contains-duplicate-ii.cpp ├── leetcode_contains-duplicate-iii.cpp ├── leetcode_contains-duplicate.cpp ├── leetcode_contiguous-array.cpp ├── leetcode_continuous-subarray-sum.cpp ├── leetcode_convert-a-number-to-hexadecimal.cpp ├── leetcode_convert-bst-to-greater-tree.cpp ├── leetcode_convert-sorted-array-to-binary-search-tree.cpp ├── leetcode_convertsortedarraytobinarysearchtree.cpp ├── leetcode_convertsortedlisttobinarysearchtree.cpp ├── leetcode_convex-polygon.cpp ├── leetcode_copy-list-with-random-pointer.cpp ├── leetcode_count-and-say.cpp ├── leetcode_count-numbers-with-unique-digits.cpp ├── leetcode_count-of-smaller-numbers-after-self.cpp ├── leetcode_count-the-repetitions.cpp ├── leetcode_counting-bits.cpp ├── leetcode_couples-holding-hands.cpp ├── leetcode_cracking-the-safe.cpp ├── leetcode_custom-sort-string.cpp ├── leetcode_daily-temperatures.cpp ├── leetcode_data-stream-as-disjoint-intervals.cpp ├── leetcode_decode-string.cpp ├── leetcode_decode-ways.cpp ├── leetcode_delete-node-in-a-bst.cpp ├── leetcode_delete-operation-for-two-strings.cpp ├── leetcode_design-compressed-string-iterator.cpp ├── leetcode_design-hit-counter.cpp ├── leetcode_design-phone-directory.cpp ├── leetcode_design-snake-game.cpp ├── leetcode_design-tic-tac-toe.cpp ├── leetcode_design-twitter.cpp ├── leetcode_detect-capital.cpp ├── leetcode_diagonal-traverse.cpp ├── leetcode_diameter-of-binary-tree.cpp ├── leetcode_domino-and-tromino-tiling.cpp ├── leetcode_edit-distance.cpp ├── leetcode_elimination-game.cpp ├── leetcode_employee-free-time.cpp ├── leetcode_employee-importance.cpp ├── leetcode_encode-and-decode-tinyurl.cpp ├── leetcode_encode-n-ary-tree-to-binary-tree.cpp ├── leetcode_encode-string-with-shortest-length.cpp ├── leetcode_erect-the-fence.cpp ├── leetcode_escape-the-ghosts.cpp ├── leetcode_evaluate-division.cpp ├── leetcode_evaluate-reverse-polish-notation.cpp ├── leetcode_evaluatereversepolishnotation.cpp ├── leetcode_exam-room.cpp ├── leetcode_excel-sheet-column-title.cpp ├── leetcode_expressive-words.cpp ├── leetcode_factorial-trailing-zeroes.cpp ├── leetcode_find-all-anagrams-in-a-string.cpp ├── leetcode_find-all-duplicates-in-an-array.cpp ├── leetcode_find-all-numbers-disappeared-in-an-array.cpp ├── leetcode_find-anagram-mappings.cpp ├── leetcode_find-and-replace-in-string.cpp ├── leetcode_find-bottom-left-tree-value.cpp ├── leetcode_find-duplicate-file-in-system.cpp ├── leetcode_find-duplicate-subtrees.cpp ├── leetcode_find-eventual-safe-states.cpp ├── leetcode_find-first-and-last-position-of-element-in-sorted-array.cpp ├── leetcode_find-k-closest-elements.cpp ├── leetcode_find-k-pairs-with-smallest-sums.cpp ├── leetcode_find-k-th-smallest-pair-distance.cpp ├── leetcode_find-largest-value-in-each-tree-row.cpp ├── leetcode_find-leaves-of-binary-tree.cpp ├── leetcode_find-median-from-data-stream.cpp ├── leetcode_find-mode-in-binary-search-tree.cpp ├── leetcode_find-peak-element.cpp ├── leetcode_find-permutation.cpp ├── leetcode_find-right-interval.cpp ├── leetcode_find-smallest-letter-greater-than-target.cpp ├── leetcode_find-the-closest-palindrome.cpp ├── leetcode_find-the-difference.cpp ├── leetcode_find-the-duplicate-number.cpp ├── leetcode_first-bad-version.cpp ├── leetcode_first-missing-positive.cpp ├── leetcode_first-unique-character-in-a-string.cpp ├── leetcode_fizzbuzz.cpp ├── leetcode_flatten-2d-vector.cpp ├── leetcode_flatten-nested-list-iterator.cpp ├── leetcode_flattenbinarytreetolinkedlist.cpp ├── leetcode_flip-game-ii.cpp ├── leetcode_flipgame.cpp ├── leetcode_flipping-an-image.cpp ├── leetcode_flood-fill.cpp ├── leetcode_fraction-addition-and-subtraction.cpp ├── leetcode_fraction-to-recurring-decimal.cpp ├── leetcode_freedom-trail.cpp ├── leetcode_friend-circles.cpp ├── leetcode_frog-jump.cpp ├── leetcode_game-of-life.cpp ├── leetcode_gas-station.cpp ├── leetcode_gasstation.cpp ├── leetcode_generalized-abbreviation.cpp ├── leetcode_generate-parentheses.cpp ├── leetcode_goat-latin.cpp ├── leetcode_graycode.cpp ├── leetcode_group-anagrams.cpp ├── leetcode_group-shifted-strings.cpp ├── leetcode_guess-number-higher-or-lower.cpp ├── leetcode_hamming-distance.cpp ├── leetcode_happy-number.cpp ├── leetcode_heaters.cpp ├── leetcode_house-robber-ii.cpp ├── leetcode_house-robber-iii.cpp ├── leetcode_house-robber.cpp ├── leetcode_image-overlap.cpp ├── leetcode_image-smoother.cpp ├── leetcode_implement-magic-dictionary.cpp ├── leetcode_increasing-subsequences.cpp ├── leetcode_increasing-triplet-subsequence.cpp ├── leetcode_insert-delete-getrandom-o1-duplicates-allowed.cpp ├── leetcode_insert-delete-getrandom-o1.cpp ├── leetcode_insert-delete-getrandom-o1.java ├── leetcode_insert-into-a-binary-search-tree.cpp ├── leetcode_insert-into-a-cyclic-sorted-list.cpp ├── leetcode_insertionsortlist.cpp ├── leetcode_integer-break.cpp ├── leetcode_integer-replacement.cpp ├── leetcode_integertoroman.cpp ├── leetcode_intersection-of-two-linked-lists.cpp ├── leetcode_ip-to-cidr.cpp ├── leetcode_ipo.cpp ├── leetcode_is-graph-bipartite.cpp ├── leetcode_is-subsequence.cpp ├── leetcode_island-perimeter.cpp ├── leetcode_isomorphic-strings.cpp ├── leetcode_jewels-and-stones.cpp ├── leetcode_judge-route-circle.cpp ├── leetcode_jump-game.cpp ├── leetcode_jumpgame.cpp ├── leetcode_jumpgameII.cpp ├── leetcode_k-diff-pairs-in-an-array.cpp ├── leetcode_k-empty-slots.cpp ├── leetcode_k-similar-strings.cpp ├── leetcode_k-th-smallest-in-lexicographical-order.cpp ├── leetcode_k-th-symbol-in-grammar.cpp ├── leetcode_keyboard-row.cpp ├── leetcode_keys-and-rooms.cpp ├── leetcode_kill-process.cpp ├── leetcode_kth-largest-element-in-a-stream.cpp ├── leetcode_kth-largest-element-in-an-array.cpp ├── leetcode_kth-smallest-element-in-a-bst.cpp ├── leetcode_kth-smallest-element-in-a-sorted-matrix.cpp ├── leetcode_kth-smallest-number-in-multiplication-table.cpp ├── leetcode_largest-bst-subtree.cpp ├── leetcode_largest-divisible-subset.cpp ├── leetcode_largest-number-at-least-twice-of-others.cpp ├── leetcode_largest-number.cpp ├── leetcode_largest-palindrome-product.cpp ├── leetcode_largest-rectangle-in-histogram.cpp ├── leetcode_largest-sum-of-averages.cpp ├── leetcode_largest-triangle-area.cpp ├── leetcode_leaf-similar-trees.cpp ├── leetcode_lengthoflastword.cpp ├── leetcode_letter-combinations-of-a-phone-number.cpp ├── leetcode_lettercombinationofaphonenumber.cpp ├── leetcode_lexicographical-numbers.cpp ├── leetcode_lfu-cache.cpp ├── leetcode_license-key-formatting.cpp ├── leetcode_line-reflection.cpp ├── leetcode_linked-list-components.cpp ├── leetcode_linked-list-random-node.cpp ├── leetcode_linkedlist.cpp ├── leetcode_linkedlistcycleII.cpp ├── leetcode_logger-rate-limiter.cpp ├── leetcode_lonely-pixel-i.cpp ├── leetcode_lonely-pixel-ii.cpp ├── leetcode_longest-absolute-file-path.cpp ├── leetcode_longest-common-prefix.cpp ├── leetcode_longest-consecutive-sequence.cpp ├── leetcode_longest-increasing-subsequence.cpp ├── leetcode_longest-line-of-consecutive-one-in-matrix.cpp ├── leetcode_longest-mountain-in-array.cpp ├── leetcode_longest-palindrome.cpp ├── leetcode_longest-palindromic-subsequence.cpp ├── leetcode_longest-palindromic-substring.cpp ├── leetcode_longest-repeating-character-replacement.cpp ├── leetcode_longest-substring-with-at-least-k-repeating-characters.cpp ├── leetcode_longest-substring-with-at-most-k-distinct-characters.cpp ├── leetcode_longest-substring-with-at-most-two-distinct-characters.cpp ├── leetcode_longest-substring-without-repeating-characters.cpp ├── leetcode_longest-uncommon-subsequence-i.cpp ├── leetcode_longest-uncommon-subsequence-ii.cpp ├── leetcode_longest-univalue-path.cpp ├── leetcode_longest-word-in-dictionary-through-deleting.cpp ├── leetcode_longestcommonprefix.cpp ├── leetcode_lowest-common-ancestor-of-a-binary-search-tree.cpp ├── leetcode_lowest-common-ancestor-of-a-binary-tree.cpp ├── leetcode_lru-cache.cpp ├── leetcode_magic-squares-in-grid.cpp ├── leetcode_magical-string.cpp ├── leetcode_majority-element.cpp ├── leetcode_making-a-large-island.cpp ├── leetcode_matchsticks-to-square.cpp ├── leetcode_max-area-of-island.cpp ├── leetcode_max-chunks-to-make-sorted-ii.cpp ├── leetcode_max-chunks-to-make-sorted.cpp ├── leetcode_max-consecutive-ones-ii.cpp ├── leetcode_max-consecutive-ones.cpp ├── leetcode_max-stack.cpp ├── leetcode_max-sum-of-sub-matrix-no-larger-than-k.cpp ├── leetcode_maximal-square.cpp ├── leetcode_maximize-distance-to-closest-person.cpp ├── leetcode_maximum-average-subarray-i.cpp ├── leetcode_maximum-average-subarray-ii.cpp ├── leetcode_maximum-binary-tree.cpp ├── leetcode_maximum-depth-of-n-ary-tree.cpp ├── leetcode_maximum-distance-in-arrays.cpp ├── leetcode_maximum-frequency-stack.cpp ├── leetcode_maximum-length-of-pair-chain.cpp ├── leetcode_maximum-product-of-three-numbers.cpp ├── leetcode_maximum-product-of-word-lengths.cpp ├── leetcode_maximum-product-subarray.cpp ├── leetcode_maximum-subarray.cpp ├── leetcode_maximum-sum-of-3-non-overlapping-subarrays.cpp ├── leetcode_maximum-vacation-days.cpp ├── leetcode_maximum-width-of-binary-tree.cpp ├── leetcode_maximumdepthofbinarytree.cpp ├── leetcode_median-of-two-sorted-arrays.cpp ├── leetcode_meeting-rooms-ii.cpp ├── leetcode_merge-intervals.cpp ├── leetcode_merge-k-sorted-lists.cpp ├── leetcode_merge-two-binary-trees.cpp ├── leetcode_mergesortedarray.cpp ├── leetcode_min-cost-climbing-stairs.cpp ├── leetcode_min-stack.cpp ├── leetcode_minesweeper.cpp ├── leetcode_mini-parser.cpp ├── leetcode_minimize-max-distance-to-gas-station.cpp ├── leetcode_minimum-absolute-difference-in-bst.cpp ├── leetcode_minimum-cost-to-hire-k-workers.cpp ├── leetcode_minimum-distance-between-bst-nodes.cpp ├── leetcode_minimum-genetic-mutation.cpp ├── leetcode_minimum-height-trees.cpp ├── leetcode_minimum-index-sum-of-two-lists.cpp ├── leetcode_minimum-moves-to-equal-array-elements-ii.cpp ├── leetcode_minimum-moves-to-equal-array-elements.cpp ├── leetcode_minimum-number-of-arrows-to-burst-balloons.cpp ├── leetcode_minimum-path-sum.cpp ├── leetcode_minimum-time-difference.cpp ├── leetcode_minimum-window-subsequence.cpp ├── leetcode_minimum-window-substring.cpp ├── leetcode_minimumdeothofbinarytree.cpp ├── leetcode_missingnumber.cpp ├── leetcode_most-common-word.cpp ├── leetcode_most-frequent-subtree-sum.cpp ├── leetcode_moving-average-from-data-stream.cpp ├── leetcode_my-calendar-i.cpp ├── leetcode_my-calendar-ii.cpp ├── leetcode_my-calendar-iii.cpp ├── leetcode_n-ary-tree-level-order-traversal.cpp ├── leetcode_n-ary-tree-postorder-traversal.cpp ├── leetcode_n-ary-tree-preorder-traversal.cpp ├── leetcode_nested-list-weight-sum-ii.cpp ├── leetcode_nested-list-weight-sum.cpp ├── leetcode_new-21-game.cpp ├── leetcode_next-closest-time.cpp ├── leetcode_next-greater-element-i.cpp ├── leetcode_next-greater-element-ii.cpp ├── leetcode_next-greater-element-iii.cpp ├── leetcode_next-permutation.cpp ├── leetcode_nimgame.cpp ├── leetcode_non-decreasing-array.cpp ├── leetcode_non-overlapping-intervals.cpp ├── leetcode_number-complement.cpp ├── leetcode_number-of-1-bits.cpp ├── leetcode_number-of-atoms.cpp ├── leetcode_number-of-boomerangs.cpp ├── leetcode_number-of-longest-increasing-subsequence.cpp ├── leetcode_number-of-matching-subsequences.cpp ├── leetcode_number-of-segments-in-a-string.cpp ├── leetcode_ones-and-zeroes.cpp ├── leetcode_online-stock-span.cpp ├── leetcode_optimal-account-balancing.cpp ├── leetcode_optimal-division.cpp ├── leetcode_out-of-boundary-paths.cpp ├── leetcode_output-contest-matches.cpp ├── leetcode_pacific-atlantic-water-flow.cpp ├── leetcode_paint-house-ii.cpp ├── leetcode_paint-house.cpp ├── leetcode_palindrome-partitioning.cpp ├── leetcode_palindrome-permutation.cpp ├── leetcode_palindromic-substrings.cpp ├── leetcode_partition-equal-subset-sum.cpp ├── leetcode_partition-labels.cpp ├── leetcode_pascalstriangle.cpp ├── leetcode_pascaltriangleII.cpp ├── leetcode_patching-array.cpp ├── leetcode_path-sum-iii.cpp ├── leetcode_pathsum.cpp ├── leetcode_pathsumII.cpp ├── leetcode_peak-index-in-a-mountain-array.cpp ├── leetcode_perfect-number.cpp ├── leetcode_perfect-rectangle.cpp ├── leetcode_perfect-squares.cpp ├── leetcode_permutation-in-string.cpp ├── leetcode_permutationsII.cpp ├── leetcode_plus-one-linked-list.cpp ├── leetcode_plus-one.cpp ├── leetcode_poor-pigs.cpp ├── leetcode_populating-next-right-pointers-in-each-node.cpp ├── leetcode_positions-of-large-groups.cpp ├── leetcode_postordertraverse.cpp ├── leetcode_pour-water.cpp ├── leetcode_power-of-four.cpp ├── leetcode_power-of-three.cpp ├── leetcode_power-of-two.cpp ├── leetcode_powxn.cpp ├── leetcode_predict-the-winner.cpp ├── leetcode_product-of-array-except-self.cpp ├── leetcode_profitable-schemes.cpp ├── leetcode_push-dominoes.cpp ├── leetcode_pyramid-transition-matrix.cpp ├── leetcode_quad-tree-intersection.cpp ├── leetcode_queue-reconstruction-by-height.cpp ├── leetcode_race-car.cpp ├── leetcode_random-flip-matrix.cpp ├── leetcode_random-pick-with-blacklist.cpp ├── leetcode_random-pick-with-weight.cpp ├── leetcode_random-point-in-non-overlapping-rectangles.cpp ├── leetcode_range-addition-ii.cpp ├── leetcode_range-addition.cpp ├── leetcode_range-sum-query-2d-mutable.cpp ├── leetcode_range-sum-query-mutable.cpp ├── leetcode_ransom-note.cpp ├── leetcode_reaching-points.cpp ├── leetcode_rearrange-string-k-distance-apart.cpp ├── leetcode_reconstruct-itinerary.cpp ├── leetcode_reconstruct-original-digits-from-english.cpp ├── leetcode_rectangle-overlap.cpp ├── leetcode_redundant-connection-ii.cpp ├── leetcode_redundant-connection.cpp ├── leetcode_regular-expression-matching.cpp ├── leetcode_relative-ranks.cpp ├── leetcode_remove-9.cpp ├── leetcode_remove-boxes.cpp ├── leetcode_remove-duplicate-letters.cpp ├── leetcode_remove-duplicates-from-sorted-array.cpp ├── leetcode_remove-nth-node-from-end-of-list.cpp ├── leetcode_removeduplicatesfromsortedlist.cpp ├── leetcode_removeelement.cpp ├── leetcode_repeated-string-match.cpp ├── leetcode_repeated-substring-pattern.cpp ├── leetcode_replace-words.cpp ├── leetcode_reshape-the-matrix.cpp ├── leetcode_restoreipaddress.cpp ├── leetcode_reverse-pairs.cpp ├── leetcode_reverse-string-ii.cpp ├── leetcode_reverse-string.cpp ├── leetcode_reverse-vowels-of-a-string.cpp ├── leetcode_reverse-words-in-a-string-iii.cpp ├── leetcode_reverseWordsinaString.cpp ├── leetcode_reverseinteger.cpp ├── leetcode_robot-room-cleaner.cpp ├── leetcode_romantointeger.cpp ├── leetcode_rotate-function.cpp ├── leetcode_rotate-image.cpp ├── leetcode_rotated-digits.cpp ├── leetcode_russian-doll-envelopes.cpp ├── leetcode_sametree.cpp ├── leetcode_search-a-2d-matrix-ii.cpp ├── leetcode_search-in-a-binary-search-tree.cpp ├── leetcode_search-in-a-sorted-array-of-unknown-size.cpp ├── leetcode_search-in-rotated-sorted-array.cpp ├── leetcode_search-insert-position.cpp ├── leetcode_second-minimum-node-in-a-binary-tree.cpp ├── leetcode_sentence-screen-fitting.cpp ├── leetcode_sentence-similarity-ii.cpp ├── leetcode_sentence-similarity.cpp ├── leetcode_sequence-reconstruction.cpp ├── leetcode_serialize-and-deserialize-binary-tree.cpp ├── leetcode_serialize-and-deserialize-bst.cpp ├── leetcode_set-mismatch.cpp ├── leetcode_shopping-offers.cpp ├── leetcode_shortest-completing-word.cpp ├── leetcode_shortest-distance-to-a-character.cpp ├── leetcode_shortest-path-visiting-all-nodes.cpp ├── leetcode_shortest-unsorted-continuous-subarray.cpp ├── leetcode_shortest-word-distance.cpp ├── leetcode_shuffle-an-array.cpp ├── leetcode_single-element-in-a-sorted-array.cpp ├── leetcode_single-number-ii.cpp ├── leetcode_single-number-iii.cpp ├── leetcode_single-number.cpp ├── leetcode_singlenumber.cpp ├── leetcode_sliding-puzzle.cpp ├── leetcode_sliding-window-maximum.cpp ├── leetcode_sliding-window-median.cpp ├── leetcode_smallest-good-base.cpp ├── leetcode_solve-the-equation.cpp ├── leetcode_sort-characters-by-frequency.cpp ├── leetcode_sort-colors.cpp ├── leetcode_sort-transformed-array.cpp ├── leetcode_soup-servings.cpp ├── leetcode_spiralmatrix.cpp ├── leetcode_spiralmatrixII.cpp ├── leetcode_split-array-into-consecutive-subsequences.cpp ├── leetcode_split-array-largest-sum.cpp ├── leetcode_split-array-with-equal-sum.cpp ├── leetcode_split-assembled-strings.cpp ├── leetcode_split-bst.cpp ├── leetcode_sqrtx.cpp ├── leetcode_squirrel-simulation.cpp ├── leetcode_string-compression.cpp ├── leetcode_student-attendance-record-i.cpp ├── leetcode_student-attendance-record-ii.cpp ├── leetcode_subarray-sum-equals-k.cpp ├── leetcode_subsets.cpp ├── leetcode_subtree-of-another-tree.cpp ├── leetcode_sum-of-distances-in-tree.cpp ├── leetcode_sum-of-left-leaves.cpp ├── leetcode_sum-of-two-integers.cpp ├── leetcode_summary-ranges.cpp ├── leetcode_sumrooftoleafnumber.cpp ├── leetcode_super-pow.cpp ├── leetcode_super-washing-machines.cpp ├── leetcode_swap-adjacent-in-lr-string.cpp ├── leetcode_swim-in-rising-water.cpp ├── leetcode_symmetrictree.cpp ├── leetcode_target-sum.cpp ├── leetcode_task-scheduler.cpp ├── leetcode_teemo-attacking.cpp ├── leetcode_ternary-expression-parser.cpp ├── leetcode_the-maze-ii.cpp ├── leetcode_the-maze-iii.cpp ├── leetcode_the-maze.cpp ├── leetcode_third-maximum-number.cpp ├── leetcode_toeplitz-matrix.cpp ├── leetcode_top-k-frequent-elements.cpp ├── leetcode_top-k-frequent-words.cpp ├── leetcode_total-hamming-distance.cpp ├── leetcode_trapping-rain-water-ii.cpp ├── leetcode_trapping-rain-water.cpp ├── leetcode_triangle.cpp ├── leetcode_twosum.cpp ├── leetcode_uglynumber.cpp ├── leetcode_uglynumberII.cpp ├── leetcode_unique-substrings-in-wraparound-string.cpp ├── leetcode_uniquebinarysearchtrees.cpp ├── leetcode_uniquepaths.cpp ├── leetcode_uniquepathsII.cpp ├── leetcode_valid-parentheses.cpp ├── leetcode_valid-perfect-square.cpp ├── leetcode_valid-square.cpp ├── leetcode_valid-word-abbreviation.cpp ├── leetcode_valid-word-square.cpp ├── leetcode_validSudoku.cpp ├── leetcode_validate-binary-search-tree.cpp ├── leetcode_validate-ip-address.cpp ├── leetcode_water-and-jug-problem.cpp ├── leetcode_wiggle-subsequence.cpp ├── leetcode_wigglesort.cpp ├── leetcode_wildcard-matching.cpp ├── leetcode_word-abbreviation.cpp ├── leetcode_word-break-ii.cpp ├── leetcode_word-break.cpp ├── leetcode_word-ladder.cpp ├── leetcode_word-search-ii.cpp ├── leetcode_word-search.cpp ├── leetcode_word-squares.cpp ├── leetcode_wordladder.cpp ├── leetcode_zigzag-conversion.cpp ├── leetcode_zuma-game.cpp └── lintcode_word-count-map-reduce.cpp ├── LintCode ├── README.md ├── lintcode_a+b.cpp ├── lintcode_add-and-search-word.cpp ├── lintcode_add-binary.cpp ├── lintcode_add-digits.cpp ├── lintcode_add-two-numbers.cpp ├── lintcode_all-paths-from-source-to-target.cpp ├── lintcode_anagrams.cpp ├── lintcode_and-and-or.cpp ├── lintcode_assignment-operator-overloading-c-only.cpp ├── lintcode_backpack-ii.cpp ├── lintcode_backpack-vi.cpp ├── lintcode_backpack.cpp ├── lintcode_balanced-binary-tree.cpp ├── lintcode_best-meeting-point.cpp ├── lintcode_best-time-to-buy-and-sell-stock-ii.cpp ├── lintcode_best-time-to-buy-and-sell-stock-iv.cpp ├── lintcode_best-time-to-buy-and-sell-stock.cpp ├── lintcode_binary-representation.java ├── lintcode_binary-search-tree-iterator.cpp ├── lintcode_binary-search.cpp ├── lintcode_binary-tree-inorder-traversal.cpp ├── lintcode_binary-tree-level-order-traversal-ii.cpp ├── lintcode_binary-tree-level-order-traversal.cpp ├── lintcode_binary-tree-maximum-node.cpp ├── lintcode_binary-tree-maximum-path-sum.cpp ├── lintcode_binary-tree-path-sum.cpp ├── lintcode_binary-tree-paths.cpp ├── lintcode_binary-tree-postorder-traversal.cpp ├── lintcode_binary-tree-preorder-traversal.cpp ├── lintcode_binary-tree-serialization.cpp ├── lintcode_binary-tree-zigzag-level-order-traversal.cpp ├── lintcode_building-outline.cpp ├── lintcode_burst-balloons.cpp ├── lintcode_candy.cpp ├── lintcode_cartesian-product.cpp ├── lintcode_check-full-binary-tree.cpp ├── lintcode_classical-binary-search.cpp ├── lintcode_climbing-stairs.cpp ├── lintcode_clone-binary-tree.cpp ├── lintcode_clone-graph.cpp ├── lintcode_closest-binary-search-tree-value.cpp ├── lintcode_coin-change-ii.cpp ├── lintcode_coins-in-a-line-ii.cpp ├── lintcode_coins-in-a-line-iii.cpp ├── lintcode_coins-in-a-line.cpp ├── lintcode_combination-sum-ii.cpp ├── lintcode_combination-sum.cpp ├── lintcode_combinations.cpp ├── lintcode_compare-strings.cpp ├── lintcode_connecting-graph-iii.cpp ├── lintcode_construct-binary-tree-from-inorder-and-postorder-traversal.cpp ├── lintcode_construct-binary-tree-from-preorder-and-inorder-traversal.cpp ├── lintcode_container-with-most-water.cpp ├── lintcode_continuous-subarray-sum-ii.cpp ├── lintcode_continuous-subarray-sum.cpp ├── lintcode_convert-binary-search-tree-to-doubly-linked-list.cpp ├── lintcode_convert-expression-to-polish-notation.cpp ├── lintcode_convert-expression-to-reverse-polish-notation.cpp ├── lintcode_convert-sorted-array-to-binary-search-tree-with-minimal-height.cpp ├── lintcode_convert-sorted-list-to-binary-search-tree.cpp ├── lintcode_copy-books.cpp ├── lintcode_copy-list-with-random-pointer.cpp ├── lintcode_cosine-similarity.cpp ├── lintcode_count-1-in-binary.cpp ├── lintcode_count-and-say.cpp ├── lintcode_count-of-smaller-number-before-itself.cpp ├── lintcode_count-of-smaller-number.cpp ├── lintcode_course-schedule-iii.cpp ├── lintcode_course-schedule.cpp ├── lintcode_create-maximum-number.cpp ├── lintcode_cutting-a-rod.cpp ├── lintcode_data-stream-median.cpp ├── lintcode_decode-ways.cpp ├── lintcode_delete-digits.java ├── lintcode_delete-node-in-the-middle-of-singly-linked-list.cpp ├── lintcode_deliver-the-message.cpp ├── lintcode_dices-sum.cpp ├── lintcode_digit-counts.cpp ├── lintcode_digit-divide-numbers.cpp ├── lintcode_distinct-subsequences.cpp ├── lintcode_divide-two-integers.cpp ├── lintcode_edit-distance.cpp ├── lintcode_evaluate-reverse-polish-notation.cpp ├── lintcode_expression-evaluation.cpp ├── lintcode_expression-tree-build.cpp ├── lintcode_fast-power.cpp ├── lintcode_fibonacci.cpp ├── lintcode_find-anagram-mappings.cpp ├── lintcode_find-minimum-in-rotated-sorted-array-ii.cpp ├── lintcode_find-minimum-in-rotated-sorted-array.cpp ├── lintcode_find-peak-element-ii.cpp ├── lintcode_find-peak-element.cpp ├── lintcode_find-the-connected-component-in-the-undirected-graph.cpp ├── lintcode_find-the-duplicate-number.cpp ├── lintcode_find-the-missing-number.cpp ├── lintcode_find-the-weak-connected-component-in-the-directed-graph.cpp ├── lintcode_first-bad-version.cpp ├── lintcode_first-missing-positive.cpp ├── lintcode_first-position-of-target.cpp ├── lintcode_first-position-unique-character.cpp ├── lintcode_first-unique-number-in-stream.cpp ├── lintcode_fizz-buzz.cpp ├── lintcode_flatten-binary-tree-to-linked-list.cpp ├── lintcode_flatten-list.cpp ├── lintcode_flatten-nested-list-iterator.cpp ├── lintcode_flip-bits.cpp ├── lintcode_four-sum.cpp ├── lintcode_gas-station.cpp ├── lintcode_generate-parentheses.cpp ├── lintcode_graph-valid-tree.cpp ├── lintcode_gray-code.cpp ├── lintcode_greatest-common-divisor.cpp ├── lintcode_guess-number-game.cpp ├── lintcode_happy-number.cpp ├── lintcode_hash-function.cpp ├── lintcode_heapify.java ├── lintcode_house-robber-ii.cpp ├── lintcode_house-robber-iii.cpp ├── lintcode_house-robber.cpp ├── lintcode_identical-binary-tree.cpp ├── lintcode_implement-queue-by-two-stacks.cpp ├── lintcode_implement-trie.cpp ├── lintcode_insert-interval.cpp ├── lintcode_insert-node-in-a-binary-search-tree.cpp ├── lintcode_insertion-sort-list.cpp ├── lintcode_integer-to-roman.cpp ├── lintcode_interleaving-positive-and-negative-numbers.cpp ├── lintcode_interleaving-string.cpp ├── lintcode_intersection-of-arrays.cpp ├── lintcode_intersection-of-two-arrays-ii.cpp ├── lintcode_intersection-of-two-arrays.cpp ├── lintcode_intersection-of-two-linked-lists.cpp ├── lintcode_interval-minimum-number.cpp ├── lintcode_interval-sum-ii.cpp ├── lintcode_interval-sum.cpp ├── lintcode_invert-binary-tree.cpp ├── lintcode_jump-game-ii.cpp ├── lintcode_jump-game.cpp ├── lintcode_k-sum-ii.cpp ├── lintcode_k-sum.cpp ├── lintcode_kill-process.cpp ├── lintcode_kth-largest-element.cpp ├── lintcode_kth-smallest-element-in-a-bst.cpp ├── lintcode_kth-smallest-number-in-sorted-matrix.cpp ├── lintcode_largest-number.cpp ├── lintcode_largest-rectangle-in-histogram.cpp ├── lintcode_last-digit-by-factorial-divide.cpp ├── lintcode_leap-year.cpp ├── lintcode_left-pad.cpp ├── lintcode_length-of-last-word.cpp ├── lintcode_letter-combinations-of-a-phone-number.cpp ├── lintcode_lfu-cache.cpp ├── lintcode_linked-list-cycle-ii.cpp ├── lintcode_linked-list-cycle.cpp ├── lintcode_lintcode_o1-check-power-of-2.cpp ├── lintcode_longest-common-prefix.cpp ├── lintcode_longest-common-subsequence.cpp ├── lintcode_longest-common-substring.cpp ├── lintcode_longest-consecutive-sequence.cpp ├── lintcode_longest-increasing-continuous-subsequence-ii.cpp ├── lintcode_longest-increasing-continuous-subsequence.cpp ├── lintcode_longest-increasing-subsequence.cpp ├── lintcode_longest-palindromic-substring.cpp ├── lintcode_longest-substring-with-at-most-k-distinct-characters.cpp ├── lintcode_longest-substring-without-repeating-characters.cpp ├── lintcode_longest-words.cpp ├── lintcode_lowercase-to-uppercase.cpp ├── lintcode_lowest-common-ancestor.cpp ├── lintcode_lru-cache.cpp ├── lintcode_majority-number-ii.cpp ├── lintcode_majority-number-iii.cpp ├── lintcode_majority-number.cpp ├── lintcode_matrix-zigzag-traversal.cpp ├── lintcode_max-consecutive-ones-ii.cpp ├── lintcode_max-points-on-a-line.cpp ├── lintcode_max-tree.java ├── lintcode_maximal-rectangle.cpp ├── lintcode_maximal-square.cpp ├── lintcode_maximum-and-minimum.cpp ├── lintcode_maximum-average-subarray.cpp ├── lintcode_maximum-depth-of-binary-tree.cpp ├── lintcode_maximum-gap.cpp ├── lintcode_maximum-product-subarray.cpp ├── lintcode_maximum-subarray-difference.cpp ├── lintcode_maximum-subarray-ii.cpp ├── lintcode_maximum-subarray-iii.cpp ├── lintcode_maximum-subarray.cpp ├── lintcode_maximum-weighted-sum-path.cpp ├── lintcode_median-of-two-sorted-arrays.cpp ├── lintcode_median.cpp ├── lintcode_merge-intervals.cpp ├── lintcode_merge-k-sorted-lists.cpp ├── lintcode_merge-number.cpp ├── lintcode_merge-sorted-array-ii.cpp ├── lintcode_merge-sorted-array.cpp ├── lintcode_merge-two-sorted-lists.cpp ├── lintcode_min-stack.cpp ├── lintcode_mini-twitter.cpp ├── lintcode_minimum-adjustment-cost.java ├── lintcode_minimum-depth-of-binary-tree.cpp ├── lintcode_minimum-path-sum.cpp ├── lintcode_minimum-size-subarray-sum.cpp ├── lintcode_minimum-subarray.cpp ├── lintcode_minimum-window-substring.cpp ├── lintcode_mock-hanoi-tower-by-stacks.cpp ├── lintcode_move-zeroes.cpp ├── lintcode_n-queens-ii.cpp ├── lintcode_n-queens.cpp ├── lintcode_next-permutation-ii.cpp ├── lintcode_next-permutation.cpp ├── lintcode_nth-to-last-node-in-list.cpp ├── lintcode_number-of-big-islands.cpp ├── lintcode_number-of-islands.cpp ├── lintcode_nuts-bolts-problem.cpp ├── lintcode_open-the-lock.cpp ├── lintcode_pacific-atlantic-water-flow.cpp ├── lintcode_paint-fence.cpp ├── lintcode_paint-house-ii.cpp ├── lintcode_paint-house.cpp ├── lintcode_palindrome-linked-list.cpp ├── lintcode_palindrome-number.cpp ├── lintcode_palindrome-partitioning-ii.cpp ├── lintcode_parking-lot.cpp ├── lintcode_partition-array-by-odd-and-even.cpp ├── lintcode_partition-array.cpp ├── lintcode_partition-equal-subset-sum.cpp ├── lintcode_partition-list.cpp ├── lintcode_perfect-squares.cpp ├── lintcode_permutation-index-ii.cpp ├── lintcode_permutation-index.cpp ├── lintcode_permutation-sequence.cpp ├── lintcode_permutations-ii.cpp ├── lintcode_permutations.cpp ├── lintcode_plus-one.cpp ├── lintcode_post-office-problem.cpp ├── lintcode_powx-n.cpp ├── lintcode_previous-permutation.cpp ├── lintcode_print-numbers-by-recursion.cpp ├── lintcode_product-of-array-exclude-itself.cpp ├── lintcode_recover-rotated-sorted-array.cpp ├── lintcode_rectangle-area.java ├── lintcode_regular-expression-matching.cpp ├── lintcode_rehashing.cpp ├── lintcode_remove-duplicates-from-sorted-array-ii.cpp ├── lintcode_remove-duplicates-from-sorted-array.cpp ├── lintcode_remove-duplicates-from-sorted-list-ii.cpp ├── lintcode_remove-duplicates-from-sorted-list.cpp ├── lintcode_remove-element.cpp ├── lintcode_remove-linked-list-elements.cpp ├── lintcode_remove-node-in-binary-search-tree.cpp ├── lintcode_remove-nth-node-from-end-of-list.cpp ├── lintcode_reorder-array-to-construct-the-minimum-number.cpp ├── lintcode_reorder-list.cpp ├── lintcode_repeated-dna.cpp ├── lintcode_replace-with-greatest-from-right.cpp ├── lintcode_restore-ip-addresses.cpp ├── lintcode_reverse-3-digit-integer.cpp ├── lintcode_reverse-array.cpp ├── lintcode_reverse-integer.cpp ├── lintcode_reverse-linked-list-ii.cpp ├── lintcode_reverse-linked-list.cpp ├── lintcode_reverse-nodes-in-k-group.cpp ├── lintcode_reverse-order-storage.cpp ├── lintcode_reverse-pairs.cpp ├── lintcode_reverse-words-in-a-string.cpp ├── lintcode_roman-to-integer.cpp ├── lintcode_rotate-image.cpp ├── lintcode_rotate-list.cpp ├── lintcode_rotate-string.cpp ├── lintcode_route-between-two-nodes-in-graph.cpp ├── lintcode_russian-doll-envelopes.cpp ├── lintcode_same-number.cpp ├── lintcode_scramble-string.cpp ├── lintcode_search-a-2d-matrix-ii.cpp ├── lintcode_search-a-2d-matrix.cpp ├── lintcode_search-for-a-range.cpp ├── lintcode_search-in-rotated-sorted-array-ii.cpp ├── lintcode_search-in-rotated-sorted-array.cpp ├── lintcode_search-insert-position.cpp ├── lintcode_search-range-in-binary-search-tree.cpp ├── lintcode_segmemt-tree-build-ii.cpp ├── lintcode_segment-tree-build.cpp ├── lintcode_segment-tree-modify.cpp ├── lintcode_segment-tree-query-ii.cpp ├── lintcode_segment-tree-query.cpp ├── lintcode_set-matrix-zeroes.cpp ├── lintcode_shape-factory.cpp ├── lintcode_shortest-path-in-undirected-graph.cpp ├── lintcode_simplify-path.cpp ├── lintcode_single-number-ii.cpp ├── lintcode_single-number-iii.cpp ├── lintcode_single-number-iv.cpp ├── lintcode_single-number.cpp ├── lintcode_singleton.cpp ├── lintcode_singleton.java ├── lintcode_sliding-window-maximum.cpp ├── lintcode_sliding-window-median.cpp ├── lintcode_sliding-window-unique-elements-sum.cpp ├── lintcode_smallest-subset.cpp ├── lintcode_sort-colors-ii.cpp ├── lintcode_sort-colors.cpp ├── lintcode_sort-integers-ii.cpp ├── lintcode_sort-integers.cpp ├── lintcode_sort-letters-by-case.cpp ├── lintcode_sort-list.cpp ├── lintcode_space-replacement.cpp ├── lintcode_spiral-matrix-ii.cpp ├── lintcode_spiral-matrix.cpp ├── lintcode_sqrtx.cpp ├── lintcode_string-permutation.cpp ├── lintcode_string-to-integeratoi.cpp ├── lintcode_strings-homomorphism.cpp ├── lintcode_strstr.cpp ├── lintcode_subarray-sum-closest.cpp ├── lintcode_subarray-sum-ii.cpp ├── lintcode_subarray-sum.cpp ├── lintcode_submatrix-sum.cpp ├── lintcode_subsets-ii.cpp ├── lintcode_subsets.cpp ├── lintcode_substring-anagrams.cpp ├── lintcode_subtree.cpp ├── lintcode_sum-of-all-subsets.cpp ├── lintcode_super-ugly-number.cpp ├── lintcode_surrounded-regions.cpp ├── lintcode_swap-nodes-in-pairs.cpp ├── lintcode_swap-two-nodes-in-linked-list.cpp ├── lintcode_ternary-expression-parser.cpp ├── lintcode_the-longest-scene.cpp ├── lintcode_the-smallest-difference.cpp ├── lintcode_three-distinct-factors.cpp ├── lintcode_three-sum-closest.cpp ├── lintcode_three-sum.cpp ├── lintcode_top-k-frequent-words-ii.cpp ├── lintcode_top-k-largest-numbers.cpp ├── lintcode_topological-sorting.cpp ├── lintcode_toy-factory.cpp ├── lintcode_trailing-zeros.cpp ├── lintcode_trapping-rain-water.cpp ├── lintcode_triangle.cpp ├── lintcode_tuple-multiply.cpp ├── lintcode_two-strings-are-anagrams.cpp ├── lintcode_two-sum-input-array-is-sorted.cpp ├── lintcode_two-sum.cpp ├── lintcode_ugly-number.cpp ├── lintcode_unique-binary-search-trees-ii.cpp ├── lintcode_unique-binary-search-trees.cpp ├── lintcode_unique-characters.cpp ├── lintcode_unique-paths-ii.cpp ├── lintcode_unique-paths.cpp ├── lintcode_update-bits.cpp ├── lintcode_valid-palindrome.cpp ├── lintcode_valid-parentheses.cpp ├── lintcode_valid-sudoku.cpp ├── lintcode_valid-triangle.cpp ├── lintcode_validate-binary-search-tree.cpp ├── lintcode_walls-and-gates.cpp ├── lintcode_wiggle-sort-ii.cpp ├── lintcode_wiggle-sort.cpp ├── lintcode_wildcard-matching.cpp ├── lintcode_window-sum.cpp ├── lintcode_wood-cut.cpp ├── lintcode_word-break.java ├── lintcode_word-ladder-ii.cpp ├── lintcode_word-ladder.cpp ├── lintcode_word-search-ii.cpp ├── lintcode_word-search.cpp └── lintcode_word-sorting.cpp ├── README.md ├── References.md ├── TODO.md ├── UVa ├── Ants.java ├── Friends.java ├── GoogleIsFeelingLucky.java ├── ICanGuessTheDataStructure.java ├── OpenSource.java ├── PeskyPalindromes.java ├── SplittingNumbers.java ├── TheSettlersOfCatan.java └── VirtualFriends.java ├── assets ├── Bubble-Sort.gif ├── Heap-Sort.gif ├── Insertion-Sort.gif ├── Merge-Sort.png ├── Quicksort.gif └── Selection-Sort.gif └── interviews.iml /Algorithms/array/bitonic_search.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to search a element in bitonic array 4 | 5 | def bitonic_search(arr, low, high): 6 | 7 | if not arr: 8 | return "List is empty" 9 | 10 | if low == high: 11 | return arr[high] 12 | 13 | mid = (low + high)/2 14 | 15 | if arr[mid] < arr[mid+1]: 16 | return bitonic_search(arr, mid+1, high) 17 | elif arr[mid] < arr[mid-1]: 18 | return bitonic_search(arr, low, mid-1) 19 | else: 20 | return arr[mid] 21 | 22 | 23 | arr = [3, 4, 5, 7, 8, 13, 56, 44, 32, 9, 1] 24 | 25 | print bitonic_search(arr, 0, len(arr)-1) -------------------------------------------------------------------------------- /Algorithms/array/count_duplicate.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find the number of duplicate elements in an array 4 | 5 | def count_duplicate(arr): 6 | records = {} 7 | 8 | for a in arr: 9 | if a not in records.keys(): 10 | records[a] = 0 11 | elif records[a] == 0: 12 | records[a] = 1 13 | 14 | count = 0 15 | for record in records.values(): 16 | if record == 1: 17 | count += 1 18 | 19 | return count 20 | 21 | 22 | print count_duplicate("ababbdjhh") 23 | -------------------------------------------------------------------------------- /Algorithms/array/first_and_last_occurence_in_sorted_array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find the first and last occurence of an element in an array 4 | 5 | def find_first(arr, element): 6 | 7 | for i in range(len(arr)): 8 | if arr[i] == element: 9 | return i 10 | 11 | return -1 12 | 13 | def find_last(arr, element): 14 | 15 | index = -1 16 | for i in range(len(arr)): 17 | if arr[i] == element: 18 | if i+1 < len(arr) and arr[i+1] == element: 19 | index = i+1 20 | else: 21 | index = i 22 | break 23 | 24 | return index 25 | 26 | arr = [1, 2, 3, 3, 3, 3, 4, 5, 5, 5, 6, 7, 7] 27 | print find_first(arr, 3) 28 | print find_last(arr, 7) 29 | 30 | -------------------------------------------------------------------------------- /Algorithms/array/majority_element.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Find out the majority element in the array using Moore's algorithm 4 | 5 | # A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element). 6 | 7 | def majority_element(ar): 8 | 9 | count = 1 10 | maj_index = 0 11 | 12 | for i in range(len(ar)): 13 | if count == 0: 14 | maj_index = i 15 | count = 1 16 | if ar[i] == ar[maj_index]: 17 | count += 1 18 | else: 19 | count -= 1 20 | 21 | return ar[maj_index] 22 | 23 | print majority_element([2, 2, 3, 5, 2, 2, 6]) -------------------------------------------------------------------------------- /Algorithms/backtrack/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/backtrack/__init__.py -------------------------------------------------------------------------------- /Algorithms/binary_tree/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/binary_tree/__init__.py -------------------------------------------------------------------------------- /Algorithms/binary_tree/binary_tree_diameter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find the diameter of a binary tree 4 | # i.e. number of nodes in the longest path between two leaves in the tree 5 | 6 | import binary_tree 7 | 8 | def diameter(tree, node): 9 | 10 | if node is None: 11 | return 0 12 | 13 | lh = tree.height(node.left) 14 | rh = tree.height(node.right) 15 | 16 | return max(lh+rh+1, max(diameter(tree, node.left), diameter(tree, node.right))) 17 | 18 | 19 | if __name__=="__main__": 20 | tree = binary_tree.construct_binary_tree() 21 | 22 | print diameter(tree, tree.root) -------------------------------------------------------------------------------- /Algorithms/binary_tree/check_if_all_leaves_are_at_same_level.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Check if all the leaves are at same level 4 | 5 | import binary_tree 6 | 7 | 8 | def check_leaves(root, level, given_level): 9 | if root is None: 10 | return True 11 | 12 | elif root.left is None and root.right is None: 13 | if given_level[0] == 0: 14 | given_level[0] = level 15 | return True 16 | else: 17 | return (level == given_level[0]) 18 | 19 | else: 20 | return check_leaves(root.left, level+1, given_level) and check_leaves(root.right, level+1, given_level) 21 | 22 | 23 | if __name__=="__main__": 24 | tree = binary_tree.construct_binary_tree() 25 | 26 | print check_leaves(tree.root, 1, [0]) -------------------------------------------------------------------------------- /Algorithms/binary_tree/construct_tree_from_sorted_array.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to construct Balanced BST from a sorted list 4 | 5 | import binary_tree 6 | 7 | def construct_tree(list, s_in, e_in): 8 | 9 | if s_in > e_in: 10 | return 11 | 12 | index = (s_in+e_in)/2 13 | 14 | if index < len(list): 15 | root = binary_tree.Node(list[index]) 16 | 17 | root.left = construct_tree(list, s_in, index-1) 18 | root.right = construct_tree(list, index+1, e_in) 19 | 20 | return root 21 | 22 | if __name__=='__main__': 23 | # tree = binary_tree.construct_binary_tree() 24 | root = construct_tree([1,2,3,4,5,6,7], 0, 7) 25 | tree = binary_tree.Tree(root) 26 | tree.inorder(root) -------------------------------------------------------------------------------- /Algorithms/binary_tree/count_leaf_nodes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | ''' 4 | Program to count leaf nodes in a binary tree. 5 | 6 | A node is a leaf node if both left and right child nodes of it are NULL. 7 | 8 | Time Complexity: O(n) 9 | ''' 10 | 11 | import binary_tree 12 | 13 | def count_leaf_nodes(root): 14 | if root is None: 15 | return 0 16 | 17 | if root.left is None and root.right is None: 18 | return 1 19 | 20 | else: 21 | return count_leaf_nodes(root.left) + count_leaf_nodes(root.right) 22 | 23 | if __name__ == "__main__": 24 | tree = binary_tree.construct_binary_tree() 25 | print count_leaf_nodes(tree.root) 26 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/half_tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find half tree 4 | 5 | import binary_tree 6 | 7 | def half_tree(root): 8 | if root is None: 9 | return None 10 | 11 | root.left = half_tree(root.left) 12 | root.right = half_tree(root.right) 13 | 14 | if not root.left and not root.right: 15 | return root 16 | 17 | if not root.left: 18 | return root.right 19 | 20 | if not root.right: 21 | return root.left 22 | 23 | return root 24 | 25 | def inorder(root): 26 | if root is not None: 27 | inorder(root.left) 28 | print root.data 29 | inorder(root.right) 30 | 31 | tree = binary_tree.construct_binary_tree() 32 | root = half_tree(tree.root) 33 | 34 | inorder(root) 35 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/iterative_postorder_traversal_using_two_stacks.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Iterative postorder traversal using two stacks 4 | 5 | import binary_tree 6 | 7 | def postorder(root): 8 | if root is None: 9 | return 10 | 11 | stack1 = [root] 12 | stack2 = [] 13 | 14 | while stack1: 15 | s = stack1.pop(-1) 16 | stack2.append(s) 17 | 18 | if s.left: 19 | stack1.append(s.left) 20 | 21 | if s.right: 22 | stack1.append(s.right) 23 | 24 | while(stack2): 25 | s = stack2.pop(-1) 26 | print s.data 27 | 28 | if __name__ == "__main__": 29 | tree = binary_tree.construct_binary_tree() 30 | postorder(tree.root) 31 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/iterative_preorder.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Iterative preorder traversal 4 | 5 | import binary_tree 6 | 7 | def iterative_preorder(root): 8 | '''Print preorder traversal using stack''' 9 | if root is None: 10 | return 11 | 12 | stack = [root] 13 | curr = root 14 | 15 | while stack: 16 | s = stack.pop(-1) 17 | print s.data 18 | 19 | if s.right: 20 | stack.append(s.right) 21 | 22 | if s.left: 23 | stack.append(s.left) 24 | 25 | if __name__ == "__main__": 26 | tree = binary_tree.construct_binary_tree() 27 | iterative_preorder(tree.root) 28 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/iteratively_search_element_in_binary_tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Iterative search for a key in a binary tree 4 | 5 | import binary_tree 6 | 7 | def search(root, x): 8 | 9 | if root is None: 10 | return 11 | 12 | queue = [root] 13 | 14 | while queue: 15 | 16 | node = queue[0] 17 | 18 | if node.data == x: 19 | return True 20 | 21 | del queue[0] 22 | 23 | if node.left != None: 24 | queue.append(node.left) 25 | if node.right != None: 26 | queue.append(node.right) 27 | 28 | return False 29 | 30 | tree = binary_tree.construct_binary_tree() 31 | 32 | print search(tree.root, 100) 33 | 34 | 35 | 36 | 37 | 38 | 39 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/left_leaves_sum.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find sum of all left leaves 4 | 5 | import binary_tree 6 | 7 | max_sum = 0 8 | 9 | def sum_left_leaves(root): 10 | global max_sum 11 | 12 | if root is None: 13 | return 14 | 15 | if root.left and not root.left.left and not root.left.right: 16 | max_sum += root.left.data 17 | 18 | sum_left_leaves(root.left) 19 | sum_left_leaves(root.right) 20 | 21 | 22 | tree = binary_tree.construct_binary_tree() 23 | sum_left_leaves(tree.root) 24 | print max_sum 25 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/left_view_of_tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to print left view of a tree 4 | 5 | import binary_tree 6 | 7 | max_level = 0 8 | 9 | def left_view_of_tree(node, level): 10 | global max_level 11 | 12 | if node is None: 13 | return 14 | 15 | if max_level < level: 16 | print node.data, level, max_level 17 | max_level = level 18 | 19 | left_view_of_tree(node.left, level+1) 20 | left_view_of_tree(node.right, level+1) 21 | 22 | 23 | if __name__=="__main__": 24 | tree = binary_tree.construct_binary_tree() 25 | print "Printing lef view of tree" 26 | left_view_of_tree(tree.root, 1) -------------------------------------------------------------------------------- /Algorithms/binary_tree/level_of_node.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find level of a node in a binary tree 4 | 5 | import binary_tree 6 | import copy 7 | 8 | def level_of_node(root, node, level): 9 | if root is None: 10 | return 0 11 | 12 | if root.data == node: 13 | return level 14 | 15 | else: 16 | return max(level_of_node(root.left, node, level+1), level_of_node(root.right, node, level+1)) 17 | 18 | 19 | def find_level(): 20 | tree = binary_tree.construct_binary_tree() 21 | level = 0 22 | print level_of_node(tree.root, 8, level+1) 23 | 24 | 25 | if __name__=="__main__": 26 | find_level() -------------------------------------------------------------------------------- /Algorithms/binary_tree/mirror_binary_tree.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find mirror of a binary tree 4 | 5 | import binary_tree 6 | 7 | def mirror(root): 8 | '''Convert the tree to its mirror tree''' 9 | if root is None or (root.left is None and root.right is None): 10 | return 11 | 12 | else: 13 | mirror(root.left) 14 | mirror(root.right) 15 | 16 | temp = root.left 17 | root.left = root.right 18 | root.right = temp 19 | 20 | if __name__=="__main__": 21 | tree = binary_tree.construct_binary_tree() 22 | tree.inorder(tree.root) 23 | # Change the tree to its mirror tree 24 | mirror(tree.root) 25 | print "After changing the tree to its mirror" 26 | tree.inorder(tree.root) 27 | -------------------------------------------------------------------------------- /Algorithms/binary_tree/print_tree_vertical_order.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | '''Print a Binary Tree in Vertical Order''' 4 | 5 | import binary_tree 6 | 7 | def vertical_order_print(root, distance, hash_map): 8 | if root is None: 9 | return 10 | 11 | hash_map.setdefault(distance, []) 12 | hash_map[distance].append(root.data) 13 | 14 | vertical_order_print(root.left, distance-1, hash_map) 15 | vertical_order_print(root.right, distance+1, hash_map) 16 | 17 | if __name__ == "__main__": 18 | tree = binary_tree.construct_binary_tree() 19 | 20 | hash_map = {} 21 | vertical_order_print(tree.root, 0, hash_map) 22 | 23 | print hash_map 24 | -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/.DS_Store -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/__init__.py -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/array_and_string/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/array_and_string/.DS_Store -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/linked_list/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/linked_list/__init__.py -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/moderate_problems/word_frequencies.py: -------------------------------------------------------------------------------- 1 | # find frequency word 2 | # in book 3 | 4 | 5 | def find_frequency(book, word): 6 | count = 0 7 | for each_word in book: 8 | if each_word == word: 9 | count += 1 -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/sorting_helper/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/sorting_helper/__init__.py -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/sorting_helper/bubble_sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | ''' 4 | Problem: Sort a string using bubble sort algorithm 5 | 6 | ''' 7 | def sort(s): 8 | 9 | length = len(s) 10 | s = list(s) 11 | 12 | for i in range(length-1): 13 | for j in range(i+1, length): 14 | if s[i] > s[j]: 15 | s[j], s[i] = s[i], s[j] 16 | 17 | 18 | return s 19 | -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/trees_and_graphs/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/trees_and_graphs/.DS_Store -------------------------------------------------------------------------------- /Algorithms/cracking_the_coding_interview/trees_and_graphs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/cracking_the_coding_interview/trees_and_graphs/__init__.py -------------------------------------------------------------------------------- /Algorithms/data_structures/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/data_structures/__init__.py -------------------------------------------------------------------------------- /Algorithms/dynamic_programming/floyd_warshall.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Floyd Warshall (Dynammic Programmic). Algorithm to find minimum distance between all the vertices 4 | 5 | import sys 6 | 7 | INF = sys.maxint 8 | 9 | def floyd_warshall(graph, V): 10 | soln = graph 11 | 12 | for k in range(V): 13 | for i in range(V): 14 | for j in range(V): 15 | if soln[i][j] > soln[i][k] + soln[k][j] and soln[i][k] != INF and soln[k][j] != INF: 16 | soln[i][j] = soln[i][k] + soln[k][j] 17 | 18 | print soln 19 | 20 | graph = [[0, 5, INF, 10], 21 | [INF, 0, 3, INF], 22 | [INF, INF, 0, 1], 23 | [INF, INF, INF, 0]] 24 | 25 | floyd_warshall(graph, 4) -------------------------------------------------------------------------------- /Algorithms/dynamic_programming/nth_stairs_problem.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # nth stairs problem 4 | 5 | # Recursive implementation 6 | def n_stairs(N): 7 | if N == 0 or N == 1 or N == 2: 8 | return N 9 | 10 | else: 11 | return n_stairs(N-1) + n_stairs(N-2) 12 | 13 | # Implementation through Dynamic Programming 14 | def n_stairs_dynamic(N): 15 | soln = [-1] * N 16 | 17 | soln[0] = 1 18 | soln[1] = 2 19 | 20 | for i in range(2, N): 21 | soln[i] = soln[i-1] + soln[i-2] 22 | 23 | return soln[N-1] 24 | 25 | if __name__ == "__main__": 26 | N = 4 27 | print n_stairs(4) 28 | print n_stairs_dynamic(N) 29 | -------------------------------------------------------------------------------- /Algorithms/graph/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/graph/.DS_Store -------------------------------------------------------------------------------- /Algorithms/graph/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/graph/__init__.py -------------------------------------------------------------------------------- /Algorithms/graph/algorithms/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/graph/algorithms/__init__.py -------------------------------------------------------------------------------- /Algorithms/linked_list/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/linked_list/__init__.py -------------------------------------------------------------------------------- /Algorithms/linked_list/delete_alternate_nodes.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to delete alternate nodes in a linked list 4 | 5 | import initialize 6 | 7 | def delete_alternate(head): 8 | 9 | if not head: 10 | return 11 | 12 | elif not head.nextnode: 13 | return head 14 | 15 | else: 16 | 17 | curr = head 18 | 19 | while (curr and curr.nextnode): 20 | 21 | curr.nextnode = curr.nextnode.nextnode 22 | curr = curr.nextnode 23 | 24 | return head 25 | 26 | lList = initialize.initialize_linked_list() 27 | 28 | head = delete_alternate(lList.head) 29 | 30 | while (head): 31 | print head.data 32 | head = head.nextnode -------------------------------------------------------------------------------- /Algorithms/linked_list/delete_m_after_n.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | import initialize 4 | 5 | # Program to delete m nodes after n nodes 6 | 7 | def delete_m_after_n(head, m, n): 8 | count_n = 0 9 | curr = head 10 | 11 | while ((count_n < n-1) and (curr != None)): 12 | curr = curr.nextnode 13 | count_n += 1 14 | 15 | temp = curr 16 | 17 | count = 0 18 | 19 | while count < m and curr != None: 20 | curr = curr.nextnode 21 | count += 1 22 | 23 | temp.nextnode = curr.nextnode 24 | 25 | 26 | if __name__=="__main__": 27 | ll = initialize.initialize_linked_list() 28 | 29 | delete_m_after_n(ll.head, 2, 3) 30 | 31 | ll.print_list() 32 | -------------------------------------------------------------------------------- /Algorithms/linked_list/rotate_linked_list.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | import initialize 4 | 5 | # Program to rotate a linked list 6 | 7 | def rotate(head): 8 | 9 | if not head: 10 | return 11 | 12 | temp = head 13 | 14 | while (temp.nextnode): 15 | temp = temp.nextnode 16 | 17 | node = head 18 | head = head.nextnode 19 | temp.nextnode = node 20 | temp.nextnode.nextnode = None 21 | 22 | return head 23 | 24 | lList = initialize.initialize_linked_list() 25 | 26 | head = rotate(lList.head) 27 | 28 | while (head): 29 | print head.data 30 | head = head.nextnode -------------------------------------------------------------------------------- /Algorithms/practise_2018/merge_sort_linked_list.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/practise_2018/merge_sort_linked_list.py -------------------------------------------------------------------------------- /Algorithms/random_problems/n_chocolates.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | def nchoc(A, B): 3 | heap = [] 4 | for h in B: 5 | heapq.heappush(heap, -h) 6 | 7 | i = 0 8 | count = 0 9 | k = 0 10 | while (i < A): 11 | if heap: 12 | k = heapq.heappop(heap) 13 | print k 14 | count += k 15 | if k/2 < 0: 16 | heapq.heappush(heap, k/2) 17 | i += 1 18 | 19 | return -count 20 | 21 | 22 | A = 10 23 | B = [ 2147483647, 2000000014, 2147483647 ] 24 | print nchoc(A, B) -------------------------------------------------------------------------------- /Algorithms/searching/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/searching/__init__.py -------------------------------------------------------------------------------- /Algorithms/sorting/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/sorting/__init__.py -------------------------------------------------------------------------------- /Algorithms/sorting/bubble_sort.py: -------------------------------------------------------------------------------- 1 | # coding: UTF-8 2 | 3 | ''' 4 | Bubble Sort 5 | 6 | Bubble sort is based on the idea of repeatedly comparing pairs of adjacent elements and then swapping their positions if 7 | they exist in the wrong order. 8 | 9 | Complexity: O(n*n) 10 | ''' 11 | 12 | def bubble_sort(array): 13 | 14 | for i in range(len(array)-1): 15 | for j in range(i, len(array)): 16 | if array[i] > array[j]: 17 | array[i], array[j] = array[j], array[i] 18 | 19 | return array 20 | -------------------------------------------------------------------------------- /Algorithms/sorting/bucket_sort.py: -------------------------------------------------------------------------------- 1 | # coding: UTF-8 -------------------------------------------------------------------------------- /Algorithms/sorting/counting_sort.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/Algorithms/sorting/counting_sort.py -------------------------------------------------------------------------------- /Algorithms/sorting/insertion_sort.py: -------------------------------------------------------------------------------- 1 | # coding: UTF-8 2 | 3 | ''' 4 | Insertion sort 5 | 6 | Insertion sort is based on the idea that one element from the input elements is consumed in each iteration to find 7 | its correct position i.e. the position to which it belongs in a sorted array. 8 | 9 | Time complexity: O(n*n) 10 | ''' 11 | 12 | def insertion_sort(array): 13 | 14 | for i in range(1, len(array)): 15 | 16 | current_value = array[i] 17 | position = i 18 | 19 | while ( position > 0 and current_value < array[position-1]): 20 | array[position] = array[position-1] 21 | position = position-1 22 | 23 | array[position] = current_value 24 | 25 | return array 26 | -------------------------------------------------------------------------------- /Algorithms/sorting/quick_sort.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | ''' 4 | Quick sort 5 | 6 | Quick sort is based on the divide-and-conquer approach based on the idea of choosing one element as a pivot element 7 | and partitioning the array around it such that: Left side of pivot contains all the elements that are less than the pivot 8 | element Right side contains all elements greater than the pivot. 9 | ''' 10 | 11 | -------------------------------------------------------------------------------- /Algorithms/sorting/radix_sort.py: -------------------------------------------------------------------------------- 1 | # coding: UTF-8 -------------------------------------------------------------------------------- /Algorithms/sorting/selection_sort.py: -------------------------------------------------------------------------------- 1 | # coding: UTF-8 2 | 3 | ''' 4 | Selection sort 5 | 6 | The Selection sort algorithm is based on the idea of finding the minimum or maximum element in an unsorted array 7 | and then putting it in its correct position in a sorted array. 8 | 9 | Complexity: O(n*n) 10 | ''' 11 | 12 | def selection_sort(array): 13 | ''' Sort a list using selection sort algorithm''' 14 | for i, _ in enumerate(array): 15 | # Initialize smallest element and index 16 | index = i 17 | for j in range(i, len(array)): 18 | if array[j] < array[index]: 19 | index = j 20 | 21 | if index != i: 22 | array[i], array[index] = array[index], array[i] 23 | 24 | return array 25 | -------------------------------------------------------------------------------- /Algorithms/string/check_if_string_formed_from_interleavings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to Check if a string is formed by interleaving of two strings 4 | 5 | def check(str, str1, str2, m, n, i): 6 | 7 | if m == 0 and n == 0 and i == 0: 8 | return True 9 | else: 10 | if m > 0 and i > 0 and str[0] == str1[0]: 11 | return check(str[1:], str1[1:], str2, m-1, n, i-1) 12 | 13 | elif n > 0 and i > 0 and str[0] == str2[0]: 14 | return check(str[1:], str1, str2[1:], m, n-1, i-1) 15 | 16 | else: 17 | return False 18 | 19 | a = list("CABD") 20 | b = list("AB") 21 | c = list("CD") 22 | 23 | print check(a, b, c, len(b), len(c), len(a)) 24 | 25 | -------------------------------------------------------------------------------- /Algorithms/string/check_if_strings_are_anagrams.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to check if two strings are anagrams of each other 4 | 5 | def count_characters(str1, count_dict): 6 | 7 | for i in str1: 8 | if i not in count_dict: 9 | count_dict[i] = 1 10 | else: 11 | count_dict[i] += 1 12 | 13 | return count_dict 14 | 15 | def check_anagrams(str1, str2): 16 | 17 | count_dict = count_characters(str1, {}) 18 | 19 | for i in str2: 20 | if i in count_dict and count_dict[i] > 0: 21 | count_dict[i] -= 1 22 | else: 23 | return False 24 | 25 | for i in count_dict: 26 | if count_dict[i] != 0: 27 | return False 28 | 29 | return True 30 | 31 | print check_anagrams("aabbrd", "rabab") -------------------------------------------------------------------------------- /Algorithms/string/interleavings_of_two_strings.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to print all interleavings of two strings 4 | 5 | def print_all_interleavings(str1, str2, str, m, n, i): 6 | 7 | if m == 0 and n == 0: 8 | print "".join(str) 9 | 10 | else: 11 | 12 | if m != 0: 13 | str[i] = str1[0] 14 | print_all_interleavings(str1[1:], str2, str, m-1, n, i+1) 15 | 16 | if n != 0: 17 | str[i] = str2[0] 18 | print_all_interleavings(str1, str2[1:], str, m, n-1, i+1) 19 | 20 | 21 | a = "AB" 22 | b = "CDE" 23 | 24 | c = [""] * (len(a)+len(b)) 25 | 26 | print_all_interleavings(list(a), list(b), c, len(a), len(b), 0) -------------------------------------------------------------------------------- /Algorithms/string/min_edit_distance.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to calculate edit distance between two strings 4 | 5 | # Recursive solution to implement edit distance 6 | def edit_distance(str1, str2, m, n): 7 | if m == 0 and n == 0: 8 | return 0 9 | if m == 0: 10 | return n 11 | if n == 0: 12 | return m 13 | 14 | left = edit_distance(str1, str2, m-1, n) + 1 15 | right = edit_distance(str1, str2, m, n-1) + 1 16 | 17 | corner = edit_distance(str1, str2, m-1, n-1) + (str1[m-1] != str2[n-1]) 18 | 19 | return min(left, min(right, corner)) 20 | 21 | a = list("abc") 22 | b = list("abcd") 23 | print edit_distance(a, b, len(a), len(b)) -------------------------------------------------------------------------------- /Algorithms/string/most_occuring_element_in_string.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to find most/least occuring element in a string 4 | 5 | def count(s, count_dict): 6 | 7 | for i in s: 8 | if i not in count_dict: 9 | count_dict[i] = 1 10 | else: 11 | count_dict[i] += 1 12 | 13 | max_value = 0 14 | max_element = 0 15 | for i in count_dict: 16 | if count_dict[i] > max_value: 17 | max_value = count_dict[i] 18 | max_element = i 19 | 20 | return max_element 21 | 22 | s = "aabbccaaabbmmmlllssssaaa" 23 | 24 | count_dict = {} 25 | 26 | print count(s, count_dict) 27 | -------------------------------------------------------------------------------- /Algorithms/string/remove_duplicates.py: -------------------------------------------------------------------------------- 1 | # -*- coding: UTF-8 -*- 2 | 3 | # Program to remove duplicates from string 4 | 5 | def remove_duplicates(str1): 6 | 7 | scanned_elements = [] 8 | 9 | for i in range(len(str1)): 10 | if str1[i] not in scanned_elements: 11 | scanned_elements.append(str1[i]) 12 | 13 | return "".join(scanned_elements) 14 | 15 | a = list("ddcvvwwfaadsffsqq") 16 | 17 | print remove_duplicates(a) 18 | -------------------------------------------------------------------------------- /Company/Amazon/kthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class Solution { 10 | 11 | public int findKthLargest(int[] nums, int k) { 12 | 13 | int length = nums.length; 14 | Arrays.sort(nums); 15 | return nums[length - k]; 16 | 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /Company/Facebook/hammingDistance.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, calculate the Hamming distance. 4 | 5 | // Note: 6 | // 0 ≤ x, y < 2^31. 7 | 8 | // Example: 9 | 10 | // Input: x = 1, y = 4 11 | 12 | // Output: 2 13 | 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | 19 | // The above arrows point to positions where the corresponding bits are different. 20 | 21 | public class Solution { 22 | 23 | public int hammingDistance(int x, int y) { 24 | 25 | return Integer.bitCount(x ^ y); 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /Company/Facebook/kthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class Solution { 10 | 11 | public int findKthLargest(int[] nums, int k) { 12 | 13 | int length = nums.length; 14 | Arrays.sort(nums); 15 | return nums[length - k]; 16 | 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /Company/Facebook/pow(x,n).java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class Solution { 4 | 5 | public double myPow(double x, int n) { 6 | 7 | if(n == 0) { 8 | 9 | return 1; 10 | 11 | } 12 | 13 | if(Double.isInfinite(x)) { 14 | 15 | return 0; 16 | 17 | } 18 | 19 | if(n < 0) { 20 | 21 | n = -n; 22 | x = 1 / x; 23 | 24 | } 25 | 26 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 27 | 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /Company/Facebook/sqrt(x).java: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | 3 | // Compute and return the square root of x. 4 | 5 | public class Solution { 6 | 7 | public int mySqrt(int x) { 8 | 9 | if(x == 0) return 0; 10 | 11 | int left = 1; 12 | int right = x; 13 | 14 | while(left <= right) { 15 | 16 | int mid = left + (right - left) / 2; 17 | 18 | if(mid == x / mid) return mid; 19 | else if(mid > x / mid) right = mid - 1; 20 | else if(mid < x / mid) left = mid + 1; 21 | 22 | } 23 | 24 | return right; 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /Company/Google/pow(x,n).java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class Solution { 4 | 5 | public double myPow(double x, int n) { 6 | 7 | if(n == 0) { 8 | 9 | return 1; 10 | 11 | } 12 | 13 | if(Double.isInfinite(x)) { 14 | 15 | return 0; 16 | 17 | } 18 | 19 | if(n < 0) { 20 | 21 | n = -n; 22 | x = 1 / x; 23 | 24 | } 25 | 26 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 27 | 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /Company/Google/wiggleSort.java: -------------------------------------------------------------------------------- 1 | // Given an unsorted array nums, reorder it in-place such that nums[0] <= nums[1] >= nums[2] <= nums[3].... 2 | 3 | // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | 5 | public class Solution { 6 | 7 | public void wiggleSort(int[] nums) { 8 | 9 | for(int i = 1; i < nums.length; i++) { 10 | 11 | int current = nums[i - 1]; 12 | 13 | if((i % 2 == 1) == (current > nums[i])) { 14 | 15 | nums[i - 1] = nums[i]; 16 | nums[i] = current; 17 | 18 | } 19 | 20 | } 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Company/LinkedIn/maximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class Solution { 15 | 16 | public int maxDepth(TreeNode root) { 17 | 18 | if(root == null) return 0; 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /Company/LinkedIn/pow(x,n).java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class Solution { 4 | 5 | public double myPow(double x, int n) { 6 | 7 | if(n == 0) { 8 | 9 | return 1; 10 | 11 | } 12 | 13 | if(Double.isInfinite(x)) { 14 | 15 | return 0; 16 | 17 | } 18 | 19 | if(n < 0) { 20 | 21 | n = -n; 22 | x = 1 / x; 23 | 24 | } 25 | 26 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 27 | 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /Company/Uber/maximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class Solution { 15 | 16 | public int maxDepth(TreeNode root) { 17 | 18 | if(root == null) return 0; 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter1ArraysAndStrings/DeleteDups.java: -------------------------------------------------------------------------------- 1 | //Write code to remove duplicates from an unsorted linked list 2 | 3 | public class RemoveDups { 4 | void deleteDups(LinkedListNode n) { 5 | HashSet set = new HashSet(); 6 | LinkedListNode previous = null; 7 | while(n != null) { 8 | if(set.contains(n.data)) { 9 | previous.next = n.next; 10 | } 11 | else { 12 | set.add(n.data); 13 | previous = n; 14 | } 15 | n = n.next; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter1ArraysAndStrings/IsRotation.java: -------------------------------------------------------------------------------- 1 | // Assume you have a method isSubstring which checks if one word is a isSubstring of another. 2 | // Given two strings, s1 and s2, write code to check if s2 is a rotation of s1 using only 3 | // one call to isSubstring(e.g., "waterbottle" is a rotation of "erbottlewat"). 4 | 5 | public class IsRotation { 6 | public boolean isRotation(String s1, String s2) { 7 | int len = s1.length(); 8 | /*check that s1 and s2 are equal length and not empty */ 9 | if(len == s2.length() && len > 0) { 10 | /* concatenate s1 and s1 within new buffer */ 11 | String s1s1 = s1 + s1; 12 | return isSubstring(s1s1, s2); 13 | } 14 | 15 | return false; 16 | } 17 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter1ArraysAndStrings/IsUniqueChars.java: -------------------------------------------------------------------------------- 1 | //Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? 2 | 3 | public class isUniqueChars { 4 | public boolean isUniqueChars(String str) { 5 | int checker = 0; 6 | for(int i = 0; i < str.length(); i++) { 7 | int val = str.charAt(i) - 'a'; 8 | if((checker & (1 << val)) > 0) { 9 | return false; 10 | } 11 | checker |= (1 << val)); 12 | } 13 | return true; 14 | } 15 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter1ArraysAndStrings/Permutation.java: -------------------------------------------------------------------------------- 1 | // Given two strings, write a metho dto decide if one is a permutation of the other 2 | 3 | public class Permutation { 4 | public boolean permutation(String s, String t) { 5 | if(s.length() != t.length()) { 6 | return false; 7 | } 8 | 9 | int[] letters = new int[256]; 10 | 11 | char[] s_array = s.toCharArray(); 12 | for(char c : s_array) { 13 | letters[c]++; 14 | } 15 | 16 | for(int i = 0; i < t.length(); i++) { 17 | int c = (int)t.charAt(i); 18 | if(--letters[c] < 0) { 19 | return false; 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter2LinkedLists/DeleteDups.java: -------------------------------------------------------------------------------- 1 | //Write code to remove duplicates from an unsorted linked list 2 | 3 | public class RemoveDups { 4 | void deleteDups(LinkedListNode n) { 5 | HashSet set = new HashSet(); 6 | LinkedListNode previous = null; 7 | while(n != null) { 8 | if(set.contains(n.data)) { 9 | previous.next = n.next; 10 | } 11 | else { 12 | set.add(n.data); 13 | previous = n; 14 | } 15 | n = n.next; 16 | } 17 | } 18 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter2LinkedLists/DeleteNode.java: -------------------------------------------------------------------------------- 1 | //Implement an algorithm to delete a node in the middle of a singly linked list, give only access to that node 2 | 3 | public class DeleteNode { 4 | public static boolean deleteNode(LinkedListNode n) { 5 | if(n == null || n.next == null) { 6 | return false; 7 | } 8 | 9 | LinkedListNode next = n.next; 10 | n.data = next.data; 11 | n.next = next.next; 12 | return true; 13 | } 14 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter2LinkedLists/NthToLast.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/CrackingTheCodingInterview/Chapter2LinkedLists/NthToLast.java -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter3StacksAndQueues/QueueUsingTwoStacks.java: -------------------------------------------------------------------------------- 1 | /* implement a MyQueue class which implements a queue using two stacks */ 2 | 3 | public class QueueUsingTwoStacks { 4 | 5 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter4TreesAndGraphs/CreateBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* given a sorted (increasing order) array with unique integer elements, write an algorithm 2 | * to create a binary search tree with minimal height */ 3 | 4 | public class CreateBinarySearchTree { 5 | TreeNode createMinimalBST(int arr[], int start, int end) { 6 | if(end < start) { 7 | return null; 8 | } 9 | int mid = (start + end) / 2; 10 | TreeNode n = new TreeNode(arr[mid]); 11 | n.left = createMinimalBST(arr, start, mid - 1); 12 | n.right = createMinimalBST(arr, mid + 1, end); 13 | return n; 14 | } 15 | 16 | TreeNode createMinimalBST(int array[]) { 17 | return createMinimalBST(array, 0, array.length - 1); 18 | } 19 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter4TreesAndGraphs/ValidBinarySearchTree.java: -------------------------------------------------------------------------------- 1 | /* implement a function to check if a binary tree is a binary search tree */ 2 | 3 | public class ValidBinarySearchTree { 4 | boolean checkBST(TreeNode n) { 5 | return checkBST(n, null, null); 6 | } 7 | 8 | boolean checkBST(TreeNode n, Integer min, Integer max) { 9 | if(n == null) { 10 | return true; 11 | } 12 | if((min != null && n.data <= min) || (max != null && n.data > max)) { 13 | return false; 14 | } 15 | 16 | if(!checkBST(n.left, min, n.data) || !checkBST(n.right, n.data, max)) { 17 | return false; 18 | } 19 | return true; 20 | } 21 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter5BitManipulation/SwapBits.java: -------------------------------------------------------------------------------- 1 | /* write a program to swap odd and even bits in an integer with as few instructions as 2 | * possible (e.g., bit 0 and bit 1 are swapped, bit 2 and bit 3 are swapped, and so on) */ 3 | 4 | public class SwapBits { 5 | public int swapOddEvenBits(int x) { 6 | return ( ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1) ); 7 | } 8 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter7MathematicsAndProbability/WouldIntersect.java: -------------------------------------------------------------------------------- 1 | /* give two lines on a Cartesian plane, determine whether the two lines would intersect */ 2 | 3 | public class WouldIntersect { 4 | //placeholder for class name 5 | } 6 | 7 | class Line { 8 | static double epsilon = 0.000001; 9 | public double slope; 10 | public double yintercept; 11 | 12 | public Line(double s, double y) { 13 | this.slope = s; 14 | this.yintercept = y; 15 | } 16 | 17 | public boolean Intersect(Line line2) { 18 | return Math.abs(this.slope - line2.slope) > epsilon || Math.abs(this.yintercept - line2.yintercept) < epsilon; 19 | } 20 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/Chapter9RecursionAndDynamicProgramming/Staircase.java: -------------------------------------------------------------------------------- 1 | /* a child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps 2 | * at a time. Implement a method to count how many possible ways the child can run up the stairs */ 3 | 4 | public class Staircase { 5 | public static int countWaysDP(int n, int[] map) { 6 | if(n < 0) { 7 | return 0; 8 | } 9 | else if(n == 0) { 10 | return 1; 11 | } 12 | else if(map[n] > -1) { 13 | return map[n]; 14 | } 15 | else { 16 | map[n] = countWaysDP(n - 1, map) + 17 | countWaysDP(n - 2, map) + 18 | countWaysDP(n - 3, map); 19 | return map[n]; 20 | } 21 | } 22 | } -------------------------------------------------------------------------------- /CrackingTheCodingInterview/CrackingTheCodingInterview.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /HackerRank/AppendAndDelete.py: -------------------------------------------------------------------------------- 1 | # Complete the appendAndDelete function below. 2 | def appendAndDelete(s, t, k): 3 | minOps = 0 4 | ls = len(s) 5 | lt = len(t) 6 | m = min(lt, ls) 7 | same = 0 8 | 9 | for i in range(m): 10 | if s[i] == t[i]: 11 | same += 1 12 | else: 13 | break 14 | # Case A 15 | if (ls + lt - (2 * same)) > k: 16 | print("NO") 17 | elif(ls + lt - (2 * same)) % 2 == k % 2: 18 | print("YES") 19 | elif(ls + lt) < k: 20 | print("YES") 21 | else: 22 | print("NO") 23 | 24 | print(appendAndDelete("ashley", "ash", 2)) 25 | -------------------------------------------------------------------------------- /HackerRank/AppleAndOrange.py: -------------------------------------------------------------------------------- 1 | # Complete the countApplesAndOranges function below. 2 | def countApplesAndOranges(s, t, a, b, apples, oranges): 3 | cApples, cOranges = 0, 0 4 | for apple in apples: 5 | dis = a + apple 6 | if dis >= s and dis <= t: 7 | cApples += 1 8 | for orange in oranges: 9 | dis = b + orange 10 | if dis >= s and dis <= t: 11 | cOranges += 1 12 | print(cApples) 13 | print(cOranges) 14 | -------------------------------------------------------------------------------- /HackerRank/BeautifulDaysAtTheMovies.py: -------------------------------------------------------------------------------- 1 | # Complete the beautifulDays function below. 2 | def beautifulDays(i, j, k): 3 | c = 0 4 | for i in range(i, j + 1): 5 | if (abs(i - int(''.join(reversed(str(i))))) % k) == 0: 6 | c += 1 7 | return c 8 | 9 | print(beautifulDays(20, 23, 6)) 10 | -------------------------------------------------------------------------------- /HackerRank/BirthdayChocolate.py: -------------------------------------------------------------------------------- 1 | # Complete the birthday function below. 2 | def birthday(s, d, m): 3 | i, j = 0, m 4 | res = 0 5 | 6 | # Scan through the array with a window size of the month 7 | # calculate the sum of the window slit array 8 | # if it is equal to the date then increment counter else 9 | # move on to the next window slit 10 | while(j <= len(s)): 11 | if sum(s[i : j]) == d: 12 | res += 1 13 | i += 1 14 | j += 1 15 | return res 16 | -------------------------------------------------------------------------------- /HackerRank/BonAppetit.py: -------------------------------------------------------------------------------- 1 | # Complete the bonAppetit function below. 2 | def bonAppetit(bill, k, b): 3 | cost = 0 4 | cost = sum(bill) - bill[k] 5 | 6 | herShare = cost // 2 7 | 8 | if b == herShare: 9 | return "Bon Appetit" 10 | else: 11 | return int(b - herShare) 12 | 13 | print(bonAppetit([3, 10, 2, 9], 1, 7)) 14 | -------------------------------------------------------------------------------- /HackerRank/BreakingRecords.py: -------------------------------------------------------------------------------- 1 | # Complete the breakingRecords function below. 2 | def breakingRecords(scores): 3 | miniCount, maxiCount = 0, 0 4 | mini, maxi = scores[0], scores[0] 5 | 6 | for score in scores: 7 | if score < mini: 8 | mini = score 9 | miniCount += 1 10 | elif score > maxi: 11 | maxi = score 12 | maxiCount += 1 13 | 14 | return([maxiCount, miniCount]) 15 | -------------------------------------------------------------------------------- /HackerRank/CatAndMouse.py: -------------------------------------------------------------------------------- 1 | # Complete the catAndMouse function below. 2 | def catAndMouse(x, y, z): 3 | disA = abs(x - z) 4 | disB = abs(y - z) 5 | 6 | if disA == disB: 7 | return "Mouse C" 8 | elif abs(x - z) < abs(y - z): 9 | return "Cat A" 10 | elif abs(x - z) > abs(y - z): 11 | return "Cat B" 12 | -------------------------------------------------------------------------------- /HackerRank/ChocolateFeast.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/chocolate-feast/problem 2 | 3 | # Algorithm is specified in the question 4 | def chocolateFeast(n, c, m): 5 | chocolates = n // c 6 | wrappers = chocolates 7 | count = chocolates 8 | 9 | while(wrappers >= m): 10 | chocolates = wrappers // m 11 | wrappers = wrappers % m + chocolates 12 | count += chocolates 13 | 14 | return count 15 | 16 | 17 | 18 | print(chocolateFeast(7,3,2)) 19 | -------------------------------------------------------------------------------- /HackerRank/CircularArrayRotation.py: -------------------------------------------------------------------------------- 1 | # a little complex with assigning the array with the rotated state 2 | def circularArrayRotation(a, k, queries): 3 | l = len(a) 4 | pos = (l + k) % l 5 | newAr = [0] * l 6 | i = 0 7 | 8 | while(i < l): 9 | newAr[pos] = a[i] 10 | i += 1 11 | pos += 1 12 | if pos > l - 1: 13 | pos = 0 14 | 15 | res = [] 16 | 17 | for i in queries: 18 | res.append(newAr[i]) 19 | 20 | return res 21 | -------------------------------------------------------------------------------- /HackerRank/Contests/UniversityCodesprint5/ArrayTriplets.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/contests/university-codesprint-5/challenges/array-triplets 2 | # Medium 3 | 4 | def solve(a): 5 | total = sum(a) 6 | each = total // 3 7 | -------------------------------------------------------------------------------- /HackerRank/Contests/UniversityCodesprint5/ExceedingTheSpeedLimit.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/contests/university-codesprint-5/challenges/exceeding-speed-limit 2 | 3 | def solve(s): 4 | if s <= 90: 5 | return "0 No punishment" 6 | elif s > 90 and s <= 110: 7 | return str((s - 90) * 300) + " Warning" 8 | elif s > 110: 9 | return str((s - 90) * 500) + " License removed" 10 | 11 | 12 | print(solve(85)) 13 | -------------------------------------------------------------------------------- /HackerRank/CountingValleys.py: -------------------------------------------------------------------------------- 1 | # Complete the countingValleys function below. 2 | def countingValleys(n, s): 3 | val = 0 4 | count = 0 5 | l = [0] 6 | for i in s: 7 | if i == 'U': 8 | last = val 9 | val += 1 10 | else: 11 | last = val 12 | val -= 1 13 | 14 | if val == 0: 15 | if last > 0: 16 | pass 17 | else: 18 | count += 1 19 | return(count) 20 | countingValleys(5, "UDUDUDUDUDUD") 21 | -------------------------------------------------------------------------------- /HackerRank/CutTheSticks.py: -------------------------------------------------------------------------------- 1 | # Complete the cutTheSticks function below. 2 | def cutTheSticks(arr): 3 | lastMin = minLen = min(arr) 4 | l = len(arr) 5 | res = [] 6 | while(l > 0): 7 | res.append(l) 8 | for i in range(len(arr)): 9 | if arr[i] >= minLen: 10 | arr[i] -= minLen 11 | 12 | if arr[i] == 0: 13 | l -= 1 14 | try: 15 | minLen = min(i for i in arr if i > 0) 16 | except: 17 | return res 18 | 19 | l = list(map(int, "5 4 4 2 2 8".split())) 20 | 21 | print(cutTheSticks(l)) 22 | -------------------------------------------------------------------------------- /HackerRank/DayOfTheProgrammer.py: -------------------------------------------------------------------------------- 1 | # Complete the dayOfProgrammer function below. 2 | def dayOfProgrammer(year): 3 | if (year == 1918): 4 | return '26.09.1918' 5 | elif ((year <= 1917) & (year%4 == 0)) or ((year > 1918) & 6 | (year%400 == 0 or ((year%4 == 0) & (year%100 != 0)))): 7 | return '12.09.%s' %year 8 | else: 9 | return '13.09.%s' %year 10 | -------------------------------------------------------------------------------- /HackerRank/DesignerPDFViewer.py: -------------------------------------------------------------------------------- 1 | # Complete the designerPdfViewer function below. 2 | def designerPdfViewer(h, word): 3 | lookup = dict(zip(list("abcdefghijklmnopqrstuvwxyz"), h)) 4 | ht = max(lookup[x] for x in word) 5 | wd = len(word) 6 | return ht * wd 7 | -------------------------------------------------------------------------------- /HackerRank/DrawingBook.py: -------------------------------------------------------------------------------- 1 | import math 2 | # half the number of pages from front | 3 | # half the number of pages to last and then subtract the number of pages to the current page form it 4 | def pageCount(n, p): 5 | return min(p//2, n//2 - p//2) 6 | 7 | print(pageCount(7, 1)) 8 | 9 | # TAGS: Page turning, first, last, book, minimum 10 | -------------------------------------------------------------------------------- /HackerRank/ElectronicsShop.py: -------------------------------------------------------------------------------- 1 | def getMoneySpent(keyboards, drives, b): 2 | cost = -1 3 | for i in keyboards: 4 | for j in drives: 5 | if i + j <= b: 6 | if cost < i + j: 7 | cost = i + j 8 | return cost 9 | 10 | getMoneySpent([40, 50, 6]) 11 | -------------------------------------------------------------------------------- /HackerRank/EqualizeTheArray.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/equality-in-a-array/problem 2 | 3 | # Find the max reccuring element and delete its count from the len of the array 4 | def equalizeArray(arr): 5 | d = {} 6 | maxElementCount = -1 7 | 8 | for element in arr: 9 | if element in d: 10 | d[element] += 1 11 | else: 12 | d[element] = 1 13 | 14 | if d[element] > maxElementCount: 15 | maxElementCount = d[element] 16 | return len(arr) - maxElementCount 17 | 18 | print(equalizeArray([1,1,1,2,2])) 19 | -------------------------------------------------------------------------------- /HackerRank/ExtraLongFactorials.py: -------------------------------------------------------------------------------- 1 | # Complete the extraLongFactorials function below. 2 | def extraLongFactorials(n): 3 | result = 1 4 | 5 | for i in range(1, n + 1): 6 | result = result * i 7 | 8 | return result 9 | 10 | print(extraLongFactorials(100)) 11 | -------------------------------------------------------------------------------- /HackerRank/FairRations.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/fair-rations/problem 2 | 3 | # Idea: If the sum of the array is ODD, 4 | # then adding 2's to its each time will not make it even 5 | # Hence, While summing the bread check if the sum turns out to be odd 6 | # if so, add 2 to the count, return count if sum is even 7 | def fairRations(breadArray): 8 | s = 0 9 | count = 0 10 | 11 | for i in breadArray: 12 | s += i 13 | if s % 2 != 0: 14 | count += 2 15 | 16 | return count if not (s % 2) else "NO" 17 | 18 | array = [1, 0, 1, 1, 1, 1, 0, 1] 19 | print(fairRations(array)) 20 | 21 | # TAGS: bread, distribution, fair, 2 bread 22 | -------------------------------------------------------------------------------- /HackerRank/FindDigits.py: -------------------------------------------------------------------------------- 1 | # Complete the findDigits function below. 2 | def findDigits(n): 3 | listNum = list(map(int, list(str(n)))) 4 | 5 | count = 0 6 | for i in listNum: 7 | if i != 0: 8 | if n % i == 0: 9 | count += 1 10 | return(count) 11 | 12 | 13 | 14 | findDigits(123) 15 | -------------------------------------------------------------------------------- /HackerRank/HalloweenSale.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/halloween-sale/problem 2 | 3 | def howManyGames(p, d, m, s): 4 | count = 0 5 | 6 | # Make sure you have enough money to buy 7 | while s >= 0: 8 | s -= p # Charge the wallet 9 | p = max(p - d, m) # check whats the least, discounted price or min price 10 | games += 1 11 | return games - 1 12 | 13 | print(howManyGames(100, 1, 1, 99)) 14 | -------------------------------------------------------------------------------- /HackerRank/JumpingOnTheClouds.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem 2 | 3 | # Greedy approach, select the larger step if its a valid move, 4 | # else take the smaller step. 5 | def jumpingOnTheClouds(c): 6 | l = 0 7 | count = 0 8 | 9 | while(l < len(c) - 1): 10 | if l + 2 < len(c) and c[l + 2] != 1: 11 | l = l + 2 12 | count += 1 13 | else: 14 | l = l + 1 15 | count += 1 16 | return count 17 | 18 | print(jumpingOnTheClouds([0,1,0,0,0,1,0])) 19 | -------------------------------------------------------------------------------- /HackerRank/JumpingTheClouds.py: -------------------------------------------------------------------------------- 1 | # Complete the jumpingOnClouds function below. 2 | def jumpingOnClouds(c, k): 3 | e = 100 4 | n = len(c) 5 | i = 0 6 | print("first index:", i, "value is:", c[i], "energy is:", e) 7 | print() 8 | while(e > 0): 9 | i = (i + k) % n 10 | e -= 1 11 | if c[i] == 1: 12 | e -= 2 13 | print("next index:", i, "value is:", c[i], "energy is:", e) 14 | print() 15 | if i == 0: 16 | break 17 | return(e) 18 | 19 | l = "0 0 1 0" 20 | print(jumpingOnClouds(list(map(int, l.split())), 2)) 21 | -------------------------------------------------------------------------------- /HackerRank/Kangaroo.py: -------------------------------------------------------------------------------- 1 | # Complete the kangaroo function below. 2 | def kangaroo(x1, v1, x2, v2): 3 | if x1 == x2 and v1 == v2: 4 | return ("YES") 5 | elif x1 == x2 and v1 > v2: 6 | return ("NO") 7 | elif x1 <= x2 and v1 <= v2: 8 | return ("NO") 9 | else: 10 | if (x1 - x2) % (v1-v2) == 0: 11 | return 'YES' 12 | else: 13 | return 'NO' 14 | -------------------------------------------------------------------------------- /HackerRank/LibraryFine.py: -------------------------------------------------------------------------------- 1 | # Complete the libraryFine function below. 2 | def libraryFine(d2, m2, y2, d1, m1, y1): 3 | if y2 <= y1: 4 | if y2 maxi: 11 | maxi = val 12 | print(mini, maxi) 13 | 14 | miniMaxSum([1,2,3,4,5]) 15 | -------------------------------------------------------------------------------- /HackerRank/MinimumDistances.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/minimum-distances/problem 2 | 3 | 4 | def minimumDistances(array): 5 | lookup = {} 6 | minDistance = sum(array) 7 | 8 | for x in range(len(array)): 9 | if array[x] in lookup: 10 | dis = abs(lookup[array[x]] - x) 11 | if minDistance > dis: 12 | minDistance = dis 13 | else: 14 | lookup[array[x]] = x 15 | if minDistance != sum(array): 16 | return minDistance 17 | return -1 18 | 19 | print(minimumDistances(list(map(int, "1 2 3 4 10".split())))) 20 | -------------------------------------------------------------------------------- /HackerRank/RepeatedString.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/repeated-string/problem 2 | import math 3 | 4 | # Split the array into two parts. Count the number of a's in the quotient * len(s) 5 | # Add the count of a's from 0 to the partial len of s. This should give the total 6 | # number of a's 7 | def repeatedString(s, n): 8 | return s.count("a") * (n // len(s)) + s[ : n % len(s)].count("a") 9 | print(repeatedString('a', 22)) 10 | -------------------------------------------------------------------------------- /HackerRank/SaveThePrisoner.py: -------------------------------------------------------------------------------- 1 | # Complete the saveThePrisoner function below. 2 | def saveThePrisoner(numPrisoners, numSweets, start): 3 | if ((numSweets + start - 1) % numPrisoners == 0): 4 | return(numPrisoners) 5 | else: 6 | return ((numSweets + start - 1) % numPrisoners) 7 | print(saveThePrisoner(3, 7, 3)) 8 | -------------------------------------------------------------------------------- /HackerRank/SequenceEquation.py: -------------------------------------------------------------------------------- 1 | # Complete the permutationEquation function below. 2 | def permutationEquation(p): 3 | lookup = {} 4 | res = [] 5 | for x in range(len(p)): 6 | lookup[p[x]] = x + 1 7 | 8 | for x in range(len(p)): 9 | res.append(lookup[lookup[x + 1]]) 10 | return res 11 | permutationEquation([2,3,1]) 12 | -------------------------------------------------------------------------------- /HackerRank/ServiceLane.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/service-lane/problem 2 | 3 | 4 | def serviceLane(width, cases): 5 | result = [] 6 | 7 | for case in cases: 8 | i = case[0] 9 | j = case[1] 10 | 11 | result.append(min(width[i : j + 1])) 12 | return result 13 | 14 | serviceLane(1, [[1, 2], [3, 4]]) 15 | -------------------------------------------------------------------------------- /HackerRank/SherlockAndSquares.py: -------------------------------------------------------------------------------- 1 | import math 2 | # Complete the squares function below. 3 | def squares(a, b): 4 | return math.floor(b**(0.5)) - math.ceil(a**(0.5)) + 1 5 | print(squares(100, 1000)) 6 | -------------------------------------------------------------------------------- /HackerRank/SockMerchant.py: -------------------------------------------------------------------------------- 1 | # Complete the sockMerchant function below. 2 | def sockMerchant(n, ar): 3 | sockList = {} 4 | totalPairs = 0 5 | 6 | for i in ar: 7 | if i in sockList: 8 | del sockList[i] 9 | totalPairs += 1 10 | else: 11 | sockList[i] = 1 12 | return totalPairs 13 | -------------------------------------------------------------------------------- /HackerRank/StrangeCounter.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/strange-code/problem 2 | # Easy 3 | 4 | 5 | def strangeCounter(t): 6 | rem = 3 # The time upward 7 | while(rem < t): 8 | t = t - rem # Subtract from the original 9 | rem *= 2 # Follow the condition and increment 10 | return(rem - t + 1) # The difference between time upward and original + 1 11 | 12 | print(strangeCounter(8)) 13 | 14 | # TAGS: revise, time, modulus 15 | -------------------------------------------------------------------------------- /HackerRank/TheGridSearch.py: -------------------------------------------------------------------------------- 1 | # https://www.hackerrank.com/challenges/the-grid-search/problem 2 | 3 | def gridSearch(G, R, C, P, r, c): 4 | filRow = R - r + 1 5 | filCol = C - c + 1 6 | 7 | for i in range(filRow): 8 | for j in range(filCol): 9 | daffuq = [] 10 | for x in range(r): 11 | daffuq.append(G[i + x][j : j + c]) 12 | print(daffuq) 13 | if daffuq == P: 14 | return "YES" 15 | return "NO" 16 | 17 | G = [[1, 2, 3, 4, 1, 2], 18 | [5, 6, 1, 2, 1, 2], 19 | [1, 2, 3, 6, 1, 2], 20 | [7, 8, 1, 2, 3, 4]] 21 | P = [[1, 2], [3, 4]] 22 | 23 | print(gridSearch(G, 4, 6, P, 2, 2)) 24 | 25 | # TAGS: Grid, filter, search, n^2 26 | -------------------------------------------------------------------------------- /HackerRank/TheHurdleRace.py: -------------------------------------------------------------------------------- 1 | # Complete the hurdleRace function below. 2 | def hurdleRace(k, height): 3 | if k < max(height): 4 | return max(height) - k 5 | return 0 6 | 7 | print(hurdleRace(2, [2,5,4,5,2])) 8 | -------------------------------------------------------------------------------- /HackerRank/TimeConversion.py: -------------------------------------------------------------------------------- 1 | def timeConversion(s): 2 | hh = s[0:2] 3 | mm = s[3:5] 4 | ss = s[6:8] 5 | AMorPM = s[8:10] 6 | if AMorPM == "PM": 7 | if int(hh) < 12: 8 | hh = str(int(hh) + 12) 9 | else: 10 | if int(hh) == 12: 11 | hh = str("00") 12 | return hh + ":" + mm + ":" + ss 13 | 14 | 15 | 16 | 17 | 18 | 19 | print(timeConversion("12:05:45AM")) 20 | -------------------------------------------------------------------------------- /HackerRank/ViralAdertising.py: -------------------------------------------------------------------------------- 1 | # Complete the viralAdvertising function below. 2 | def viralAdvertising(n): 3 | sumLiked = 0 4 | day = 1 5 | liked = 5 // 2 6 | sumLiked += liked 7 | receivedBy = liked * 3 8 | 9 | # print(liked, receivedBy) 10 | 11 | while(day < n): 12 | day += 1 13 | liked = receivedBy // 2 14 | receivedBy = liked * 3 15 | sumLiked += liked 16 | 17 | return sumLiked 18 | print(viralAdvertising(3)) 19 | -------------------------------------------------------------------------------- /HackerRank/a-very-big-sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | long long sum; 14 | int n; 15 | 16 | int main() { 17 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 18 | sum = 0; 19 | scanf("%d",&n); 20 | long long v; 21 | for(int i = 0; i < n; ++ i){ 22 | scanf("%lld",&v); 23 | sum += v; 24 | } 25 | printf("%lld\n",sum); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /HackerRank/abstract-classes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Design 4 | */ 5 | class MyBook : public Book { 6 | private: 7 | int price; 8 | public: 9 | MyBook(string title, string author, int price) 10 | : Book (title, author){ 11 | this->price = price; 12 | } 13 | 14 | void display(){ 15 | cout<<"Title: "< 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | const int N = 100100; 14 | int s[N]; 15 | int n, m, v, id; 16 | 17 | int main() { 18 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 19 | scanf("%d%d",&n,&m); 20 | m %= n; 21 | for(int i = 0; i < n; ++ i){ 22 | scanf("%d",&v); 23 | id = (i - m + n)%n; 24 | s[id] = v; 25 | } 26 | for(int i = 0; i < n; ++ i) 27 | printf("%d ",s[i]); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /HackerRank/arrays_ds.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | const int N = 1100; 14 | int n; 15 | int arr[N]; 16 | 17 | int main() { 18 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 19 | scanf("%d",&n); 20 | for(int i = 0; i < n ; ++ i) 21 | scanf("%d",&arr[i]); 22 | for(int i = n - 1; i >= 0; -- i) 23 | printf("%d ",arr[i]); 24 | puts(""); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /HackerRank/beautiful-3-set.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * From Codeforces 4 | * Tag: Construction 5 | * Time: O(n) 6 | * Space: O(1) 7 | */ 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | using namespace std; 16 | int n, k; 17 | 18 | int main(){ 19 | cin>>n; 20 | k = (2*n)/3; 21 | cout< 8 | using namespace std; 9 | 10 | bool cmp(string &a, string &b){ 11 | return a.size() == b.size()? a < b : a.size() < b.size(); 12 | } 13 | 14 | int main(){ 15 | int n; 16 | cin >> n; 17 | vector unsorted(n); 18 | for(int unsorted_i = 0; unsorted_i < n; unsorted_i++){ 19 | cin >> unsorted[unsorted_i]; 20 | } 21 | sort(unsorted.begin(), unsorted.end(), cmp); 22 | for(int i = 0; i < n; ++ i) 23 | cout< 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | const int N = 300010; 14 | int n, cnt, max_h, v; 15 | 16 | int main() { 17 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 18 | scanf("%d",&n); 19 | max_h = cnt = 0; 20 | for(int i = 0; i < n; ++ i){ 21 | scanf("%d",&v); 22 | if(v > max_h){ 23 | max_h = v; 24 | cnt = 1; 25 | }else if(v == max_h) 26 | ++ cnt; 27 | } 28 | printf("%d\n",cnt); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /HackerRank/bob-and-ben.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Game Theory 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | using namespace std; 10 | int n, m, ans, u, v; 11 | 12 | int main(){ 13 | int T; 14 | scanf("%d",&T); 15 | while (T --){ 16 | scanf("%d",&n); 17 | ans = 0; 18 | for(int i = 0; i < n; ++ i){ 19 | scanf("%d%d",&u,&v); 20 | if ( u == 1) ans^=1; 21 | else if (u > 2){ 22 | if (u%2==1) ans^=1; 23 | else ans^=2; 24 | } 25 | } 26 | if (ans) 27 | puts("BOB"); 28 | else 29 | puts("BEN"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /HackerRank/bon-appetit.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n, k, v, b; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | scanf("%d%d",&n,&k); 18 | int ans = 0; 19 | for(int i = 0; i < n; ++ i){ 20 | scanf("%d",&v); 21 | if(i != k) 22 | ans += v; 23 | } 24 | scanf("%d",&b); 25 | if(ans/2 == b) 26 | puts("Bon Appetit"); 27 | else 28 | printf("%d\n",b - ans/2); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /HackerRank/countingsort1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Sort 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int n; 18 | vector rec(101,0); 19 | cin>>n; 20 | for(int i = 0; i < n; i ++){ 21 | int a; 22 | cin>>a; 23 | rec[a] ++; 24 | } 25 | for(int i = 0; i < 100; i ++){ 26 | cout< 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int n; 18 | vector rec(100,0); 19 | int tmp; 20 | cin >> n; 21 | for(int i = 0; i < n; i ++) { 22 | cin >> tmp; 23 | rec[tmp] ++; 24 | } 25 | for(int i = 0; i < 100; i ++){ 26 | for(int j = 0; j < rec[i]; j ++) 27 | cout< 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | const int N = 200; 14 | int v, cnt[N], maxcnt; 15 | int n; 16 | 17 | int main() { 18 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 19 | scanf("%d",&n); 20 | maxcnt = 0; 21 | for(int i = 0; i < n; ++ i){ 22 | scanf("%d",&v); 23 | ++ cnt[v]; 24 | maxcnt = max(maxcnt, cnt[v]); 25 | } 26 | printf("%d\n",n - maxcnt); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank/game-with-cells.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n, m; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | scanf("%d%d",&n,&m); 18 | int tr = n/2, onr = n%2, tc = m/2, onc = m%2; 19 | printf("%d\n",tr*tc+tr*onc+onr*tc+onr*onc); 20 | return 0; 21 | } 22 | -------------------------------------------------------------------------------- /HackerRank/hackerrank-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: 6 | */ 7 | #include 8 | using namespace std; 9 | string s, t = "hackerrank"; 10 | int i, j; 11 | 12 | int main(){ 13 | int q; 14 | cin >> q; 15 | for(int a0 = 0; a0 < q; a0++){ 16 | cin>>s; 17 | i = j = 0; 18 | for(i = 0; i < s.size() && j < t.size(); ++ i){ 19 | if(s[i] == t[j]) 20 | ++ j; 21 | } 22 | if(j >= t.size()) 23 | puts("YES"); 24 | else 25 | puts("NO"); 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank/insert-a-node-at-the-tail-of-a-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: O(n) 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | /* 8 | Insert Node at the end of a linked list 9 | head pointer input could be NULL as well for empty list 10 | Node is defined as 11 | struct Node 12 | { 13 | int data; 14 | struct Node *next; 15 | } 16 | */ 17 | Node* Insert(Node *head,int data) 18 | { 19 | // Complete this method 20 | Node *node = new Node(); 21 | node->data = data; 22 | node->next = NULL; 23 | if(!head) 24 | head = node; 25 | else{ 26 | Node *p = head; 27 | while(p->next) 28 | p = p->next; 29 | p->next = node; 30 | } 31 | return head; 32 | } 33 | -------------------------------------------------------------------------------- /HackerRank/is-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | bool checkBST(Node* root) { 8 | bool ans = true; 9 | int maxval = -(1<<30); 10 | solve(root, maxval, ans); 11 | return ans; 12 | } 13 | 14 | void solve(Node* root, int &maxval, bool &ans){ 15 | if(root->left) 16 | solve(root->left, maxval, ans); 17 | if(maxval >= root->data){ 18 | ans = false; 19 | return ; 20 | } 21 | maxval = max(maxval, root->data); 22 | if(root->right) 23 | solve(root->right, maxval, ans); 24 | } 25 | -------------------------------------------------------------------------------- /HackerRank/library-fine.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | using namespace std; 10 | int d1, m1, y1, d2, m2, y2; 11 | 12 | int main() { 13 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 14 | scanf("%d%d%d%d%d%d",&d1,&m1,&y1,&d2,&m2,&y2); 15 | int ans = 0; 16 | if(y1 > y2) 17 | ans = 10000; 18 | else{ 19 | if(y1 == y2 && m1 > m2) 20 | ans = 500*(m1 - m2); 21 | else{ 22 | if(y1 == y2 && m1 == m2 && d1 > d2) 23 | ans = 15*(d1 - d2); 24 | } 25 | } 26 | printf("%d\n",ans); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank/lonely-integer-fill-the-key-line.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | 9 | using namespace std; 10 | 11 | int lonely_integer(vector < int > a) { 12 | int answer = 0; 13 | for(int i = 0; i < a.size(); i++) { 14 | // FILL THE MISSING LINE HERE 15 | } 16 | return answer; 17 | } 18 | 19 | int main() { 20 | int res; 21 | int _a_size; 22 | cin >> _a_size; 23 | vector _a(_a_size); 24 | for(int _a_i = 0; _a_i < _a_size; _a_i++) { 25 | cin >> _a[_a_i]; 26 | } 27 | res = lonely_integer(_a); 28 | cout << res; 29 | return 0; 30 | } 31 | 32 | -------------------------------------------------------------------------------- /HackerRank/lowest-triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | 9 | using namespace std; 10 | 11 | int lowestTriangle(int base, int area){ 12 | if(area%base == 0 || (2*area)%base == 0) 13 | return 2*area/base; 14 | int mod_v = (2*area)%base; 15 | return (2*area + (base - mod_v))/base; 16 | } 17 | 18 | int main() { 19 | int base; 20 | int area; 21 | cin >> base >> area; 22 | int height = lowestTriangle(base, area); 23 | cout << height << endl; 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /HackerRank/make-it-anagram-mglines.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Hash 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int main() { 15 | char s1[10010], s2[10010]; 16 | cin >> s1 >> s2; 17 | int a[26] = {0}; 18 | for(int i = 0; i < strlen(s1); i++) { 19 | a[s1[i] - 'a']++; 20 | } 21 | for(int i = 0; i < strlen(s2); i++) { 22 | a[s2[i] - 'a']--; 23 | } 24 | long long int ans = 0; 25 | for(int i = 0; i < 26; i++) 26 | ans += abs(a[i]); 27 | cout << ans << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /HackerRank/marcs-cakewalk.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(nlgn) 5 | * Space: O(lgn) 6 | */ 7 | #include 8 | using namespace std; 9 | const int N = 100; 10 | int cake[N], n; 11 | 12 | int main(){ 13 | scanf("%d",&n); 14 | for(int i = 0; i < n; ++ i) 15 | scanf("%d",&cake[i]); 16 | sort(cake, cake + n, greater()); 17 | long long ans = 0, mask = 1; 18 | for(int i = 0; i < n; ++ i, mask <<= 1){ 19 | ans += mask*cake[i]; 20 | } 21 | printf("%lld\n",ans); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /HackerRank/migratory-birds.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | using namespace std; 9 | int n, v, dict[6]; 10 | 11 | int main(){ 12 | scanf("%d",&n); 13 | memset(dict, 0, sizeof(dict)); 14 | for(int i = 0; i < n; ++ i){ 15 | scanf("%d",&v); 16 | ++ dict[v]; 17 | } 18 | int ans_id = 0, ans_cnt = 0; 19 | for(int i = 1; i <= 5; ++ i){ 20 | if(dict[i] > ans_cnt){ 21 | ans_cnt = dict[i]; 22 | ans_id = i; 23 | } 24 | } 25 | printf("%d\n",ans_id); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /HackerRank/minimum-absolute-difference-in-an-array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(nlgn) 5 | * Space: O(lgn) 6 | */ 7 | #include 8 | using namespace std; 9 | const int N = 200100; 10 | int arr[N], n; 11 | 12 | int main(){ 13 | scanf("%d",&n); 14 | for(int i = 0; i < n; ++ i) 15 | scanf("%d",&arr[i]); 16 | sort(arr, arr + n); 17 | int ans = INT_MAX; 18 | for(int i = 1; i < n; ++ i) 19 | ans = min(ans, arr[i] - arr[i - 1]); 20 | printf("%d\n",ans); 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /HackerRank/nim-game-1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Game 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int T; 18 | scanf("%d",&T); 19 | while(T --){ 20 | scanf("%d",&n); 21 | int ans = 0, v; 22 | for(int i = 0; i < n; ++ i){ 23 | scanf("%d",&v); 24 | ans ^= v; 25 | } 26 | if(ans) 27 | puts("First"); 28 | else 29 | puts("Second"); 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /HackerRank/p1-paper-cutting.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | 9 | using namespace std; 10 | 11 | long long solve(long long n, long long m){ 12 | long long res = 0; 13 | if(n <= m) 14 | res = (n - 1) + n*(m - 1); 15 | else 16 | res = (m - 1) + m*(n - 1); 17 | return res; 18 | } 19 | 20 | int main() { 21 | long long n, m; 22 | cin >> n >> m; 23 | long long result = solve(n, m); 24 | cout << result << endl; 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /HackerRank/print-the-elements-of-a-linked-list.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | /* 8 | Print elements of a linked list on console 9 | head pointer input could be NULL as well for empty list 10 | Node is defined as 11 | struct Node 12 | { 13 | int data; 14 | struct Node *next; 15 | } 16 | */ 17 | void Print(Node *head) 18 | { 19 | // This is a "method-only" submission. 20 | // You only need to complete this method. 21 | if(head == NULL) 22 | return ; 23 | Node *p = head; 24 | while(p){ 25 | printf("%d\n",p->data); 26 | p = p->next; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank/pythagorean-triple.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | using namespace std; 9 | int a; 10 | 11 | int main() { 12 | scanf("%d",&a); 13 | long long m, n, v; 14 | printf("%d ",a); 15 | if(a%2 == 0){ 16 | m = a/2, n = 1; 17 | printf("%lld %lld\n", m*m - n*n, m*m + n*n); 18 | }else{ 19 | n = (a - 1)/2; 20 | m = n + 1; 21 | printf("%lld %lld\n", 2*m*n, m*m + n*n); 22 | } 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /HackerRank/runningtime.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n^2) 5 | * Space: O(n) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int n; 18 | int ans = 0; 19 | vector rec; 20 | cin>>n; 21 | for(int i = 0; i < n; i ++){ 22 | int tmp; 23 | cin>>tmp; 24 | rec.push_back(tmp); 25 | for(int j = 0; j < i; j ++){ 26 | if(rec[j] > tmp) 27 | ans ++; 28 | } 29 | } 30 | cout< 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n, m, s; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int T; 18 | scanf("%d",&T); 19 | while(T --){ 20 | scanf("%d%d%d",&n,&m,&s); 21 | -- s; 22 | -- m; 23 | m %= n; 24 | s = (s + m)%n; 25 | printf("%d\n",s+1); 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank/sherlock-and-squares.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | using namespace std; 11 | 12 | int main(){ 13 | int T; 14 | scanf("%d",&T); 15 | while(T --){ 16 | int a,b; 17 | scanf("%d%d",&a,&b); 18 | int sa = sqrt(a), sb=sqrt(b); 19 | int ans = sb - sa; 20 | if(sa*sa == a) 21 | ans ++; 22 | printf("%d\n",ans); 23 | } 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /HackerRank/sherlock-and-watson.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int main(){ 15 | int n, k, q; 16 | scanf("%d%d%d",&n,&k,&q); 17 | vector v1, v2; 18 | v1.resize(n); 19 | v2.resize(n); 20 | for(int i = 0; i < n; i ++) 21 | scanf("%d",&v1[i]); 22 | for(int i = 0; i < n; i ++){ 23 | int pos = (i + k)%n; 24 | v2[pos] = v1[i]; 25 | } 26 | for(int i = 0; i < q; i ++){ 27 | int a; 28 | scanf("%d",&a); 29 | printf("%d\n",v2[a]); 30 | } 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /HackerRank/simple-array-sum.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n, sum; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | sum = 0; 18 | scanf("%d",&n); 19 | while(n --){ 20 | int a; 21 | scanf("%d",&a); 22 | sum += a; 23 | } 24 | printf("%d\n",sum); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /HackerRank/solve-me-first.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int solveMeFirst(int a, int b) { 15 | return a+b; 16 | } 17 | 18 | int main() { 19 | int num1, num2; 20 | int sum; 21 | scanf("%d%d",&num1,&num2); 22 | sum = solveMeFirst(num1,num2); 23 | printf("%d",sum); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /HackerRank/staircase.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n^2) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | scanf("%d",&n); 18 | int num_space = n - 1; 19 | for(int i = 1; i <= n; ++ i){ 20 | for(int j = 0; j < num_space; ++ j) 21 | printf(" "); 22 | for(int j = 0; j < i; ++ j) 23 | printf("#"); 24 | puts(""); 25 | -- num_space; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /HackerRank/strange-advertising.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n; 14 | long long ans; 15 | 16 | int main() { 17 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 18 | scanf("%d",&n); 19 | long long v = 5; 20 | ans = 0; 21 | for(int i = 1; i <= n; ++ i){ 22 | ans += v/2; 23 | v = (v/2)*3; 24 | } 25 | printf("%lld\n",ans); 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /HackerRank/strings-xor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | string strings_xor(string s, string t) { 15 | 16 | string res = ""; 17 | for(int i = 0; i < s.size(); i++) { 18 | if(s[i] == t[i]) 19 | res += '0'; 20 | else 21 | res += '1'; 22 | } 23 | 24 | return res; 25 | } 26 | 27 | int main() { 28 | string s, t; 29 | cin >> s >> t; 30 | cout << strings_xor(s, t) << endl; 31 | return 0; 32 | } 33 | 34 | -------------------------------------------------------------------------------- /HackerRank/tower-breakers-1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Game 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | int n,m; 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int T; 18 | scanf("%d",&T); 19 | while(T --){ 20 | scanf("%d%d",&m,&n); 21 | if(n == 1 || m%2 == 0) 22 | puts("2"); 23 | else 24 | puts("1"); 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /HackerRank/tree-height-of-a-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | /*The tree node has data, left child and right child 8 | struct node 9 | { 10 | int data; 11 | node* left; 12 | node* right; 13 | }; 14 | 15 | */ 16 | void dfs(node * root, int &ans, int dep){ 17 | if(!root){ 18 | return ; 19 | } 20 | ++ dep; 21 | ans = max(ans, dep); 22 | if(root->left) 23 | dfs(root->left, ans, dep); 24 | if(root->right) 25 | dfs(root->right, ans, dep); 26 | } 27 | 28 | int height(node * root){ 29 | int ans = 0; 30 | dfs(root, ans, 0); 31 | return ans; 32 | } 33 | -------------------------------------------------------------------------------- /HackerRank/tree-inorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | /* you only have to complete the function given below. 8 | Node is defined as 9 | 10 | struct node 11 | { 12 | int data; 13 | node* left; 14 | node* right; 15 | }; 16 | 17 | */ 18 | 19 | void Inorder(node *root) { 20 | if(root->left) 21 | Inorder(root->left); 22 | printf("%d ",root->data); 23 | if(root->right) 24 | Inorder(root->right); 25 | } 26 | -------------------------------------------------------------------------------- /HackerRank/tree-level-order-traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: BFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | /* 8 | struct node 9 | { 10 | int data; 11 | node* left; 12 | node* right; 13 | }*/ 14 | #include 15 | void LevelOrder(node * root){ 16 | queue q; 17 | bool isfirst = true; 18 | q.push(root); 19 | while(!q.empty()){ 20 | node *tmp = q.front(); 21 | q.pop(); 22 | if(!isfirst) 23 | printf(" "); 24 | printf("%d",tmp->data); 25 | if(tmp->left) 26 | q.push(tmp->left); 27 | if(tmp->right) 28 | q.push(tmp->right); 29 | isfirst = false; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /HackerRank/tree-postorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | /* you only have to complete the function given below. 8 | Node is defined as 9 | 10 | struct node 11 | { 12 | int data; 13 | node* left; 14 | node* right; 15 | }; 16 | 17 | */ 18 | 19 | 20 | void Postorder(node *root) { 21 | if(root->left) 22 | Postorder(root->left); 23 | if(root->right) 24 | Postorder(root->right); 25 | printf("%d ",root->data); 26 | } 27 | -------------------------------------------------------------------------------- /HackerRank/tree-preorder-traversal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | /* you only have to complete the function given below. 8 | Node is defined as 9 | 10 | struct node 11 | { 12 | int data; 13 | node* left; 14 | node* right; 15 | }; 16 | 17 | */ 18 | 19 | void Preorder(node *root) { 20 | printf("%d ",root->data); 21 | if(root->left) 22 | Preorder(root->left); 23 | if(root->right) 24 | Preorder(root->right); 25 | } 26 | -------------------------------------------------------------------------------- /HackerRank/tutorial-intro.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation, Hash 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int v,n; 18 | vector rec; 19 | cin>>v>>n; 20 | for(int i = 0; i < n; i ++){ 21 | int tmp; 22 | cin>>tmp; 23 | rec.push_back(tmp); 24 | } 25 | for(int i = 0; i < n; i ++){ 26 | if(rec[i] == v){ 27 | cout< 8 | #include 9 | #include 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | 15 | int main() { 16 | /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 17 | int T; 18 | cin>>T; 19 | while(T --){ 20 | int n; 21 | cin>>n; 22 | long long _ans = 1; 23 | for(int i = 0; i < n; i ++) { 24 | if(i%2 == 0) 25 | _ans = _ans*2; 26 | else 27 | _ans += 1; 28 | } 29 | cout<<_ans<= nums[2] <= nums[3].... 2 | 3 | // For example, given nums = [3, 5, 2, 1, 6, 4], one possible answer is [1, 6, 2, 5, 3, 4]. 4 | 5 | public class Solution { 6 | 7 | public void wiggleSort(int[] nums) { 8 | 9 | for(int i = 1; i < nums.length; i++) { 10 | 11 | int current = nums[i - 1]; 12 | 13 | if((i % 2 == 1) == (current > nums[i])) { 14 | 15 | nums[i - 1] = nums[i]; 16 | nums[i] = current; 17 | 18 | } 19 | 20 | } 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /LeetCode/BinarySearch/pow(x,n).java: -------------------------------------------------------------------------------- 1 | // Implement pow(x, n). 2 | 3 | public class Solution { 4 | 5 | public double myPow(double x, int n) { 6 | 7 | if(n == 0) { 8 | 9 | return 1; 10 | 11 | } 12 | 13 | if(Double.isInfinite(x)) { 14 | 15 | return 0; 16 | 17 | } 18 | 19 | if(n < 0) { 20 | 21 | n = -n; 22 | x = 1 / x; 23 | 24 | } 25 | 26 | return n % 2 == 0 ? myPow(x * x, n / 2) : x * myPow(x * x, n / 2); 27 | 28 | } 29 | 30 | } -------------------------------------------------------------------------------- /LeetCode/BinarySearch/sqrt(x).java: -------------------------------------------------------------------------------- 1 | // Implement int sqrt(int x). 2 | 3 | // Compute and return the square root of x. 4 | 5 | public class Solution { 6 | 7 | public int mySqrt(int x) { 8 | 9 | if(x == 0) return 0; 10 | 11 | int left = 1; 12 | int right = x; 13 | 14 | while(left <= right) { 15 | 16 | int mid = left + (right - left) / 2; 17 | 18 | if(mid == x / mid) return mid; 19 | else if(mid > x / mid) right = mid - 1; 20 | else if(mid < x / mid) left = mid + 1; 21 | 22 | } 23 | 24 | return right; 25 | 26 | } 27 | 28 | } -------------------------------------------------------------------------------- /LeetCode/BitManipulation/countingBits.java: -------------------------------------------------------------------------------- 1 | // Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array. 2 | 3 | // Example: 4 | // For num = 5 you should return [0,1,1,2,1,2]. 5 | 6 | public class Solution { 7 | public int[] countBits(int num) { 8 | 9 | int[] bits = new int[num + 1]; 10 | 11 | bits[0] = 0; 12 | 13 | for(int i = 1; i <= num; i++) { 14 | 15 | bits[i] = bits[i >> 1] + (i & 1); 16 | 17 | } 18 | 19 | return bits; 20 | 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /LeetCode/BitManipulation/hammingDistance.java: -------------------------------------------------------------------------------- 1 | // The Hamming distance between two integers is the number of positions at which the corresponding bits are different. 2 | 3 | // Given two integers x and y, calculate the Hamming distance. 4 | 5 | // Note: 6 | // 0 ≤ x, y < 2^31. 7 | 8 | // Example: 9 | 10 | // Input: x = 1, y = 4 11 | 12 | // Output: 2 13 | 14 | // Explanation: 15 | // 1 (0 0 0 1) 16 | // 4 (0 1 0 0) 17 | // ↑ ↑ 18 | 19 | // The above arrows point to positions where the corresponding bits are different. 20 | 21 | public class Solution { 22 | 23 | public int hammingDistance(int x, int y) { 24 | 25 | return Integer.bitCount(x ^ y); 26 | 27 | } 28 | 29 | } -------------------------------------------------------------------------------- /LeetCode/BitManipulation/sumOfTwoIntegers.java: -------------------------------------------------------------------------------- 1 | // Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. 2 | 3 | // Example: 4 | // Given a = 1 and b = 2, return 3. 5 | 6 | public class Solution { 7 | 8 | public int getSum(int a, int b) { 9 | 10 | if(a == 0) return b; 11 | if(b == 0) return a; 12 | 13 | while(b != 0) { 14 | 15 | int carry = a & b; 16 | a = a ^ b; 17 | b = carry << 1; 18 | 19 | } 20 | 21 | return a; 22 | 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /LeetCode/DepthFirstSearch/maximumDepthOfABinaryTree.java: -------------------------------------------------------------------------------- 1 | // Given a binary tree, find its maximum depth. 2 | 3 | // The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. 4 | 5 | /** 6 | * Definition for a binary tree node. 7 | * public class TreeNode { 8 | * int val; 9 | * TreeNode left; 10 | * TreeNode right; 11 | * TreeNode(int x) { val = x; } 12 | * } 13 | */ 14 | public class Solution { 15 | 16 | public int maxDepth(TreeNode root) { 17 | 18 | if(root == null) return 0; 19 | 20 | return 1 + Math.max(maxDepth(root.left), maxDepth(root.right)); 21 | 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /LeetCode/DivideAndConquer/kthLargestElementInAnArray.java: -------------------------------------------------------------------------------- 1 | // Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element. 2 | 3 | // For example, 4 | // Given [3,2,1,5,6,4] and k = 2, return 5. 5 | 6 | // Note: 7 | // You may assume k is always valid, 1 ≤ k ≤ array's length. 8 | 9 | public class Solution { 10 | 11 | public int findKthLargest(int[] nums, int k) { 12 | 13 | int length = nums.length; 14 | Arrays.sort(nums); 15 | return nums[length - k]; 16 | 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /LeetCode/DynamicProgramming/climbingStairs.java: -------------------------------------------------------------------------------- 1 | // You are climbing a stair case. It takes n steps to reach to the top. 2 | 3 | // Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 4 | 5 | // Note: Given n will be a positive integer. 6 | 7 | public class Solution { 8 | 9 | public int climbStairs(int n) { 10 | 11 | int[] dp = new int[n + 1]; 12 | 13 | dp[0] = 1; 14 | dp[1] = 1; 15 | 16 | for(int i = 2; i < dp.length; i++) { 17 | 18 | dp[i] = dp[i - 1] + dp[i - 2]; 19 | 20 | } 21 | 22 | return dp[dp.length - 1]; 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /LeetCode/LinkedList/README.md: -------------------------------------------------------------------------------- 1 | List of interview questions pertaining to Linked Lists 2 | -------------------------------------------------------------------------------- /LeetCode/LinkedList/deleteNodeInALinkedList.java: -------------------------------------------------------------------------------- 1 | // Write a function to delete a node (except the tail) in a singly linked list, given only access to that node. 2 | 3 | // Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function. 4 | 5 | /** 6 | * Definition for singly-linked list. 7 | * public class ListNode { 8 | * int val; 9 | * ListNode next; 10 | * ListNode(int x) { val = x; } 11 | * } 12 | */ 13 | public class Solution { 14 | 15 | public void deleteNode(ListNode node) { 16 | 17 | node.val = node.next.val; 18 | node.next = node.next.next; 19 | 20 | } 21 | 22 | } -------------------------------------------------------------------------------- /LeetCode/String/README.md: -------------------------------------------------------------------------------- 1 | List of interview questions pertaining to Strings 2 | -------------------------------------------------------------------------------- /LeetCode/TwoPointers/reverseString.java: -------------------------------------------------------------------------------- 1 | // Write a function that takes a string as input and returns the string reversed. 2 | 3 | // Example: 4 | // Given s = "hello", return "olleh". 5 | 6 | public class Solution { 7 | 8 | public String reverseString(String s) { 9 | 10 | if(s == null || s.length() == 1 || s.length() == 0) return s; 11 | 12 | char[] word = s.toCharArray(); 13 | 14 | for(int i = 0, j = s.length() - 1; i < j; i++, j--) { 15 | 16 | char temp = word[i]; 17 | word[i] = word[j]; 18 | word[j] = temp; 19 | 20 | } 21 | 22 | return new String(word); 23 | 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /LeetCode/leetcode_132-pattern.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Data Structure (stack) 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool find132pattern(vector& nums) { 10 | int s2 = INT_MIN; 11 | stack stk; 12 | for(int i = nums.size() - 1; i >= 0; -- i){ 13 | if(nums[i] < s2) 14 | return true; 15 | else while(!stk.empty() && stk.top() < nums[i]){ 16 | s2 = stk.top(); 17 | stk.pop(); 18 | } 19 | stk.push(nums[i]); 20 | } 21 | return false; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LeetCode/leetcode_2-keys-keyboard.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n^1.5) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | int minSteps(int n) { 10 | if(n == 0){ 11 | return n; 12 | } 13 | 14 | vector dp(n + 1, n); 15 | dp[1] = 0; 16 | for(int i = 2; i <= n; ++ i){ 17 | dp[i] = min(dp[i], i); 18 | 19 | for(int j = 2; j*j <= i; ++ j){ 20 | if(i%j == 0){ 21 | dp[i] = min(dp[i], dp[j] + i/j); 22 | dp[i] = min(dp[i], dp[i/j] + j); 23 | } 24 | } 25 | } 26 | 27 | return dp[n]; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /LeetCode/leetcode_adddigits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Tag: Math 3 | * Time: O(1) 4 | * Space: O(1) 5 | */ 6 | class Solution { 7 | public: 8 | int addDigits(int num) { 9 | return num%9 == 0?(num == 0?0:9):num%9; 10 | } 11 | }; 12 | -------------------------------------------------------------------------------- /LeetCode/leetcode_array-partition-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(ngln) 5 | * Space: O(lgn) 6 | */ 7 | class Solution { 8 | public: 9 | int arrayPairSum(vector& nums) { 10 | int sum = 0; 11 | if(nums.size() == 0) 12 | return sum; 13 | sort(nums.begin(), nums.end()); 14 | for(int i = 0; i < nums.size(); i += 2) 15 | sum += nums[i]; 16 | return sum; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_assign-cookies.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(nlgn) 5 | * Space: O(lgn) 6 | */ 7 | class Solution { 8 | public: 9 | int findContentChildren(vector& g, vector& s) { 10 | if(g.size() == 0 || s.size() == 0) 11 | return 0; 12 | int ans = 0, gid = 0; 13 | sort(g.begin(), g.end()); 14 | sort(s.begin(), s.end()); 15 | for(int i = 0; i < s.size() && gid < g.size(); ++ i){ 16 | if(s[i] >= g[gid]){ 17 | ++ ans, ++ gid; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_base-7.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | string convertToBase7(int num) { 10 | string ans = ""; 11 | if(num == 0){ 12 | ans = "0"; 13 | return ans; 14 | } 15 | int v = 0; 16 | bool isneg = false; 17 | if(num < 0){ 18 | isneg = true; 19 | num = -num; 20 | } 21 | while(num > 0){ 22 | v = num%7; 23 | num /= 7; 24 | ans += to_string(v); 25 | } 26 | if(isneg) 27 | ans += "-"; 28 | reverse(ans.begin(), ans.end()); 29 | return ans; 30 | } 31 | }; 32 | -------------------------------------------------------------------------------- /LeetCode/leetcode_besttimetobuyandsellstockII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Greedy 3 | * Time complexity: O(n) 4 | * Memory complexity: O(n) 5 | */ 6 | class Solution { 7 | public: 8 | int maxProfit(vector &prices) { 9 | int ans = 0; 10 | for(int i = 1; i < prices.size(); i ++){ 11 | if(prices[i] > prices[i - 1]){ 12 | ans += (prices[i] - prices[i - 1]); 13 | } 14 | } 15 | return ans; 16 | } 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_binary-gap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int binaryGap(int N) { 10 | int ans = 0; 11 | int curPos = -1, lastPos = -1, pos = 0; 12 | while(N > 0){ 13 | if(N&1 == 1){ 14 | lastPos = curPos; 15 | curPos = pos; 16 | } 17 | 18 | if(lastPos >= 0){ 19 | ans = max(ans, curPos - lastPos); 20 | } 21 | 22 | N >>= 1; 23 | ++ pos; 24 | } 25 | 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LeetCode/leetcode_binary-number-with-alternating-bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool hasAlternatingBits(int n) { 10 | if(n <= 1){ 11 | return true; 12 | } 13 | 14 | while(n > 0){ 15 | if((n&1) == ((n>>1)&1)){ 16 | return false; 17 | } 18 | 19 | n >>= 1; 20 | } 21 | 22 | return true; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_bulb-switcher.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int bulbSwitch(int n) { 10 | return (int)sqrt(n); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /LeetCode/leetcode_candy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: DP 3 | * Time complexity: O(n) 4 | * Memory complexity: O(n) 5 | */ 6 | class Solution { 7 | public: 8 | int candy(vector &ratings) { 9 | const int n = ratings.size(); 10 | vector res = vector(n,0); 11 | for(int i = 1; i < n; i ++){ 12 | if(ratings[i] > ratings[i - 1]){ 13 | res[i] = max(res[i], res[i - 1] + 1); 14 | } 15 | } 16 | for(int i = n - 2; i >= 0; i --){ 17 | if(ratings[i] > ratings[i + 1]){ 18 | res[i] = max(res[i], res[i + 1] + 1); 19 | } 20 | } 21 | return accumulate(&res[0],&res[0] + n, n); 22 | } 23 | }; 24 | 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int climbStairs(int n) { 10 | int prev = 0; 11 | int cur = 1; 12 | for(int i = 1; i <= n; i ++){ 13 | int tmp = cur; 14 | cur += prev; 15 | prev = tmp; 16 | } 17 | 18 | return cur; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_coin-change-2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(nm) 5 | * Space: O(m) 6 | */ 7 | class Solution { 8 | public: 9 | int change(int amount, vector& coins) { 10 | vector dp(amount + 1, 0); 11 | dp[0] = 1; 12 | for(int i = 0; i < coins.size(); ++ i){ 13 | for(int j = coins[i]; j <= amount; ++ j){ 14 | dp[j] += dp[j - coins[i]]; 15 | } 16 | } 17 | return amount == 0 ? 1 : dp[amount]; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_coin-change.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n*v) where v is the value of amount 5 | * Space: O(v) where v is the value of amount 6 | */ 7 | class Solution { 8 | public: 9 | int coinChange(vector& coins, int amount) { 10 | int ans; 11 | if(!coins.size() && amount) 12 | return -1; 13 | int INF = amount + 1; 14 | vector dp(amount + 1, INF); 15 | dp[0] = 0; 16 | for(int i = 0; i < coins.size(); ++ i){ 17 | for(int j = coins[i]; j <= amount; ++ j){ 18 | dp[j] = min(dp[j], dp[j - coins[i]] + 1); 19 | } 20 | } 21 | 22 | return dp[amount] == INF?-1:dp[amount]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_combination-sum-iv.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(max(nlgn, mn)) where m = target number 5 | * Space: O(m) 6 | */ 7 | class Solution { 8 | public: 9 | int combinationSum4(vector& nums, int target) { 10 | vector dp(target + 1, 0); 11 | if(!nums.size() || !target) { 12 | return 0; 13 | } 14 | 15 | sort(nums.begin(), nums.end()); 16 | 17 | dp[0] = 1; 18 | for(int i = 1; i <= target; ++ i){ 19 | for(int j = 0; j < nums.size() && nums[j] <= i; ++ j){ 20 | dp[i] += dp[i - nums[j]]; 21 | } 22 | } 23 | 24 | return dp[target]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/leetcode_construct-the-rectangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(sqrt(n)) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | vector constructRectangle(int area) { 10 | vector ans(2); 11 | int w = (int)sqrt(area); 12 | while(w >= 1){ 13 | if(area%w == 0){ 14 | ans[0] = area/w, ans[1] = w; 15 | break; 16 | } 17 | -- w; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_container-with-most-water.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * TODO 4 | * Tag: Two Pointers 5 | * Time: O(n) 6 | * Space: O(1) 7 | */ 8 | class Solution { 9 | public: 10 | int maxArea(vector &height) { 11 | int l = 0, r = height.size() - 1; 12 | int ans = INT_MIN; 13 | while(l < r){ 14 | ans = max(ans, min(height[l],height[r])*(r - l)); 15 | if(height[l] <= height[r]){ 16 | l ++; 17 | }else{ 18 | r --; 19 | } 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_contains-duplicate-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Hash (Data Structure) 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | bool containsNearbyDuplicate(vector& nums, int k) { 10 | if(nums.size() == 0) 11 | return false; 12 | 13 | unordered_map dict; 14 | for(int i = 0; i < nums.size(); ++ i){ 15 | if(dict.find(nums[i]) == dict.end()){ 16 | dict[nums[i]] = i; 17 | }else{ 18 | if(abs(i - dict[nums[i]]) <= k) 19 | return true; 20 | dict[nums[i]] = i; 21 | } 22 | } 23 | 24 | return false; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/leetcode_contains-duplicate.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Sort 4 | * Time: O(nlgn) 5 | * Space: O(lgn) 6 | */ 7 | class Solution { 8 | public: 9 | bool containsDuplicate(vector& nums) { 10 | if(!nums.size()) 11 | return false; 12 | sort(nums.begin(), nums.end()); 13 | for(int i = 1; i < nums.size(); ++ i){ 14 | if(nums[i] == nums[i - 1]) 15 | return true; 16 | } 17 | return false; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_convert-a-number-to-hexadecimal.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | string toHex(int num) { 10 | unsigned int val = (int)num; 11 | string res = ""; 12 | do{ 13 | res = dict[(val&mask)] + res; 14 | val >>= 4; 15 | }while(val); 16 | return res; 17 | } 18 | private: 19 | string dict="0123456789abcdef"; 20 | int mask=15; 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_convex-polygon.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Geometry 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isConvex(vector>& p) { 10 | long n = p.size(), prev = 0, cur; 11 | for (int i = 0; i < n; ++i) { 12 | vector> A; // = {p[(i+1)%n]-p[i], p[(i+2)%n]-p[i]} 13 | for (int j = 1; j < 3; ++j) A.push_back({p[(i+j)%n][0]-p[i][0], p[(i+j)%n][1]-p[i][1]}); 14 | if (cur = det2(A)) if (cur*prev < 0) return false; else prev = cur; 15 | } 16 | return true; 17 | } 18 | 19 | long det2(vector>& A) { return A[0][0]*A[1][1] - A[0][1]*A[1][0]; } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_count-and-say.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | string countAndSay(int n) { 10 | string s("1"); 11 | 12 | while(--n){ 13 | s = getNext(s); 14 | } 15 | 16 | return s; 17 | } 18 | 19 | string getNext(const string &s) { 20 | stringstream ss; 21 | 22 | for(auto i = s.begin(); i != s.end(); ){ 23 | auto j = find_if(i,s.end(),bind1st(not_equal_to(),*i)); 24 | ss << distance(i, j) << *i; 25 | i = j; 26 | } 27 | 28 | return ss.str(); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /LeetCode/leetcode_count-numbers-with-unique-digits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | private: 9 | vector dp; 10 | public: 11 | int countNumbersWithUniqueDigits(int n) { 12 | init(); 13 | return n <= 10? dp[n]:dp[10]; 14 | } 15 | 16 | private: 17 | void init(){ 18 | dp.resize(11); 19 | 20 | dp[0] = 1; 21 | dp[1] = 10; 22 | dp[10] = 0; 23 | int fact = 9, res = 1; 24 | for(int i = 9, j = 2; i >= 1; -- i, ++ j){ 25 | res *= i; 26 | dp[j] = dp[j - 1] + fact*res; 27 | } 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /LeetCode/leetcode_detect-capital.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool detectCapitalUse(string word) { 10 | int capital_cnt = 0; 11 | bool isFirstCapital = false; 12 | for(int i = 0; i < word.size(); ++ i){ 13 | if(word[i] >= 'A' && word[i] <= 'Z'){ 14 | ++ capital_cnt; 15 | if(i == 0) 16 | isFirstCapital = true; 17 | } 18 | } 19 | return capital_cnt == 0 || capital_cnt == word.size() || (capital_cnt == 1 && isFirstCapital); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_domino-and-tromino-tiling.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Better Solution 4 | * Tag: DP 5 | * Time: O(n^2) 6 | * Space: O(n) 7 | */ 8 | class Solution { 9 | private: 10 | const int MOD = 1000000007; 11 | public: 12 | int numTilings(int N) { 13 | vector dp(N + 1, 0); 14 | dp[0] = 1; 15 | for(int i = 1; i <= N; ++ i){ 16 | for(int j = 1; j <= i; ++ j){ 17 | dp[i] += (dp[i - j]*(j <= 2 ? 1 : 2))%MOD; 18 | dp[i] %= MOD; 19 | } 20 | } 21 | 22 | return dp[N]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_elimination-game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int lastRemaining(int n) { 10 | int res = 1, cnt = 0, p = 1; 11 | while(n > 1){ 12 | n >>= 1; 13 | p <<= 1; 14 | ++ cnt; 15 | if(cnt%2) 16 | res += p/2 + p*(n - 1); 17 | else 18 | res -= p/2 + p*(n - 1); 19 | } 20 | return res; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_escape-the-ghosts.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool escapeGhosts(vector>& ghosts, vector& target) { 10 | vector source = {0, 0}; 11 | for(vector ghost : ghosts){ 12 | if(manhattanDistance(ghost, target) <= manhattanDistance(source, target)){ 13 | return false; 14 | } 15 | } 16 | 17 | return true; 18 | } 19 | private: 20 | int manhattanDistance(vector source, vector target){ 21 | return abs(source[0] - target[0]) + abs(source[1] - target[1]); 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LeetCode/leetcode_factorial-trailing-zeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int trailingZeroes(int n) { 11 | int ans = 0; 12 | if(n < 5) { 13 | return ans; 14 | } 15 | 16 | int p = 5; 17 | long long k = 5; 18 | while(n/k){ 19 | ans += n/k; 20 | k *= p; 21 | } 22 | 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_find-anagram-mappings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Data Structure (Hash) 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | vector anagramMappings(vector& A, vector& B) { 10 | vector ans(A.size()); 11 | if(A.size() == 0){ 12 | return ans; 13 | } 14 | 15 | unordered_map indexOfElementsInArrayB; 16 | for(int i = 0; i < B.size(); ++ i){ 17 | indexOfElementsInArrayB[B[i]] = i; 18 | } 19 | 20 | for(int i = 0; i < A.size(); ++ i){ 21 | ans[i] = indexOfElementsInArrayB[A[i]]; 22 | } 23 | 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/leetcode_find-bottom-left-tree-value.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(h) 6 | */ 7 | class Solution { 8 | public: 9 | int findBottomLeftValue(TreeNode* root) { 10 | int ans = 0, h = -1; 11 | dfs(root, ans, h, 0); 12 | return ans; 13 | } 14 | private: 15 | void dfs(TreeNode* root, int &ans, int &h, int dep){ 16 | if(dep > h){ 17 | ans = root->val; 18 | h = dep; 19 | } 20 | if(root->left) 21 | dfs(root->left, ans, h, dep + 1); 22 | if(root->right) 23 | dfs(root->right, ans, h, dep + 1); 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_find-permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | vector findPermutation(string s) { 10 | vector ans; 11 | if(s.size() == 0) 12 | return ans; 13 | for(int i = 0; i <= s.size(); ++ i){ 14 | if(i == s.size() || s[i] == 'I'){ 15 | for(int j = i + 1, k = ans.size(); j > k; -- j){ 16 | ans.push_back(j); 17 | } 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_find-smallest-letter-greater-than-target.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Binary Search 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | char nextGreatestLetter(vector& letters, char target) { 10 | if(target >= letters.back() || target < letters.front()){ 11 | return letters.front(); 12 | } 13 | 14 | int l = 0, r = letters.size() - 1; 15 | while(l < r){ 16 | int mid = (l + r)>>1; 17 | if(letters[mid] > target) { 18 | r = mid; 19 | } else { 20 | l = mid + 1; 21 | } 22 | } 23 | 24 | return letters[l]; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/leetcode_first-bad-version.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Binary Search 4 | * Time: O(logn) 5 | * Space: O(1) 6 | * 7 | // Forward declaration of isBadVersion API. 8 | bool isBadVersion(int version); 9 | 10 | class Solution { 11 | public: 12 | int firstBadVersion(int n) { 13 | int ans = n; 14 | if(n < 2) 15 | return n; 16 | long long l = 1, r = n; 17 | while(l <= r){ 18 | long long mid = (l + r)>>1; 19 | if(isBadVersion(mid)){ 20 | ans = (int)mid; 21 | r = mid - 1; 22 | }else 23 | l = mid + 1; 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LeetCode/leetcode_fizzbuzz.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | vector fizzBuzz(int n) { 10 | vector ans; 11 | if(!n) 12 | return ans; 13 | ans.resize(n); 14 | string tmp = ""; 15 | for(int i = 0; i < n; ++ i){ 16 | tmp = ""; 17 | if((i + 1)%3 != 0 && (i + 1)%5 != 0) 18 | tmp = to_string((i+1)); 19 | if((i + 1)%3 == 0) 20 | tmp += "Fizz"; 21 | if((i + 1)%5 == 0) 22 | tmp += "Buzz"; 23 | ans[i] = tmp; 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LeetCode/leetcode_flipgame.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementaion 4 | * Time: O(n) 5 | * Space: O(1) (excluding the vector space for saving results) 6 | */ 7 | class Solution { 8 | public: 9 | vector generatePossibleNextMoves(string s) { 10 | vector ans; 11 | if(s.size() < 2) 12 | return ans; 13 | for(int i = 0; i < s.size() - 1; ++ i){ 14 | if(s[i] == '+' && s[i + 1] == '+'){ 15 | s[i] = s[i+ 1] = '-'; 16 | ans.push_back(s); 17 | s[i] = s[i+ 1] = '+'; 18 | } 19 | } 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_gas-station.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int canCompleteCircuit(vector& gas, vector& cost) { 11 | int start = 0, total = 0, tank = 0; 12 | for(int i = 0; i < gas.size(); ++ i){ 13 | tank += gas[i] - cost[i]; 14 | if(tank < 0){ 15 | start = i + 1; 16 | total += tank; 17 | tank = 0; 18 | } 19 | } 20 | 21 | return (total + tank < 0) ? -1 : start; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LeetCode/leetcode_gasstation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Algorithm: Greedy 4 | * Time Complexity: O(n) 5 | * Memory Complexity: O(n) 6 | * 7 | */ 8 | 9 | class Solution { 10 | public: 11 | int canCompleteCircuit(vector &gas, vector &cost) { 12 | double rate = -9999999.99; 13 | int ind = 0, totgas = 0, totcost = 0; 14 | for(int i = 0; i < gas.size(); i ++){ 15 | totgas += gas[i]; 16 | totcost += cost[i]; 17 | if(rate < (double)gas[i]/(double)cost[i]){ 18 | rate = (double)gas[i]/(double)cost[i]; 19 | ind = i; 20 | } 21 | } 22 | return totgas >= totcost? ind : -1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_graycode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Brute force, Implementation 3 | * Time complexity: O(2^n) 4 | * Memory complexity: O(2^n) 5 | */ 6 | class Solution { 7 | public: 8 | vector grayCode(int n) { 9 | vector res; 10 | res.reserve(1<= 0; j --){ 15 | res.push_back(high_bit | res[j]); 16 | } 17 | } 18 | return res; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_guess-number-higher-or-lower.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Binary Search 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | int guess(int num); 8 | 9 | class Solution { 10 | public: 11 | int guessNumber(int n) { 12 | long long l = 1, r = n; 13 | int ans = 1; 14 | while(l <= r){ 15 | long long mid = (l + r)>>1; 16 | int v = guess((int)mid); 17 | if(v == 0){ 18 | ans = mid; 19 | break; 20 | }else if(v == 1){ 21 | l = mid + 1; 22 | }else{ 23 | r = mid - 1; 24 | } 25 | } 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LeetCode/leetcode_hamming-distance.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int hammingDistance(int x, int y) { 10 | int v = x^y, res = 0; 11 | while(v > 0){ 12 | if(v&1) 13 | ++ res; 14 | v >>= 1; 15 | } 16 | return res; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_increasing-triplet-subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force (Two Pointers) 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool increasingTriplet(vector& nums) { 10 | if(nums.size() < 3) 11 | return false; 12 | int p1 = nums[0], p2 = INT_MAX; 13 | for(int i = 1; i < nums.size(); ++ i){ 14 | if(nums[i] < p1){ 15 | p1 = nums[i]; 16 | }else if(nums[i] > p2){ 17 | return true; 18 | }else if(nums[i] > p1 && nums[i] < p2){ 19 | p2 = nums[i]; 20 | } 21 | } 22 | return false; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_integertoroman.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Brute force, Simulate 3 | * Time complexity: O(num) 4 | * Memory complexity: O(n) 5 | */ 6 | class Solution { 7 | public: 8 | string intToRoman(int num) { 9 | const int radix[] = {1000, 900, 500, 400, 100, 90,50, 40, 10, 9, 5, 4, 1}; 10 | const string symbol[] = {"M", "CM", "D", "CD", "C", "XC","L", "XL", "X","IX", "V", "IV", "I"}; 11 | 12 | string roman; 13 | for(size_t i = 0; num > 0; ++ i){ 14 | int count = num/radix[i]; 15 | num %= radix[i]; 16 | for(; count > 0; -- count) 17 | roman += symbol[i]; 18 | } 19 | return roman; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_intersection-of-two-linked-lists.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * TODO 4 | * Tag: Two Pointers 5 | * Time: O(n) 6 | * Space: O(1) 7 | */ 8 | /** 9 | * Definition for singly-linked list. 10 | * struct ListNode { 11 | * int val; 12 | * ListNode *next; 13 | * ListNode(int x) : val(x), next(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { 19 | ListNode *pA = headA, *pB = headB; 20 | while(pA != pB){ 21 | pA = pA ? pA->next : headB; 22 | pB = pB ? pB->next : headA; 23 | } 24 | 25 | return pA; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LeetCode/leetcode_is-subsequence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isSubsequence(string s, string t) { 10 | int n = s.size(), m = t.size(), i = 0, j = 0; 11 | while(i < n && j < m){ 12 | if(s[i] == t[j]) 13 | ++ i; 14 | ++ j; 15 | } 16 | return i == n; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_isomorphic-strings.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Hash 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isIsomorphic(string s, string t) { 10 | char s_mp[300] = {0}, t_mp[300] = {0}; 11 | for(int i = 0; i < s.size(); ++ i){ 12 | s_mp[s[i]] = t[i]; 13 | t_mp[t[i]] = s[i]; 14 | } 15 | for(int i = 0; i < s.size(); ++ i){ 16 | if(s_mp[s[i]] != t[i] || t_mp[t[i]] != s[i]) 17 | return false; 18 | } 19 | return true; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_jewels-and-stones.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Hash 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | int numJewelsInStones(string J, string S) { 10 | int ans = 0; 11 | if(J.size() == 0 || S.size() == 0){ 12 | return ans; 13 | } 14 | 15 | unordered_set jewels; 16 | for(int i = 0; i < J.size(); ++ i){ 17 | jewels.insert(J[i]); 18 | } 19 | 20 | for(int i = 0; i < S.size(); ++ i){ 21 | if(jewels.count(S[i]) != 0){ 22 | ++ ans; 23 | } 24 | } 25 | 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LeetCode/leetcode_jump-game.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool canJump(vector& nums) { 11 | int reach = 1, n = nums.size(); 12 | for(int i = 0; i < reach && reach < n; i ++){ 13 | reach = max(reach, nums[i] + i + 1); 14 | } 15 | 16 | return reach >= n; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_jumpgame.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: DP 3 | * Time complexity: O(n) 4 | * Memory complexity: O(1) 5 | */ 6 | class Solution { 7 | public: 8 | bool canJump(int A[], int n) { 9 | int reach = 1; 10 | for(int i = 0; reach < n && i < reach; i ++){ 11 | reach = max(reach, A[i] + i + 1); 12 | } 13 | return reach >= n; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /LeetCode/leetcode_k-th-symbol-in-grammar.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation + DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | private: 9 | const string SYMBOLS = "0110100110010110"; 10 | public: 11 | int kthGrammar(int N, int K) { 12 | if(N <= 5){ 13 | return (SYMBOLS[(K - 1)%SYMBOLS.size()] - '0'); 14 | } 15 | 16 | int halfLenOfSymbols = 1<<(N - 2); 17 | return K <= halfLenOfSymbols ? kthGrammar(N - 1, K) : (kthGrammar(N - 1, K - halfLenOfSymbols)^1); 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_kth-largest-element-in-a-stream.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Heap (Data Structure) 4 | * Time: O(nlgn) 5 | * Space: O(k) 6 | */ 7 | 8 | class KthLargest { 9 | private: 10 | priority_queue, greater> pq; 11 | int sizeOfQueue; 12 | public: 13 | KthLargest(int k, vector nums) { 14 | sizeOfQueue = k; 15 | for(int num : nums){ 16 | add(num); 17 | } 18 | } 19 | 20 | int add(int val) { 21 | pq.push(val); 22 | 23 | while(pq.size() > sizeOfQueue){ 24 | pq.pop(); 25 | } 26 | 27 | return pq.top(); 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /LeetCode/leetcode_lengthoflastword.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Brute force 3 | * Time complexity: O(n) 4 | * Memory complexity: O(1) 5 | */ 6 | class Solution { 7 | public: 8 | int lengthOfLastWord(const char *s) { 9 | // Start typing your C/C++ solution below 10 | // DO NOT write int main() function 11 | if(s[0]=='\0') return 0; 12 | int ans = 0, cnt = 0; 13 | for(int i = 0; s[i]!='\0'; i ++){ 14 | if(s[i]==' '){ 15 | if(cnt != 0) ans = cnt; 16 | cnt = 0; 17 | }else{ 18 | cnt ++; 19 | } 20 | } 21 | if(cnt != 0) ans = cnt; 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_longest-uncommon-subsequence-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int findLUSlength(string a, string b) { 10 | return a == b?-1:max(a.size(), b.size()); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /LeetCode/leetcode_magical-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: String 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | int magicalString(int n) { 10 | string S = "122"; 11 | int i = 2; 12 | while (S.size() < n){ 13 | S += string(S[i++] - '0', S.back() ^ 3); 14 | } 15 | return count(S.begin(), S.begin() + n, '1'); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LeetCode/leetcode_majority-element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int majorityElement(vector &nums) { 10 | int ans = 0, count = 0; 11 | for(int num : nums){ 12 | if(count == 0){ 13 | ++ count; 14 | ans = num; 15 | } else if(ans != num) { 16 | -- count; 17 | } else { 18 | ++ count; 19 | } 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_max-consecutive-ones.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int findMaxConsecutiveOnes(vector& nums) { 10 | int ans = 0; 11 | if(nums.size() == 0) 12 | return ans; 13 | int sum = 0; 14 | for(int i = 0; i < nums.size(); ++ i){ 15 | sum = (sum + nums[i])*nums[i]; 16 | ans = max(ans, sum); 17 | } 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_maximum-average-subarray-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | double findMaxAverage(vector& nums, int k) { 10 | int maxSum = INT_MIN, sum = 0; 11 | for(int i = 0; i < nums.size(); ++ i){ 12 | if(i >= k){ 13 | sum -= nums[i - k]; 14 | } 15 | 16 | sum += nums[i]; 17 | if(i >= k - 1){ 18 | maxSum = max(maxSum, sum); 19 | } 20 | } 21 | 22 | return (double)maxSum/k; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int maxSubArray(vector& nums) { 10 | int ans = nums[0]; 11 | int sum = nums[0]; 12 | for(int i = 1; i < nums.size(); i ++){ 13 | if(sum + nums[i] > nums[i]){ 14 | sum += nums[i]; 15 | }else{ 16 | sum = nums[i]; 17 | } 18 | 19 | ans = max(ans, sum); 20 | } 21 | 22 | return ans; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_min-cost-climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int minCostClimbingStairs(vector& cost) { 10 | if(cost.size() == 2){ 11 | return min(cost[0], cost[1]); 12 | } 13 | 14 | int numOfStairs = cost.size(); 15 | vector dp(3, 0); 16 | for(int i = 2; i <= numOfStairs; ++ i){ 17 | dp[2] = min(dp[0] + cost[i - 2], dp[1] + cost[i - 1]); 18 | dp[0] = dp[1], dp[1] = dp[2]; 19 | } 20 | return min(dp[1], dp[2]); 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_min-stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Data Structure 4 | * Time: O(1) 5 | * Space: O(n) 6 | */ 7 | class MinStack { 8 | public: 9 | void push(int x) { 10 | all_val.push(x); 11 | if(min_val.empty() || x <= min_val.top()) 12 | min_val.push(x); 13 | } 14 | 15 | void pop() { 16 | int val = all_val.top(); 17 | all_val.pop(); 18 | if(val == min_val.top()) 19 | min_val.pop(); 20 | } 21 | 22 | int top() { 23 | return all_val.top(); 24 | } 25 | 26 | int getMin() { 27 | return min_val.top(); 28 | } 29 | private: 30 | stack all_val, min_val; 31 | }; 32 | -------------------------------------------------------------------------------- /LeetCode/leetcode_minimum-moves-to-equal-array-elements.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time:O(n) 5 | * Space:O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int minMoves(vector& nums) { 10 | int ans = 0; 11 | if(nums.size() == 0) 12 | return ans; 13 | int minval = INT_MAX; 14 | for(int i = 0; i < nums.size(); ++ i) 15 | minval = min(minval, nums[i]); 16 | for(int i = 0; i < nums.size(); ++ i) 17 | ans += (nums[i] - minval); 18 | return ans; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_my-calendar-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Data Structure (Binary Search Tree) 4 | * Time: O(lgn) 5 | * Space: O(n) 6 | */ 7 | class MyCalendar { 8 | private: 9 | map scheduledEvent; 10 | public: 11 | MyCalendar() { 12 | scheduledEvent.clear(); 13 | } 14 | 15 | bool book(int start, int end) { 16 | auto it = scheduledEvent.lower_bound(start); 17 | 18 | if(it->first == start){ 19 | ++ it; 20 | } 21 | 22 | if(it != scheduledEvent.end() && it->second < end){ 23 | return false; 24 | } 25 | 26 | scheduledEvent[end] = start; 27 | 28 | return true; 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /LeetCode/leetcode_my-calendar-iii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Binary Search Tree 4 | * Time: O(n^2) 5 | * Space: O(n) 6 | */ 7 | class MyCalendarThree { 8 | private: 9 | map timeScheduler; 10 | public: 11 | MyCalendarThree() { 12 | timeScheduler.clear(); 13 | } 14 | 15 | int book(int start, int end) { 16 | ++ timeScheduler[start]; 17 | -- timeScheduler[end]; 18 | 19 | int ans = 0, delta = 0; 20 | for(auto it = timeScheduler.begin(); it != timeScheduler.end(); ++ it){ 21 | delta += it->second; 22 | ans = max(ans, delta); 23 | } 24 | 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LeetCode/leetcode_next-greater-element-iii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | int nextGreaterElement(int n) { 10 | if(n <= 10) 11 | return -1; 12 | string v = to_string(n); 13 | next_permutation(begin(v), end(v)); 14 | long long ans = stoll(v); 15 | return (ans > INT_MAX || ans <= n) ? -1 : (int)ans; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LeetCode/leetcode_nimgame.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Game Theory 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool canWinNim(int n) { 10 | return n%4; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /LeetCode/leetcode_number-complement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int findComplement(int num) { 10 | int ans = 0, mask = 1; 11 | while(num){ 12 | if((num&1) == 0) 13 | ans |= mask; 14 | num >>= 1; 15 | mask <<= 1; 16 | } 17 | return ans; 18 | } 19 | }; 20 | 21 | class Solution { 22 | public: 23 | int findComplement(int num) { 24 | unsigned int mask = ~0; 25 | while(num & mask) mask <<= 1; 26 | return ~num & ~mask; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LeetCode/leetcode_number-of-1-bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int hammingWeight(uint32_t n) { 11 | int cnt = 0; 12 | while(n > 0){ 13 | if(n&1) ++ cnt; 14 | n >>= 1; 15 | } 16 | 17 | return cnt; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_number-of-segments-in-a-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int countSegments(string s) { 10 | int res = 0; 11 | bool meetSpace = true; 12 | if(s.size() == 0) 13 | return res; 14 | for(int i = 0; i < s.size(); ++ i){ 15 | if(s[i] == ' ') 16 | meetSpace = true; 17 | else{ 18 | if(meetSpace) 19 | ++ res; 20 | meetSpace = false; 21 | } 22 | } 23 | return res; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_online-stock-span.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Stack (Data Structure) 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | 8 | class StockSpanner { 9 | private: 10 | stack> stockSpans; 11 | 12 | public: 13 | int next(int price) { 14 | int span = 1; 15 | while(!stockSpans.empty()){ 16 | pair lastStockSpan = stockSpans.top(); 17 | if(lastStockSpan.first > price){ 18 | break; 19 | } 20 | 21 | span += lastStockSpan.second; 22 | stockSpans.pop(); 23 | } 24 | stockSpans.push(make_pair(price, span)); 25 | 26 | return span; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LeetCode/leetcode_optimal-division.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | string optimalDivision(vector& nums) { 10 | string ans = ""; 11 | int n = nums.size(); 12 | for(int i = 0; i < n; ++ i){ 13 | if(i >= 1) 14 | ans += "/"; 15 | if(i == 1 && n >= 3) 16 | ans += "("; 17 | ans += to_string(nums[i]); 18 | if(i == n - 1 && n >= 3) 19 | ans += ")"; 20 | } 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LeetCode/leetcode_output-contest-matches.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(nlgn) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | string findContestMatch(int n) { 10 | vector game_match( n + 1 ); 11 | int tot = 0; 12 | for(int i = 1; i <= n; ++ i ) 13 | game_match[tot ++] = to_string(i); 14 | while(tot > 1){ 15 | for(int i = 0; i < tot/2; ++ i) 16 | game_match[i] = "("+game_match[i]+","+game_match[tot - i - 1]+")"; 17 | tot >>= 1; 18 | } 19 | return game_match[0]; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_pascaltriangleII.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Brute force 3 | * Time complexity: O(n^2) 4 | * Memory complexity: O(n) 5 | */ 6 | class Solution { 7 | public: 8 | vector getRow(int rowIndex) { 9 | vector ans = vector(rowIndex + 1,0); 10 | ans[0] = 1; 11 | for(int i = 1; i <= rowIndex; i ++){ 12 | ans[i] = 1; 13 | for(int j = i - 1; j > 0; j --){ 14 | ans[j] = ans[j] + ans[j - 1]; 15 | } 16 | } 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_patching-array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int minPatches(vector& nums, int n) { 10 | long miss = 1; 11 | int cnt = 0, i = 0; 12 | while(miss <= n){ 13 | if(i < nums.size() && nums[i] <= miss){ 14 | miss += nums[i ++]; 15 | }else{ 16 | miss += miss; 17 | ++ cnt; 18 | } 19 | } 20 | return cnt; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_peak-index-in-a-mountain-array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int peakIndexInMountainArray(vector& A) { 10 | int ans = 1; 11 | 12 | for(int i = 1; i < A.size(); ++ i){ 13 | if(A[i] > A[i - 1]){ 14 | ans = i; 15 | } else { 16 | break; 17 | } 18 | } 19 | 20 | return ans; 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_perfect-number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(n^0.5) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool checkPerfectNumber(int num) { 10 | if(num <= 1) 11 | return false; 12 | int sum = 0, n = sqrt(num); 13 | for(int i = 2; i <= n; ++ i){ 14 | if(num%i == 0) 15 | sum += (i + (i*i == num?0:num/i)); 16 | } 17 | ++ sum; 18 | return sum == num; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_poor-pigs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int poorPigs(int buckets, int minutesToDie, int minutesToTest) { 10 | if(buckets <= 1) 11 | return 0; 12 | long long t = (minutesToTest - 1)/minutesToDie + 1; 13 | return log(buckets - 1)/log(t + 1) + 1; 14 | } 15 | }; 16 | -------------------------------------------------------------------------------- /LeetCode/leetcode_power-of-four.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isPowerOfFour(int num) { 10 | return num > 0 && !(num&(num-1)) && ((num&1431655765)==num); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /LeetCode/leetcode_power-of-three.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isPowerOfThree(int n) { 10 | return n == 0? false : log10(n)/log10(3) == floor(log10(n)/log10(3)); 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /LeetCode/leetcode_power-of-two.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isPowerOfTwo(int n) { 10 | return n>0 && (n&(n-1))==0; 11 | } 12 | }; 13 | -------------------------------------------------------------------------------- /LeetCode/leetcode_range-addition-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int maxCount(int m, int n, vector>& ops) { 10 | for(int i = 0; i < ops.size(); ++ i){ 11 | m = min(m, ops[i][0]); 12 | n = min(n, ops[i][1]); 13 | } 14 | return m*n; 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LeetCode/leetcode_rectangle-overlap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | bool isRectangleOverlap(vector& rec1, vector& rec2) { 11 | if(rec1.size() == 0 || rec2.size() == 0){ 12 | return true; 13 | } 14 | 15 | return rec1[0] < rec2[2] && rec2[0] < rec1[2] && rec1[1] < rec2[3] && rec2[1] < rec1[3]; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LeetCode/leetcode_remove-9.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int newInteger(int n) { 10 | int ans = 0, fac = 1; 11 | while(n > 0){ 12 | ans += (n%9)*fac; 13 | n /= 9; 14 | fac *= 10; 15 | } 16 | 17 | return ans; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Two Pointers 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | int removeDuplicates(vector& nums) { 11 | int n = nums.size(); 12 | if(n == 0) { 13 | return 0; 14 | } 15 | 16 | int len = n, i = 0, j = 1; 17 | for(; j < n; j ++){ 18 | if(nums[i] != nums[j]){ 19 | nums[++i] = nums[j]; 20 | len --; 21 | } 22 | } 23 | i ++; 24 | 25 | return i; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LeetCode/leetcode_removeelement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Brute force 3 | * Time complexity: O(n) 4 | * Memory complexity: O(n) 5 | */ 6 | class Solution { 7 | public: 8 | int removeElement(int A[], int n, int elem) { 9 | int loc_idx = 0; 10 | int len = n; 11 | for(int i = 0; i < n; i ++){ 12 | if(elem != A[i]){ 13 | A[loc_idx] = A[i]; 14 | ++ loc_idx; 15 | }else 16 | len --; 17 | } 18 | return len; 19 | } 20 | }; 21 | 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_reverse-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | string reverseString(string s) { 10 | if(!s.size()) 11 | return s; 12 | int i = 0, j = s.size() - 1; 13 | while(i < j){ 14 | swap(s[i], s[j]); 15 | ++ i; 16 | -- j; 17 | } 18 | return s; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_search-in-a-binary-search-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | /** 8 | * Definition for a binary tree node. 9 | * struct TreeNode { 10 | * int val; 11 | * TreeNode *left; 12 | * TreeNode *right; 13 | * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 14 | * }; 15 | */ 16 | class Solution { 17 | public: 18 | TreeNode* searchBST(TreeNode* root, int val) { 19 | return root == NULL ? NULL : root->val == val? root : root->val > val ? searchBST(root->left, val) : searchBST(root->right, val); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LeetCode/leetcode_set-mismatch.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Hash 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | vector findErrorNums(vector& nums) { 10 | vector ans(2); 11 | if(nums.size() < 1) { 12 | return ans; 13 | } 14 | 15 | for(int i = 0; i < nums.size(); ++ i) { 16 | while(nums[i] != nums[nums[i] - 1]) { 17 | swap(nums[i], nums[nums[i] - 1]); 18 | } 19 | } 20 | 21 | for(int i = 0; i < nums.size(); ++ i) { 22 | if(nums[i] != i + 1) 23 | return {nums[i], i + 1}; 24 | } 25 | 26 | return ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LeetCode/leetcode_shortest-unsorted-continuous-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Sort 4 | * Time: O(nlgn) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | int findUnsortedSubarray(vector& nums) { 10 | vector tmparr(nums); 11 | sort(tmparr.begin(), tmparr.end()); 12 | int lbnd = 0, rbnd = nums.size() - 1; 13 | for(; lbnd < nums.size() && tmparr[lbnd] == nums[lbnd]; ++ lbnd) ; 14 | if(lbnd >= nums.size()) 15 | return 0; 16 | for(; rbnd >= 0 && tmparr[rbnd] == nums[rbnd]; -- rbnd) ; 17 | return rbnd - lbnd + 1; 18 | } 19 | }; 20 | -------------------------------------------------------------------------------- /LeetCode/leetcode_single-number-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Tag: Bit Manipulation 3 | * Time : O(n) 4 | * Memory : O(1) 5 | */ 6 | class Solution { 7 | public: 8 | int singleNumber(vector& nums) { 9 | vector bitCount(32, 0); 10 | if(nums.size() == 1){ 11 | return nums[0]; 12 | } 13 | 14 | for(int num : nums){ 15 | for(int i = 0; i < 32; ++ i){ 16 | bitCount[i] = (bitCount[i] + ((num>>i)&1))%3; 17 | } 18 | } 19 | 20 | int ans = 0; 21 | for(int i = 0; i < bitCount.size(); ++ i){ 22 | ans |= (bitCount[i]<= lbit){ 13 | long long hres = n&high, lres = low&n; 14 | if((hres && !lres) || (!hres && lres)){ 15 | n = n^high; 16 | n = n^low; 17 | } 18 | -- hbit; 19 | ++ lbit; 20 | high >>= 1; 21 | low <<= 1; 22 | } 23 | return n; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_singlenumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time : O(n) 5 | * Memory : O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int singleNumber(vector& nums) { 10 | int ans = 0; 11 | for(int num : nums){ 12 | ans ^= num; 13 | } 14 | 15 | return ans; 16 | } 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_sort-colors.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Hash 4 | * Tinme: O(n) 5 | * Space: O(1) 6 | */ 7 | 8 | class Solution { 9 | public: 10 | void sortColors(vector& nums) { 11 | int colCnt[3] = {0}; 12 | for(int num : nums) 13 | colCnt[num] ++; 14 | int idx = 0; 15 | for(int i = 0; i < 3; i ++){ 16 | for(int j = 0; j < colCnt[i]; j ++){ 17 | nums[idx] = i; 18 | ++ idx; 19 | } 20 | } 21 | } 22 | }; 23 | -------------------------------------------------------------------------------- /LeetCode/leetcode_sqrtx.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: Binary Search 3 | * Time complexity: O(logx) 4 | * Memory complexity: O(1) 5 | */ 6 | class Solution { 7 | public: 8 | int sqrt(int x) { 9 | // Start typing your C/C++ solution below 10 | // DO NOT write int main() function 11 | int l = 1, r = 46341; 12 | int mid = (l + r)>>1; 13 | if(x<=1) return x; 14 | while(l<=r) 15 | { 16 | mid = (l + r) >> 1; 17 | long long tmp = mid*mid; 18 | if(tmp == x) {r = mid;break;} 19 | else if(tmp < x) l = mid + 1; 20 | else r = mid - 1; 21 | } 22 | if((long long)r*r > x) r --; 23 | return r; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_student-attendance-record-i.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool checkRecord(string s) { 10 | if(s.size() == 0) 11 | return true; 12 | int cntA = 0, cntL = 0, n = s.size(); 13 | for(int i = 0; i < n; ++ i){ 14 | if(s[i] == 'L'){ 15 | ++ cntL; 16 | }else{ 17 | cntL = 0; 18 | if(s[i] == 'A') 19 | ++ cntA; 20 | } 21 | if(cntA > 1 || cntL > 2) 22 | return false; 23 | } 24 | return true; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/leetcode_subarray-sum-equals-k.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Data Structure (HashMap) 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | int subarraySum(vector& nums, int k) { 10 | int ans = 0; 11 | if(nums.size() == 0) 12 | return ans; 13 | unordered_map dict; 14 | dict.clear(); 15 | int sum = 0; 16 | for(int i = 0; i < nums.size(); ++ i){ 17 | sum += nums[i]; 18 | if(sum == k) 19 | ++ ans; 20 | if(dict.count(sum - k)) 21 | ans += dict[sum - k]; 22 | ++ dict[sum]; 23 | } 24 | return ans; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LeetCode/leetcode_super-washing-machines.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int findMinMoves(vector& machines) { 10 | int ans = 0; 11 | if(machines.size() == 0) 12 | return ans; 13 | int sum = 0, n = machines.size(); 14 | for(int i = 0; i < n; ++ i) 15 | sum += machines[i]; 16 | if(sum%n != 0) 17 | return -1; 18 | int avg = sum/n, res = 0, tmpsum = 0; 19 | for(int i = 0; i < n; ++ i){ 20 | tmpsum += machines[i] - avg; 21 | ans = max(ans, max(machines[i] - avg, abs(tmpsum))); 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_teemo-attacking.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int findPoisonedDuration(vector& timeSeries, int duration) { 10 | int res = 0; 11 | if(timeSeries.size() == 0) 12 | return res; 13 | timeSeries.push_back(INT_MAX); 14 | int t = 0, last_t = 0; 15 | for(int i = 0; i < timeSeries.size(); ++ i){ 16 | if(t < timeSeries[i]){ 17 | res += (t - last_t + 1); 18 | last_t = timeSeries[i]; 19 | } 20 | t = max(t, timeSeries[i] + duration - 1); 21 | } 22 | return timeSeries[0] == 0?res:res - 1; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_toeplitz-matrix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: 4 | * Time: O(n*m) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | bool isToeplitzMatrix(vector>& matrix) { 10 | if(matrix.size() <= 1){ 11 | return true; 12 | } 13 | 14 | int numOfRows = matrix.size(), numOfColumns = matrix[0].size(); 15 | for(int r = 0; r < numOfRows; ++ r){ 16 | for(int c = 0; c < numOfColumns; ++ c ){ 17 | if(r > 0 && c > 0 && matrix[r][c] != matrix[r - 1][c - 1]){ 18 | return false; 19 | } 20 | } 21 | } 22 | 23 | return true; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_triangle.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: DP 3 | * Time complexity: O(n^2) 4 | * Memory complexity: O(1) 5 | */ 6 | class Solution { 7 | public: 8 | int minimumTotal(vector > &triangle) { 9 | int len = triangle.size(); 10 | for(int i = len - 2; i >= 0; i --){ 11 | for(int j = 0; j < triangle[i].size(); j ++){ 12 | triangle[i][j] = min(triangle[i][j] + triangle[i + 1][j], triangle[i][j] + triangle[i + 1][j + 1]); 13 | } 14 | } 15 | return triangle[0][0]; 16 | } 17 | }; 18 | 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_uglynumber.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Tag: Math 3 | * Time: O(lgn) where n is the given num 4 | * Space: O(1) 5 | * 6 | */ 7 | class Solution { 8 | public 9 | bool isUgly(int num) { 10 | if(num <= 0) 11 | return false; 12 | if(num <= 6) 13 | return true; 14 | for(int i = 0; i < 3; ++ i){ 15 | while(num%div_val[i] == 0) 16 | num/=div_val[i]; 17 | if(num == 1) 18 | break; 19 | } 20 | return num == 1; 21 | } 22 | private: 23 | vector div_val={2,3,5}; 24 | }; 25 | -------------------------------------------------------------------------------- /LeetCode/leetcode_unique-substrings-in-wraparound-string.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int findSubstringInWraproundString(string p) { 10 | int ans = 0; 11 | if(p.size() == 0) 12 | return ans; 13 | vector cnt(26, 0); 14 | int cur = 0, len = 0; 15 | for(int i = 0; i < p.size(); ++ i){ 16 | cur = p[i] - 'a'; 17 | if(i > 0 && p[i - 1] != (cur + 25)%26 + 'a') len = 0; 18 | if(++ len > cnt[cur]){ 19 | ans += len - cnt[cur]; 20 | cnt[cur] = len; 21 | } 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LeetCode/leetcode_uniquebinarysearchtrees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: O(n) 3 | * Time complexity: O(n^2) 4 | * Memory complexity: O(n^2) 5 | */ 6 | class Solution { 7 | public: 8 | int numTrees(int n) { 9 | vector ans(n + 1, 0); 10 | 11 | ans[0] = 1; 12 | ans[1] = 1; 13 | for(int i = 2; i <= n; i ++){ 14 | for(int k = 1; k <= i; k ++){ 15 | ans[i] += ans[k - 1]*ans[i - k]; 16 | } 17 | } 18 | return ans[n]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LeetCode/leetcode_uniquepaths.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Algorithm: DP 3 | * Time complexity: O(n^2) 4 | * Memory complexity: O(n^2) 5 | */ 6 | class Solution { 7 | public: 8 | int uniquePaths(int m, int n) { 9 | vector > dp(m + 1, vector(n + 1, 0)); 10 | dp[1][1] = 1; 11 | for(int i = 1; i <= m; i ++){ 12 | for(int j = 1; j <= n; j ++){ 13 | dp[i][j] += (dp[i][j - 1] + dp[i - 1][j]); 14 | } 15 | } 16 | return dp[m][n]; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LeetCode/leetcode_water-and-jug-problem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(lgn) 6 | */ 7 | class Solution { 8 | public: 9 | bool canMeasureWater(int x, int y, int z) { 10 | if(z > x && z > y) return false; 11 | return z%gcd(x, y) == 0; 12 | } 13 | private: 14 | int gcd(int a, int b){ 15 | return b == 0?a:gcd(b, a%b); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LeetCode/leetcode_wigglesort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | void wiggleSort(vector& nums) { 10 | if(nums.size() <= 1) 11 | return ; 12 | int n = nums.size(); 13 | for(int i = 1; i < n; i += 2){ 14 | if(nums[i - 1] > nums[i]) 15 | swap(nums[i - 1], nums[i]); 16 | if(i + 1 < n && nums[i + 1] > nums[i]) 17 | swap(nums[i + 1], nums[i]); 18 | } 19 | return ; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LintCode/lintcode_a+b.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /* 10 | * @param a: The first integer 11 | * @param b: The second integer 12 | * @return: The sum of a and b 13 | */ 14 | int aplusb(int a, int b) { 15 | // Just submit this code, then you will get accepted! 16 | return a + b; 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LintCode/lintcode_add-digits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(m^2) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param num a non-negative integer 11 | * @return one digit 12 | */ 13 | int addDigits(int num) { 14 | // Write your code here 15 | int tmp = 0; 16 | while(num >= 10){ 17 | tmp = 0; 18 | while(num){ 19 | tmp += num%10; 20 | num /= 10; 21 | } 22 | num = tmp; 23 | } 24 | return num; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LintCode/lintcode_backpack-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(nm) 5 | * Space: O(m) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param m: An integer m denotes the size of a backpack 11 | * @param A & V: Given n items with size A[i] and value V[i] 12 | * @return: The maximum value 13 | */ 14 | int backPackII(int m, vector A, vector V) { 15 | // write your code here 16 | vector dp(m + 1); 17 | for(int i = 0; i < A.size(); ++ i){ 18 | for(int j = m; j >= A[i]; -- j){ 19 | dp[j] = max(dp[j], dp[j - A[i]] + V[i]); 20 | } 21 | } 22 | return dp[m]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LintCode/lintcode_best-time-to-buy-and-sell-stock-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Greedy 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param prices: Given an integer array 11 | * @return: Maximum profit 12 | */ 13 | int maxProfit(vector &prices) { 14 | // write your code here 15 | int ans = 0; 16 | if(prices.size() < 2) 17 | return ans; 18 | int n = prices.size(); 19 | for(int i = 0; i < n - 1; ++ i){ 20 | if(prices[i + 1] > prices[i]) 21 | ans += (prices[i + 1] - prices[i]); 22 | } 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_best-time-to-buy-and-sell-stock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param prices: Given an integer array 11 | * @return: Maximum profit 12 | */ 13 | int maxProfit(vector &prices) { 14 | // write your code here 15 | if(prices.size() == 0) 16 | return 0; 17 | int ans = 0, sum = 0; 18 | int n = prices.size(); 19 | for(int i = 0; i < n - 1; ++ i){ 20 | sum += (prices[i + 1] - prices[i]); 21 | ans = max(sum, ans); 22 | if(sum < 0) 23 | sum = 0; 24 | } 25 | return ans; 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /LintCode/lintcode_check-full-binary-tree.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | /* 10 | * @param : the given tree 11 | * @return: Whether it is a full tree 12 | */ 13 | bool isFullTree(TreeNode * root) { 14 | return root == NULL? true: hasOnlyOneChild(root)? false: isFullTree(root->left) && isFullTree(root->right); 15 | } 16 | private: 17 | bool hasOnlyOneChild(TreeNode *root){ 18 | return (root->left != NULL && root->right == NULL) || 19 | (root->left == NULL && root->right != NULL); 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LintCode/lintcode_climbing-stairs.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(n) (Best: O(1)) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param n: An integer 11 | * @return: An integer 12 | */ 13 | int climbStairs(int n) { 14 | // write your code here 15 | if(!n) 16 | return 0; 17 | vector dp(n + 1); 18 | dp[0] = 1; 19 | dp[1] = 1; 20 | for(int i = 2; i <= n; ++ i) 21 | dp[i] = dp[i - 1] + dp[i - 2]; 22 | return dp[n]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /LintCode/lintcode_coins-in-a-line.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param n: an integer 11 | * @return: a boolean which equals to true if the first player will win 12 | */ 13 | bool firstWillWin(int n) { 14 | // write your code here 15 | return !((n%3==0 && n) || !n); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LintCode/lintcode_count-1-in-binary.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param num: an integer 11 | * @return: an integer, the number of ones in num 12 | */ 13 | int countOnes(int num) { 14 | // write your code here 15 | int cnt = 0; 16 | if(!num) 17 | return cnt; 18 | int bitnum = 32; 19 | while(num && bitnum){ 20 | if(num&1){ 21 | ++ cnt; 22 | } 23 | num>>=1; 24 | --bitnum; 25 | } 26 | return cnt; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LintCode/lintcode_fibonacci.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution{ 8 | public: 9 | /** 10 | * @param n: an integer 11 | * @return an integer f(n) 12 | */ 13 | int fibonacci(int n) { 14 | // write your code here 15 | if(n == 1) 16 | return 0; 17 | if(n == 2) 18 | return 1; 19 | int pre = 0, cur = 1; 20 | for(int i = 3; i <= n; ++ i){ 21 | int tmp = cur; 22 | cur += pre; 23 | pre = tmp; 24 | } 25 | return cur; 26 | } 27 | }; 28 | 29 | -------------------------------------------------------------------------------- /LintCode/lintcode_find-the-missing-number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: a vector of integers 11 | * @return: an integer 12 | */ 13 | int findMissing(vector &nums) { 14 | // write your code here 15 | if(!nums.size()) 16 | return 0; 17 | int n = nums.size(); 18 | int ans = nums[0]; 19 | for(int i = 1; i < n; ++ i) 20 | ans^=nums[i]; 21 | for(int i = 0; i <= n; ++ i) 22 | ans^=i; 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_flip-bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | *@param a, b: Two integer 11 | *return: An integer 12 | */ 13 | int bitSwapRequired(int a, int b) { 14 | // write your code here 15 | int c = a^b; 16 | int iter = 32; 17 | int cnt = 0; 18 | while(iter --){ 19 | if(c&1) 20 | ++ cnt; 21 | c>>=1; 22 | } 23 | return cnt; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_gray-code.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(2^n) 5 | * Space: O(2^n) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param n a number 11 | * @return Gray code 12 | */ 13 | vector grayCode(int n) { 14 | // Write your code here 15 | vector res; 16 | res.reserve(1<= 0; -- j){ 21 | res.push_back(high_bit | res[j]); 22 | } 23 | } 24 | return res; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LintCode/lintcode_greatest-common-divisor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(lgn) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param a: the given number 11 | * @param b: another number 12 | * @return: the greatest common divisor of two numbers 13 | */ 14 | int gcd(int a, int b) { 15 | return b == 0? a : gcd(b, a%b); 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LintCode/lintcode_last-digit-by-factorial-divide.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | int computeLastDigit(long long A, long long B) { 10 | if(A == B) 11 | return 1; 12 | if(B - A >= 10) 13 | return 0; 14 | int ans = 1; 15 | for(long long i = A + 1; i <= B; ++ i){ 16 | int factor = i%10; 17 | ans = (ans * factor)%10; 18 | } 19 | return ans; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /LintCode/lintcode_leap-year.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param n: a number represent year 11 | * @return: whether year n is a leap year. 12 | */ 13 | bool isLeapYear(int n) { 14 | return n%400 == 0 || (n%4 == 0 && n%100 != 0); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LintCode/lintcode_length-of-last-word.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param s A string 11 | * @return the length of last word 12 | */ 13 | int lengthOfLastWord(string& s) { 14 | // Write your code here 15 | int ans = 0; 16 | if(!s.size()) 17 | return ans; 18 | int i = s.size() - 1; 19 | while(i >= 0 && s[i] == ' ') 20 | -- i; 21 | if(!i) 22 | return ans; 23 | while(i >= 0 && s[i] != ' '){ 24 | -- i; 25 | ++ ans; 26 | } 27 | return ans; 28 | } 29 | }; 30 | -------------------------------------------------------------------------------- /LintCode/lintcode_lintcode_o1-check-power-of-2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /* 10 | * @param n: An integer 11 | * @return: True or false 12 | */ 13 | bool checkPowerOf2(int n) { 14 | // write your code here 15 | int cnt = 0; 16 | if(n < 0) 17 | return false; 18 | while(n){ 19 | if(n&1) 20 | ++ cnt; 21 | n >>= 1; 22 | } 23 | return cnt == 1; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_lowercase-to-uppercase.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param character: a character 11 | * @return: a character 12 | */ 13 | char lowercaseToUppercase(char character) { 14 | return toupper(character); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LintCode/lintcode_maximum-gap.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Sort 4 | * Time: O(nlgn) 5 | * Space: O(lgn) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: a vector of integers 11 | * @return: the maximum difference 12 | */ 13 | int maximumGap(vector nums) { 14 | // write your code here 15 | int ans = 0; 16 | if(nums.size() < 2) 17 | return ans; 18 | sort(nums.begin(), nums.end()); 19 | int n = nums.size(); 20 | int gap; 21 | for(int i = 1; i < n; ++ i){ 22 | gap = nums[i] - nums[i - 1]; 23 | ans = max(ans, gap); 24 | } 25 | return ans; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LintCode/lintcode_maximum-subarray.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: A list of integers 11 | * @return: A integer indicate the sum of max subarray 12 | */ 13 | int maxSubArray(vector nums) { 14 | // write your code here 15 | int sum = nums[0], n = nums.size(); 16 | int ans = nums[0]; 17 | for(int i = 1; i < n; ++ i){ 18 | if(sum < 0) 19 | sum = nums[i]; 20 | else 21 | sum += nums[i]; 22 | ans = max(ans, sum); 23 | } 24 | return ans; 25 | } 26 | }; 27 | 28 | -------------------------------------------------------------------------------- /LintCode/lintcode_move-zeroes.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implementation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums an integer array 11 | * @return nothing, do this in-place 12 | */ 13 | void moveZeroes(vector& nums) { 14 | // Write your code here 15 | int cntzeros = 0; 16 | if(!nums.size()) 17 | return ; 18 | int id = 0; 19 | for(int i = 0; i < nums.size(); ++ i){ 20 | if(nums[i]) 21 | nums[id ++] = nums[i]; 22 | else 23 | ++ cntzeros; 24 | } 25 | while(cntzeros --) 26 | nums[id ++] = 0; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LintCode/lintcode_next-permutation-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DFS 4 | * Time: ? 5 | * Space: ? 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: a vector of integers 11 | * @return: return nothing (void), do not return anything, modify nums in-place instead 12 | */ 13 | void nextPermutation(vector &num) { 14 | // write your code here 15 | if(num.size() == 0) 16 | return ; 17 | if(!next_permutation(num.begin(), num.end())) 18 | sort(num.begin(), num.end()); 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LintCode/lintcode_next-permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: ? 4 | * Time: ? 5 | * Space: ? 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: An array of integers 11 | * @return: An array of integers that's next permuation 12 | */ 13 | vector nextPermuation(vector &nums) { 14 | // write your code here 15 | if(nums.size() == 0) 16 | return nums; 17 | next_permutation(nums.begin(), nums.end()); 18 | return nums; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LintCode/lintcode_paint-fence.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param n non-negative integer, n posts 11 | * @param k non-negative integer, k colors 12 | * @return an integer, the total number of ways 13 | */ 14 | int numWays(int n, int k) { 15 | // Write your code here 16 | if(n <= 1 || !k) 17 | return n*k; 18 | int a = k, b = k*(k - 1), c = 0; 19 | for(int i = 2; i < n; ++ i){ 20 | c = (k - 1)*(a + b); 21 | a = b; 22 | b = c; 23 | } 24 | 25 | return a+b; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LintCode/lintcode_palindrome-number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: String 4 | * Time: O(n) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | /* 10 | * @param num: a positive number 11 | * @return: true if it's a palindrome or false 12 | */ 13 | bool isPalindrome(int num) { 14 | string str_num = to_string(num); 15 | return str_num == string(str_num.rbegin(), str_num.rend()); 16 | } 17 | 18 | }; 19 | -------------------------------------------------------------------------------- /LintCode/lintcode_permutations.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Backtracking 4 | * Time: O(n!) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: A list of integers. 11 | * @return: A list of permutations. 12 | */ 13 | vector > permute(vector nums) { 14 | // write your code here 15 | vector > ans; 16 | if(nums.size() == 0) 17 | return ans; 18 | sort(nums.begin(), nums.end()); 19 | do{ 20 | ans.push_back(nums); 21 | }while(next_permutation(nums.begin(), nums.end())); 22 | return ans; 23 | } 24 | }; 25 | 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_previous-permutation.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: ? 4 | * Time: ? 5 | * Space: ? 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: An array of integers 11 | * @return: An array of integers that's previous permuation 12 | */ 13 | vector previousPermuation(vector &nums) { 14 | // write your code here 15 | if(nums.size() == 0) 16 | return nums; 17 | prev_permutation(nums.begin(), nums.end()); 18 | return nums; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /LintCode/lintcode_remove-duplicates-from-sorted-array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param A: a list of integers 11 | * @return : return an integer 12 | */ 13 | int removeDuplicates(vector &nums) { 14 | // write your code here 15 | int len = nums.size(); 16 | if(!nums.size()) 17 | return len; 18 | int id = 1, n = nums.size(); 19 | for(int i = 1; i < n; ++ i){ 20 | if(nums[i] != nums[i - 1]){ 21 | nums[id ++] = nums[i]; 22 | }else 23 | -- len; 24 | } 25 | return len; 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /LintCode/lintcode_remove-element.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | *@param A: A list of integers 11 | *@param elem: An integer 12 | *@return: The new length after remove 13 | */ 14 | int removeElement(vector &A, int elem) { 15 | // write your code here 16 | int ans = 0; 17 | int idx = 0; 18 | for(int i = 0; i < A.size(); ++ i){ 19 | if(A[i] == elem){ 20 | ++ ans; 21 | }else{ 22 | A[idx] = A[i]; 23 | ++ idx; 24 | } 25 | } 26 | return A.size() - ans; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LintCode/lintcode_reverse-3-digit-integer.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param number: A 3-digit number. 11 | * @return: Reversed number. 12 | */ 13 | int reverseInteger(int number) { 14 | int ans = 0; 15 | 16 | while(number > 0){ 17 | ans = (ans*10) + (number%10); 18 | number /= 10; 19 | } 20 | 21 | return ans; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LintCode/lintcode_reverse-array.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Implement 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: a integer array 11 | * @return: nothing 12 | */ 13 | void reverseArray(vector &nums) { 14 | reverse(nums.begin(), nums.end()); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LintCode/lintcode_single-number.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param A: Array of integers. 11 | * return: The single number. 12 | */ 13 | int singleNumber(vector &A) { 14 | // write your code here 15 | if(A.size() == 0) 16 | return 0; 17 | int ans = A[0], n = A.size(); 18 | for(int i = 1; i < n; ++ i) 19 | ans ^= A[i]; 20 | return ans; 21 | } 22 | 23 | }; 24 | -------------------------------------------------------------------------------- /LintCode/lintcode_singleton.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Design 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @return: The same instance of this class every time 11 | */ 12 | static Solution* getInstance() { 13 | // write your code here 14 | static Solution* pa = new Solution(); 15 | return pa; 16 | } 17 | 18 | // Noncopyable. 19 | Solution(const Solution&) = delete; 20 | Solution& operator=(const Solution&) = delete; 21 | 22 | private: 23 | Solution() {} 24 | ~Solution() {} 25 | }; 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_singleton.java: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Design 4 | */ 5 | class Solution { 6 | private static volatile Solution instance = new Solution(); 7 | /** 8 | * @return: The same instance of this class every time 9 | */ 10 | private Solution() { 11 | } 12 | 13 | public static Solution getInstance() { 14 | // write your code here 15 | return instance; 16 | } 17 | }; 18 | -------------------------------------------------------------------------------- /LintCode/lintcode_sort-colors-ii.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(k) 6 | */ 7 | class Solution{ 8 | public: 9 | /** 10 | * @param colors: A list of integer 11 | * @param k: An integer 12 | * @return: nothing 13 | */ 14 | void sortColors2(vector &colors, int k) { 15 | // write your code here 16 | vector cnt(k); 17 | for(int i = 0; i < colors.size(); ++ i){ 18 | ++ cnt[colors[i] - 1]; 19 | } 20 | int idx = 0; 21 | for(int i = 0; i < k; ++ i){ 22 | while(cnt[i] --) 23 | colors[idx ++] = i + 1; 24 | } 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /LintCode/lintcode_sort-integers-ii.cpp: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public: 3 | /** 4 | * @param A an integer array 5 | * @return void 6 | */ 7 | void sortIntegers2(vector& A) { 8 | // Write your code here 9 | if(!A.size()) 10 | return ; 11 | sort(A.begin(),A.end()); 12 | return ; 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /LintCode/lintcode_sum-of-all-subsets.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /* 10 | * @param : the given number 11 | * @return: Sum of elements in subsets 12 | */ 13 | int subSum(int n) { 14 | return n <= 1? n : n*(n + 1)*(1<<(n - 2)); 15 | } 16 | }; 17 | -------------------------------------------------------------------------------- /LintCode/lintcode_top-k-largest-numbers.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Data Structure 4 | * Time: O(nlgn) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums: an integer array 11 | * @param k: An integer 12 | * @return: the top k largest numbers in array 13 | */ 14 | vector topk(vector &nums, int k) { 15 | vector ans(k); 16 | priority_queue > maxHeap(nums.begin(), nums.end()); 17 | 18 | for(int i = 0; i < k && i < nums.size(); ++ i) { 19 | ans[i] = maxHeap.top(); 20 | maxHeap.pop(); 21 | } 22 | 23 | return ans; 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /LintCode/lintcode_trailing-zeros.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Math 4 | * Time: O(lgn) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | // param n : description of n 10 | // return: description of return 11 | long long trailingZeros(long long n) { 12 | long long ans = 0; 13 | long long div = 5, mul = 5; 14 | while(n/div){ 15 | ans += n/div; 16 | div *= mul; 17 | } 18 | return ans; 19 | } 20 | }; 21 | 22 | -------------------------------------------------------------------------------- /LintCode/lintcode_unique-binary-search-trees.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: DP 4 | * Time: O(n^2) 5 | * Space: O(n) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @paramn n: An integer 11 | * @return: An integer 12 | */ 13 | int numTrees(int n) { 14 | // write your code here 15 | if(!n) 16 | return 1; 17 | int dp[n + 1]; 18 | dp[0] = 1; 19 | dp[1] = 1; 20 | for(int i = 2; i <= n; ++ i){ 21 | dp[i] = 0; 22 | for(int j = 1; j<= i; ++ j){ 23 | dp[i] += dp[j - 1]*dp[i - j]; 24 | } 25 | } 26 | return dp[n]; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /LintCode/lintcode_unique-characters.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Sort or Hash 4 | * Time: O(nlgn) or O(n) 5 | * Space: O(lgn) or O(n) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param str: a string 11 | * @return: a boolean 12 | */ 13 | bool isUnique(string &str) { 14 | // write your code here 15 | string tmp_str = str; 16 | sort(tmp_str.begin(), tmp_str.end()); 17 | int len = tmp_str.size() - 1; 18 | for(int i = 0; i < len; ++ i) 19 | if(tmp_str[i] == tmp_str[i + 1]) 20 | return false; 21 | return true; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /LintCode/lintcode_update-bits.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Bit Manipulation 4 | * Time: O(1) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | *@param n, m: Two integer 11 | *@param i, j: Two bit positions 12 | *return: An integer 13 | */ 14 | int updateBits(int n, int m, int i, int j) { 15 | // write your code here 16 | int l = j-i+1; 17 | unsigned int mask = l==32 ? 0xffffffff : ((1< c) && (a + c > b) && (b + c > a); 17 | } 18 | }; 19 | -------------------------------------------------------------------------------- /LintCode/lintcode_wiggle-sort.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * Tag: Brute Force 4 | * Time: O(n) 5 | * Space: O(1) 6 | */ 7 | class Solution { 8 | public: 9 | /** 10 | * @param nums a list of integer 11 | * @return void 12 | */ 13 | void wiggleSort(vector& nums) { 14 | // Write your code here 15 | if(nums.size() <= 1) 16 | return ; 17 | int n = nums.size(); 18 | for(int i = 1; i < n; i += 2){ 19 | if(nums[i] < nums[i - 1]) 20 | swap(nums[i], nums[i - 1]); 21 | if(i + 1 < n && nums[i] < nums[i + 1]) 22 | swap(nums[i], nums[i + 1]); 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | ## TODO 2 | 3 | - Data Structures 4 | - Segment Tree 5 | - Elaborate Self-Balancing BSTs 6 | 7 | - Sorting Algorithms 8 | - Bucket Sort 9 | - Radix Sort 10 | 11 | - Graph Algorithms 12 | - Dijkstra's Algorithm / A* Search / Bellman-Ford Algorithm / Floyd-Warshall Algorithm 13 | - Topological Sorting 14 | - Minimum Spanning Tree / Prim's Algorithm / Kruskal's Algorithm 15 | 16 | - Networking Fundamentals 17 | - TCP/IP, HTTP, Basics of Search, Firewalls 18 | - Protocols 19 | - IP Addresses 20 | -------------------------------------------------------------------------------- /assets/Bubble-Sort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/assets/Bubble-Sort.gif -------------------------------------------------------------------------------- /assets/Heap-Sort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/assets/Heap-Sort.gif -------------------------------------------------------------------------------- /assets/Insertion-Sort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/assets/Insertion-Sort.gif -------------------------------------------------------------------------------- /assets/Merge-Sort.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/assets/Merge-Sort.png -------------------------------------------------------------------------------- /assets/Quicksort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/assets/Quicksort.gif -------------------------------------------------------------------------------- /assets/Selection-Sort.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mohammedjasam/Technical-Interview-Guide/7ac97286820f298876f1fcb408bc6d7dc90c076c/assets/Selection-Sort.gif -------------------------------------------------------------------------------- /interviews.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | --------------------------------------------------------------------------------