Repository: imteekay/algorithms Branch: master Commit: 12008e54efb6 Files: 1561 Total size: 988.9 KB Directory structure: gitextract_w21wx358/ ├── .github/ │ └── workflows/ │ └── push-ci.yml ├── .gitignore ├── .nvmrc ├── .prettierrc ├── .vscode/ │ └── settings.json ├── FUNDING.yml ├── LICENSE ├── README.md ├── big-o.md ├── coding_interviews/ │ ├── README.md │ ├── algoexpert/ │ │ ├── README.md │ │ ├── array-of-products/ │ │ │ ├── array-of-products-optimized.js │ │ │ └── array-of-products.js │ │ ├── best-seat/ │ │ │ └── best-seat.js │ │ ├── binary-search/ │ │ │ └── binary-search.js │ │ ├── branch-sums/ │ │ │ ├── branch-sums-without-recreating-sums.js │ │ │ └── branch-sums.js │ │ ├── bst-construction/ │ │ │ └── bst-construction.js │ │ ├── bst-traversal/ │ │ │ └── bst-traversal.js │ │ ├── bubble-sort/ │ │ │ └── bubble-sort.js │ │ ├── caesar-cipher-encryptor/ │ │ │ └── caesar-cipher-encryptor.js │ │ ├── class-photos/ │ │ │ └── class-photos.js │ │ ├── common-characters/ │ │ │ └── common-characters.js │ │ ├── depth-first-search/ │ │ │ ├── depth-first-search-cleaner.js │ │ │ └── depth-first-search.js │ │ ├── evaluate-expression-tree/ │ │ │ ├── evaluate-expression-tree-cleaner.js │ │ │ ├── evaluate-expression-tree-with-trunc.js │ │ │ └── evaluate-expression-tree.js │ │ ├── find-closest-value-in-bst/ │ │ │ ├── find-closest-value-in-bst-optimized-cleaner.js │ │ │ ├── find-closest-value-in-bst-optimized.js │ │ │ └── find-closest-value-in-bst.js │ │ ├── find-three-largest-numbers/ │ │ │ └── find-three-largest-numbers.js │ │ ├── first-duplicate-value/ │ │ │ ├── first-duplicate-value-optimized.js │ │ │ └── first-duplicate-value.js │ │ ├── first-non-repeating-character/ │ │ │ └── first-non-repeating-character.js │ │ ├── generate-document/ │ │ │ └── generate-document.js │ │ ├── insertion-sort/ │ │ │ └── insertion-sort.js │ │ ├── longest-peak/ │ │ │ └── longest-peak.js │ │ ├── majority-element/ │ │ │ └── majority-element.js │ │ ├── merge-overlapping-intervals/ │ │ │ └── merge-overlapping-intervals.js │ │ ├── middle-node/ │ │ │ ├── middle-node-slow-fast.js │ │ │ └── middle-node.js │ │ ├── minimum-waiting-time/ │ │ │ └── minimum-waiting-time.js │ │ ├── missing-numbers/ │ │ │ └── missing-numbers.js │ │ ├── monotonic-array/ │ │ │ ├── monotonic-array-optimization-1.js │ │ │ ├── monotonic-array-optimization-2.js │ │ │ └── monotonic-array.js │ │ ├── move-element-to-end/ │ │ │ └── move-element-to-end.js │ │ ├── node-depths/ │ │ │ └── node-depths.js │ │ ├── non-constructible-change/ │ │ │ └── non-constructible-change.js │ │ ├── nth-fibonacci/ │ │ │ ├── nth-fibonacci-memo-no-space.js │ │ │ ├── nth-fibonacci-memo.js │ │ │ └── nth-fibonacci.js │ │ ├── optimal-freelancing/ │ │ │ ├── optimal-freelancing-sorting.js │ │ │ └── optimal-freelancing.js │ │ ├── palindrome-check/ │ │ │ └── palindrome-check.js │ │ ├── product-sum/ │ │ │ ├── product-sum-timer-later.js │ │ │ └── product-sum.js │ │ ├── remove-duplicates-from-linked-list/ │ │ │ └── remove-duplicates-from-linked-list.js │ │ ├── remove-islands/ │ │ │ ├── remove-islands-optimized.js │ │ │ └── remove-islands.js │ │ ├── run-length-encoding/ │ │ │ ├── run-length-encoding copy.js │ │ │ ├── run-length-encoding-cleaner.js │ │ │ └── run-length-encoding.js │ │ ├── semordnilap/ │ │ │ └── semordnilap.js │ │ ├── smallest-difference/ │ │ │ └── smallest-difference.js │ │ ├── sorted-squared-array/ │ │ │ ├── sorted-squared-array-insert-position.js │ │ │ ├── sorted-squared-array-two-pointers.js │ │ │ └── sorted-squared-array.js │ │ ├── spiral-traverse/ │ │ │ └── spiral-traverse.js │ │ ├── tandem-bicycle/ │ │ │ ├── tandem-bicycle-cleaner.js │ │ │ └── tandem-bicycle.js │ │ ├── three-number-sum/ │ │ │ └── three-number-sum.js │ │ ├── tournament-winner/ │ │ │ ├── tournament-winner-optimized.js │ │ │ └── tournament-winner.js │ │ ├── transpose-matrix/ │ │ │ └── transpose-matrix.js │ │ ├── two-number-sum/ │ │ │ ├── two-number-sum-optimized.js │ │ │ ├── two-number-sum-two-pointers.js │ │ │ └── two-number-sum.js │ │ ├── validate-bst/ │ │ │ └── validate-bst.js │ │ ├── validate-subsequence/ │ │ │ ├── validate-subsequence-two-pointers.js │ │ │ └── validate-subsequence.js │ │ └── zero-sum-subarray/ │ │ ├── zero-sum-subarray-optimized.js │ │ └── zero-sum-subarray.js │ ├── algorithms_in_python/ │ │ ├── queue/ │ │ │ └── R-6.7.py │ │ └── stack/ │ │ ├── R-6.1.py │ │ ├── R-6.3.py │ │ ├── R-6.4.py │ │ └── R-6.5.py │ ├── blind75/ │ │ └── README.md │ ├── coding_interview_questions/ │ │ ├── common_elements.py │ │ ├── decode-string/ │ │ │ ├── decode-string.js │ │ │ └── tests/ │ │ │ └── decode-string.test.js │ │ ├── mine_swipper.py │ │ ├── most_frequently_occurring.py │ │ ├── non_repeating.py │ │ ├── nth_element_from_the_end.py │ │ ├── one_away_strings.py │ │ ├── optimized_common_elements.py │ │ ├── rotation_array.py │ │ └── two-crystal-balls/ │ │ ├── index.js │ │ └── tests/ │ │ └── index.test.js │ ├── cracking-the-coding-interview/ │ │ ├── README.md │ │ ├── big_o/ │ │ │ ├── aditional1.py │ │ │ ├── aditional2.py │ │ │ ├── aditional3.py │ │ │ ├── aditional4.py │ │ │ ├── aditional5.py │ │ │ ├── aditional6.py │ │ │ ├── example1.py │ │ │ ├── example10.py │ │ │ ├── example11.py │ │ │ ├── example12.py │ │ │ ├── example13.py │ │ │ ├── example14.py │ │ │ ├── example15.py │ │ │ ├── example16.py │ │ │ ├── example2.py │ │ │ ├── example3.py │ │ │ ├── example4.py │ │ │ ├── example5.py │ │ │ ├── example6.py │ │ │ ├── example7.py │ │ │ └── example9.py │ │ └── chapter-001/ │ │ ├── check-permutation/ │ │ │ ├── check-permutation.js │ │ │ └── check-permutation.test.js │ │ ├── cpp/ │ │ │ └── remove_specified_character.cpp │ │ ├── is-unique/ │ │ │ ├── is-unique.js │ │ │ └── is-unique.test.js │ │ ├── one-away/ │ │ │ ├── one-away.js │ │ │ └── one-away.test.js │ │ ├── palindrome-permutation/ │ │ │ ├── palindrome-permutation.js │ │ │ └── palindrome-permutation.test.js │ │ ├── python/ │ │ │ ├── 001.01.py │ │ │ ├── 001.02.py │ │ │ ├── 001.03.py │ │ │ ├── 001.04.py │ │ │ ├── 001.05.py │ │ │ ├── 001.06.py │ │ │ ├── 001.07.py │ │ │ ├── bottlenecks.py │ │ │ └── is_unique.py │ │ ├── string-compression/ │ │ │ └── string-compression.js │ │ └── urlify/ │ │ ├── urlify.js │ │ └── urlify.test.js │ ├── daily_code_problems/ │ │ ├── 001.py │ │ ├── 002.py │ │ ├── 003.py │ │ ├── 004.py │ │ ├── 005.py │ │ ├── 006.py │ │ ├── 007.py │ │ └── README.md │ ├── elements_of_programming_interview/ │ │ ├── array.py │ │ ├── base_conversion.py │ │ ├── buy_and_sell_stock_once.py │ │ ├── can_reach_end.py │ │ ├── delete_duplicates_from_a_sorted_array.py │ │ ├── interconvert_string_and_integer.py │ │ ├── longest_subarray_length_with_same_integers.py │ │ ├── multiply_two_arbitrary_precision_integers.py │ │ └── spreadsheet_column_encoding.py │ ├── hackerrank_interview_prep_kit/ │ │ ├── hash_tables/ │ │ │ ├── count_triplets.py │ │ │ ├── ransom_note.py │ │ │ ├── sherlock_and_anagrams.py │ │ │ └── two_strings.py │ │ └── warmup/ │ │ ├── counting_valleys.py │ │ ├── jumping_on_the_clouds.py │ │ ├── repeated_string.py │ │ └── sales_by_match.py │ ├── interviews/ │ │ ├── fair/ │ │ │ ├── decrementBinaryNumber.js │ │ │ ├── diceTotalScore.js │ │ │ ├── isSubmatrixFull.js │ │ │ └── sortChessSubsquares.js │ │ ├── google/ │ │ │ └── printSequence/ │ │ │ └── printSequence.js │ │ ├── mercari/ │ │ │ ├── cumulativeSum.js │ │ │ ├── findMaxMin.js │ │ │ ├── findSumPairs.js │ │ │ ├── multipleDupesArray.js │ │ │ ├── products.js │ │ │ ├── removeDupes.js │ │ │ └── retries.js │ │ ├── meta/ │ │ │ ├── compareLettersInArray/ │ │ │ │ └── compareLettersInArray.js │ │ │ └── flatten/ │ │ │ ├── flatten.js │ │ │ └── flatten2.js │ │ ├── quintoandar/ │ │ │ ├── quinto1.py │ │ │ ├── quinto2.py │ │ │ ├── quinto3.py │ │ │ └── regions.js │ │ ├── smartnews/ │ │ │ ├── countries.js │ │ │ ├── emiter.js │ │ │ └── getTriplets.js │ │ └── uber/ │ │ ├── longest-words.js │ │ ├── maxFrequency.js │ │ ├── permutations.js │ │ └── tests/ │ │ └── maxFrequency.test.js │ ├── javascript/ │ │ ├── array/ │ │ │ ├── binary-search.js │ │ │ ├── slice.js │ │ │ └── subarrays.js │ │ ├── hashmap/ │ │ │ ├── iteration.js │ │ │ └── object.js │ │ ├── queue/ │ │ │ └── queue.js │ │ ├── stack/ │ │ │ └── stack.js │ │ ├── string/ │ │ │ ├── alphabet.js │ │ │ ├── charCode.js │ │ │ ├── isString.js │ │ │ ├── methods.js │ │ │ └── sort.js │ │ └── tree/ │ │ ├── inorder.js │ │ ├── postorder.js │ │ └── preorder.js │ ├── leetcode/ │ │ ├── easy/ │ │ │ ├── a-number-after-a-double-reversal/ │ │ │ │ ├── a-number-after-a-double-reversal.js │ │ │ │ └── tests/ │ │ │ │ └── a-number-after-a-double-reversal.test.js │ │ │ ├── add-digits/ │ │ │ │ └── add-digits.js │ │ │ ├── add-two-integers/ │ │ │ │ └── index.js │ │ │ ├── alternating-digit-sum/ │ │ │ │ └── alternating-digit-sum.js │ │ │ ├── apply-operations-to-an-array/ │ │ │ │ └── apply-operations-to-an-array.js │ │ │ ├── arithmetic_progression/ │ │ │ │ └── arithmetic_progression.py │ │ │ ├── array_partition.py │ │ │ ├── average-of-levels-in-binary-tree/ │ │ │ │ └── average-of-levels-in-binary-tree.js │ │ │ ├── average-salary-excluding-the-minimum-and-maximum-salary/ │ │ │ │ └── average-salary-excluding-the-minimum-and-maximum-salary.js │ │ │ ├── average-value-of-even-numbers-that-are-divisible-by-three/ │ │ │ │ └── average-value-of-even-numbers-that-are-divisible-by-three.js │ │ │ ├── backspace-string-compare/ │ │ │ │ ├── index.js │ │ │ │ └── tests/ │ │ │ │ └── index.test.js │ │ │ ├── baseball-game/ │ │ │ │ └── baseball-game.js │ │ │ ├── best-poker-hand/ │ │ │ │ └── best-poker-hand.js │ │ │ ├── best-time-to-buy-and-sell-stock/ │ │ │ │ ├── best-time-to-buy-and-sell-stock-tle.js │ │ │ │ └── best-time-to-buy-and-sell-stock.js │ │ │ ├── binary-number-with-alternating-bits/ │ │ │ │ └── binary-number-with-alternating-bits.js │ │ │ ├── binary-search/ │ │ │ │ └── binary-search.js │ │ │ ├── binary-tree-inorder-traversal/ │ │ │ │ └── binary-tree-inorder-traversal.js │ │ │ ├── binary-tree-paths/ │ │ │ │ └── binary-tree-paths.js │ │ │ ├── binary-tree-postorder-traversal/ │ │ │ │ └── binary-tree-postorder-traversal.js │ │ │ ├── binary-tree-preorder-traversal/ │ │ │ │ └── binary-tree-preorder-traversal.js │ │ │ ├── binary-tree-tilt/ │ │ │ │ ├── binary-tree-tilt-optimized.js │ │ │ │ └── binary-tree-tilt.js │ │ │ ├── binary_in_linked_list/ │ │ │ │ └── binary_in_linked_list.py │ │ │ ├── build_an_array_with_stack_operations/ │ │ │ │ └── build_an_array_with_stack_operations.py │ │ │ ├── build_array_from_permutation/ │ │ │ │ └── build_array_from_permutation.js │ │ │ ├── buy-two-chocolates/ │ │ │ │ ├── buy-two-chocolates-on.js │ │ │ │ ├── buy-two-chocolates-sort.js │ │ │ │ └── buy-two-chocolates.js │ │ │ ├── calculate-amount-paid-in-taxes/ │ │ │ │ └── calculate-amount-paid-in-taxes.js │ │ │ ├── calculate-delayed-arrival-time/ │ │ │ │ └── calculate-delayed-arrival-time.js │ │ │ ├── calculate-digit-sum-of-a-string/ │ │ │ │ └── calculate-digit-sum-of-a-string.js │ │ │ ├── calculate-money-in-leetcode-bank/ │ │ │ │ └── calculate-money-in-leetcode-bank.js │ │ │ ├── can-place-flowers/ │ │ │ │ └── can-place-flowers.js │ │ │ ├── capitalize-the-title/ │ │ │ │ └── capitalize-the-title.js │ │ │ ├── cells-in-a-range-on-an-excel-sheet/ │ │ │ │ ├── cells-in-a-range-on-an-excel-sheet.js │ │ │ │ └── tests/ │ │ │ │ └── cells-in-a-range-on-an-excel-sheet.test.js │ │ │ ├── check-array-formation-through-concatenation/ │ │ │ │ └── check-array-formation-through-concatenation.js │ │ │ ├── check-distances-between-same-letters/ │ │ │ │ └── check-distances-between-same-letters.js │ │ │ ├── check-if-a-string-is-an-acronym-of-words/ │ │ │ │ └── check-if-a-string-is-an-acronym-of-words.js │ │ │ ├── check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ │ │ │ │ └── check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js │ │ │ ├── check-if-all-as-appears-before-all-bs/ │ │ │ │ └── check-if-all-as-appears-before-all-bs.js │ │ │ ├── check-if-matrix-is-x-matrix/ │ │ │ │ └── check-if-matrix-is-x-matrix.js │ │ │ ├── check-if-number-has-equal-digit-count-and-digit-value/ │ │ │ │ └── check-if-number-has-equal-digit-count-and-digit-value.js │ │ │ ├── check-if-numbers-are-ascending-in-a-sentence/ │ │ │ │ └── check-if-numbers-are-ascending-in-a-sentence.js │ │ │ ├── check-if-the-sentence-is-pangram/ │ │ │ │ └── check-if-the-sentence-is-pangram.py │ │ │ ├── check-whether-two-strings-are-almost-equivalent/ │ │ │ │ └── check-whether-two-strings-are-almost-equivalent.js │ │ │ ├── check_if_all_characters_have_equal_number_of_occurrences/ │ │ │ │ └── check_if_all_characters_have_equal_number_of_occurrences.js │ │ │ ├── check_if_two_string_arrays_are_equivalent/ │ │ │ │ └── check_if_two_string_arrays_are_equivalent.py │ │ │ ├── circular-sentence/ │ │ │ │ └── circular-sentence.js │ │ │ ├── climbing-stairs/ │ │ │ │ └── climbing-stairs.js │ │ │ ├── climbing_stairs.py │ │ │ ├── concatenation_of_array/ │ │ │ │ └── concatenation_of_array.js │ │ │ ├── consecutive-characters/ │ │ │ │ └── consecutive-characters.js │ │ │ ├── construct-string-from-binary-tree/ │ │ │ │ └── construct-string-from-binary-tree.js │ │ │ ├── contains-duplicate/ │ │ │ │ ├── contains-duplicate-hashmap.js │ │ │ │ ├── contains-duplicate.js │ │ │ │ └── contains-duplicate.py │ │ │ ├── convert-sorted-array-to-binary-search-tree/ │ │ │ │ └── convert-sorted-array-to-binary-search-tree.js │ │ │ ├── convert-the-temperature/ │ │ │ │ └── convert-the-temperature.js │ │ │ ├── count-asterisks/ │ │ │ │ └── count-asterisks.js │ │ │ ├── count-common-words-with-one-occurrence/ │ │ │ │ └── count-common-words-with-one-occurrence.js │ │ │ ├── count-complete-tree-nodes/ │ │ │ │ └── count-complete-tree-nodes.js │ │ │ ├── count-equal-and-divisible-pairs-in-an-array/ │ │ │ │ ├── count-equal-and-divisible-pairs-in-an-array-2.js │ │ │ │ ├── count-equal-and-divisible-pairs-in-an-array.js │ │ │ │ └── tests/ │ │ │ │ ├── count-equal-and-divisible-pairs-in-an-array-2.test.js │ │ │ │ └── count-equal-and-divisible-pairs-in-an-array.test.js │ │ │ ├── count-good-triplets/ │ │ │ │ └── count-good-triplets.py │ │ │ ├── count-integers-with-even-digit-sum/ │ │ │ │ └── count-integers-with-even-digit-sum.js │ │ │ ├── count-k-difference/ │ │ │ │ └── count-k-difference.js │ │ │ ├── count-largest-group/ │ │ │ │ └── count-largest-group.js │ │ │ ├── count-operations-to-obtain-zero/ │ │ │ │ ├── count-operations-to-obtain-zero.js │ │ │ │ └── tests/ │ │ │ │ └── count-operations-to-obtain-zero.test.js │ │ │ ├── count-pairs-of-similar-strings/ │ │ │ │ └── count-pairs-of-similar-strings.js │ │ │ ├── count-pairs-whose-sum-is-less-than-target/ │ │ │ │ ├── count-pairs-whose-sum-is-less-than-target-two-pointers.js │ │ │ │ └── count-pairs-whose-sum-is-less-than-target.js │ │ │ ├── count-prefixes-of-a-given-string/ │ │ │ │ └── count-prefixes-of-a-given-string.js │ │ │ ├── count-square-sum-triples/ │ │ │ │ └── count-square-sum-triples.js │ │ │ ├── count-symmetric-integers/ │ │ │ │ └── count-symmetric-integers.js │ │ │ ├── count-the-digits-that-divide-a-number/ │ │ │ │ └── count-the-digits-that-divide-a-number.js │ │ │ ├── count-the-number-of-vowel-strings-in-range/ │ │ │ │ └── count-the-number-of-vowel-strings-in-range.js │ │ │ ├── count-vowel-substrings-of-a-string/ │ │ │ │ └── count-vowel-substrings-of-a-string.js │ │ │ ├── count_good_rectangles/ │ │ │ │ └── count_good_rectangles.py │ │ │ ├── count_matches/ │ │ │ │ └── count_matches.py │ │ │ ├── count_of_matches_in_tournament/ │ │ │ │ └── count_of_matches_in_tournament.py │ │ │ ├── count_students/ │ │ │ │ └── count_students.py │ │ │ ├── count_the_number_of_consistent_strings/ │ │ │ │ └── count_the_number_of_consistent_strings.py │ │ │ ├── counting-bits/ │ │ │ │ └── counting-bits.js │ │ │ ├── counting-words-with-a-given-prefix/ │ │ │ │ ├── counting-words-with-a-given-prefix.js │ │ │ │ └── tests/ │ │ │ │ └── counting-words-with-a-given-prefix.test.js │ │ │ ├── crawler-log-folder/ │ │ │ │ └── crawler-log-folder.js │ │ │ ├── create_target_array/ │ │ │ │ └── create_target_array.py │ │ │ ├── decode-the-message/ │ │ │ │ ├── decode-the-message.js │ │ │ │ └── tests/ │ │ │ │ └── decode-the-message.test.js │ │ │ ├── decode_xored_array/ │ │ │ │ └── decode_xored_array.py │ │ │ ├── decompressed_encoded_list/ │ │ │ │ └── decompressed_encoded_list.py │ │ │ ├── decrypt_string/ │ │ │ │ └── decrypt_string.py │ │ │ ├── defanging_an_ip_address/ │ │ │ │ └── defanging_an_ip_address.py │ │ │ ├── defuse-the-bomb/ │ │ │ │ └── defuse-the-bomb.js │ │ │ ├── delete-greatest-value-in-each-row/ │ │ │ │ └── delete-greatest-value-in-each-row.js │ │ │ ├── delete_columns_to_make_sorted/ │ │ │ │ └── delete_columns_to_make_sorted.py │ │ │ ├── design-an-ordered-stream/ │ │ │ │ └── design-an-ordered-stream.js │ │ │ ├── design-hashmap/ │ │ │ │ └── design-hashmap.js │ │ │ ├── design-hashset/ │ │ │ │ └── design-hashset.js │ │ │ ├── design_parking_system/ │ │ │ │ └── design_parking_system.py │ │ │ ├── destination_city/ │ │ │ │ └── destination_city.py │ │ │ ├── detect-capital/ │ │ │ │ └── detect-capital.js │ │ │ ├── determine-if-string-halves-are-alike/ │ │ │ │ └── determine-if-string-halves-are-alike.js │ │ │ ├── determine_color_of_a_chessboard_square/ │ │ │ │ └── determine_color_of_a_chessboard_square.py │ │ │ ├── di_string_match/ │ │ │ │ └── di_string_match.py │ │ │ ├── difference-between-element-sum-and-digit-sum-of-an-array/ │ │ │ │ └── difference-between-element-sum-and-digit-sum-of-an-array.js │ │ │ ├── discount_price/ │ │ │ │ └── discount_price.py │ │ │ ├── distribute-candies-among-children-i/ │ │ │ │ ├── distribute-candies-among-children-i.js │ │ │ │ └── distribute-candies-among-children-ii.js │ │ │ ├── distribute-candies-to-people/ │ │ │ │ └── distribute-candies-to-people.js │ │ │ ├── divide-a-string-into-groups-of-size-k/ │ │ │ │ └── divide-a-string-into-groups-of-size-k.js │ │ │ ├── divide-array-into-equal-pairs/ │ │ │ │ ├── divide-array-into-equal-pairs.js │ │ │ │ └── tests/ │ │ │ │ └── divide-array-into-equal-pairs.test.js │ │ │ ├── divisible-and-non-divisible-sums-difference/ │ │ │ │ └── divisible-and-non-divisible-sums-difference.js │ │ │ ├── divisor-game/ │ │ │ │ └── divisor-game.js │ │ │ ├── equal_reversed_arrays/ │ │ │ │ └── equal_reversed_arrays.py │ │ │ ├── evaluate-boolean-binary-tree/ │ │ │ │ └── evaluate-boolean-binary-tree.js │ │ │ ├── even_digits/ │ │ │ │ └── even_digits.py │ │ │ ├── excel-sheet-column-number/ │ │ │ │ └── excel-sheet-column-number.js │ │ │ ├── fair-candy-swap/ │ │ │ │ ├── fair-candy-swap-optimized.js │ │ │ │ └── fair-candy-swap.js │ │ │ ├── faulty-keyboard/ │ │ │ │ └── faulty-keyboard.js │ │ │ ├── fibonacci_number/ │ │ │ │ └── fibonacci_number.py │ │ │ ├── final-value-after-operations/ │ │ │ │ └── final-value-after-operations.js │ │ │ ├── find-all-k-distant-indices-in-an-array/ │ │ │ │ └── find-all-k-distant-indices-in-an-array.js │ │ │ ├── find-all-numbers-disappeared-in-an-array/ │ │ │ │ └── find-all-numbers-disappeared-in-an-array.js │ │ │ ├── find-center-of-star-graph/ │ │ │ │ └── find-center-of-star-graph.js │ │ │ ├── find-champion-i/ │ │ │ │ ├── find-champion-i-no-map.js │ │ │ │ └── find-champion-i.js │ │ │ ├── find-first-palindromic-string-in-the-array/ │ │ │ │ ├── find-first-palindromic-string-in-the-array.js │ │ │ │ └── tests/ │ │ │ │ └── find-first-palindromic-string-in-the-array.test.js │ │ │ ├── find-greatest-common-divisor-of-array/ │ │ │ │ └── find-greatest-common-divisor-of-array.js │ │ │ ├── find-indices-with-index-and-value-difference-i/ │ │ │ │ └── find-indices-with-index-and-value-difference-i.js │ │ │ ├── find-lucky-integer-in-an-array/ │ │ │ │ └── find-lucky-integer-in-an-array.js │ │ │ ├── find-maximum-number-of-string-pairs/ │ │ │ │ └── find-maximum-number-of-string-pairs.js │ │ │ ├── find-nearest-point-that-has-the-same-x-or-y-coordinate/ │ │ │ │ └── find-nearest-point-that-has-the-same-x-or-y-coordinate.js │ │ │ ├── find-subarrays-with-equal-sum/ │ │ │ │ └── find-subarrays-with-equal-sum.js │ │ │ ├── find-target-indices-after-sorting-array/ │ │ │ │ ├── find-target-indices-after-sorting-array.js │ │ │ │ └── tests/ │ │ │ │ └── find-target-indices-after-sorting-array.test.js │ │ │ ├── find-the-array-concatenation-value/ │ │ │ │ └── find-the-array-concatenation-value.js │ │ │ ├── find-the-difference/ │ │ │ │ └── find-the-difference.js │ │ │ ├── find-the-difference-of-two-arrays/ │ │ │ │ └── find-the-difference-of-two-arrays.js │ │ │ ├── find-the-distance-value-between-two-arrays/ │ │ │ │ └── find-the-distance-value-between-two-arrays.js │ │ │ ├── find-the-distinct-difference-array/ │ │ │ │ ├── find-the-distinct-difference-array.js │ │ │ │ └── optimized-find-the-distinct-difference-array.js │ │ │ ├── find-the-maximum-achievable-number/ │ │ │ │ └── find-the-maximum-achievable-number.js │ │ │ ├── find-the-middle-index-in-array/ │ │ │ │ └── find-the-middle-index-in-array.js │ │ │ ├── find-the-pivot-integer/ │ │ │ │ └── find-the-pivot-integer.js │ │ │ ├── find-the-width-of-columns-of-a-grid/ │ │ │ │ └── find-the-width-of-columns-of-a-grid.js │ │ │ ├── find-words-containing-character/ │ │ │ │ └── find-words-containing-character.js │ │ │ ├── find-words-that-can-be-formed-by-characters/ │ │ │ │ └── find-words-that-can-be-formed-by-characters.js │ │ │ ├── find_common_characters/ │ │ │ │ └── find_common_characters.py │ │ │ ├── find_the_highest_altitude/ │ │ │ │ └── find_the_highest_altitude.py │ │ │ ├── first-bad-version/ │ │ │ │ ├── first-bad-version-binary-search.js │ │ │ │ └── first-bad-version.js │ │ │ ├── first-letter-to-appear-twice/ │ │ │ │ └── first-letter-to-appear-twice.js │ │ │ ├── first-unique-character-in-a-string/ │ │ │ │ └── first-unique-character-in-a-string.js │ │ │ ├── first_bad_version/ │ │ │ │ └── first_bad_version.py │ │ │ ├── fizz-buzz/ │ │ │ │ └── fizz-buzz.js │ │ │ ├── flipping_an_image.py │ │ │ ├── flood-fill/ │ │ │ │ ├── flood-fill-without-visited.js │ │ │ │ └── flood-fill.js │ │ │ ├── furthest-point-from-origin/ │ │ │ │ └── furthest-point-from-origin.js │ │ │ ├── generate_the_string/ │ │ │ │ └── generate_the_string.py │ │ │ ├── goal_parser_interpretation/ │ │ │ │ └── goal_parser_interpretation.py │ │ │ ├── greatest-english-letter-in-upper-and-lower-case/ │ │ │ │ └── greatest-english-letter-in-upper-and-lower-case.js │ │ │ ├── greatest_candies/ │ │ │ │ └── greatest_candies.py │ │ │ ├── guess-number-higher-or-lower/ │ │ │ │ └── guess-number-higher-or-lower.js │ │ │ ├── halves_are_alike/ │ │ │ │ └── halves_are_alike.py │ │ │ ├── hamming_distance/ │ │ │ │ └── hamming_distance.py │ │ │ ├── height_checker/ │ │ │ │ └── height_checker.py │ │ │ ├── implement-queue-using-stacks/ │ │ │ │ └── implement-queue-using-stacks.js │ │ │ ├── implement-stack-using-queues/ │ │ │ │ └── implement-stack-using-queues.js │ │ │ ├── increasing_decreasing_string/ │ │ │ │ └── incresing_decreasin_string.py │ │ │ ├── increasing_order_search_tree/ │ │ │ │ └── increasing_order_search_tree.py │ │ │ ├── intersection-of-multiple-arrays/ │ │ │ │ └── intersection-of-multiple-arrays.js │ │ │ ├── intersection-of-two-arrays-ii/ │ │ │ │ └── intersection-of-two-arrays-ii.js │ │ │ ├── intersection_of_two_arrays/ │ │ │ │ └── intersection_of_two_arrays.py │ │ │ ├── intersection_of_two_arrays_ii/ │ │ │ │ └── intersection_of_two_arrays.py │ │ │ ├── invert-binary-tree/ │ │ │ │ └── invert-binary-tree.js │ │ │ ├── is-subsequence/ │ │ │ │ └── is-subsequence.js │ │ │ ├── is_palindrome.py │ │ │ ├── is_sum_equal/ │ │ │ │ └── is_sum_equal.py │ │ │ ├── island-perimeter/ │ │ │ │ └── island-perimeter.js │ │ │ ├── jewels_and_stones.py │ │ │ ├── judge_route_circle.py │ │ │ ├── judge_route_circle_one_line.py │ │ │ ├── k-items-with-the-maximum-sum/ │ │ │ │ ├── k-items-with-the-maximum-sum-second.js │ │ │ │ └── k-items-with-the-maximum-sum.js │ │ │ ├── keep-multiplying-found-values-by-two/ │ │ │ │ └── keep-multiplying-found-values-by-two.js │ │ │ ├── keyboard-row/ │ │ │ │ └── keyboard-row.js │ │ │ ├── kth-distinct-string-in-an-array/ │ │ │ │ └── kth-distinct-string-in-an-array.js │ │ │ ├── largest-local-values-in-a-matrix/ │ │ │ │ └── largest-local-values-in-a-matrix.js │ │ │ ├── largest-number-after-digit-swaps-by-parity/ │ │ │ │ └── largest-number-after-digit-swaps-by-parity.js │ │ │ ├── largest-positive-integer-that-exists-with-its-negative/ │ │ │ │ └── largest-positive-integer-that-exists-with-its-negative.js │ │ │ ├── last-stone-weight/ │ │ │ │ ├── last-stone-weight.js │ │ │ │ └── tests/ │ │ │ │ └── last-stone-weight.test.js │ │ │ ├── last-visited-integers/ │ │ │ │ └── last-visited-integers.js │ │ │ ├── leaf-similar-trees/ │ │ │ │ └── leaf-similar-trees.js │ │ │ ├── left-and-right-sum-differences/ │ │ │ │ └── left-and-right-sum-differences.js │ │ │ ├── length-of-last-word/ │ │ │ │ └── length-of-last-word.js │ │ │ ├── lexicographically-smallest-palindrome/ │ │ │ │ └── lexicographically-smallest-palindrome.js │ │ │ ├── linked-list-cycle/ │ │ │ │ └── linked-list-cycle.js │ │ │ ├── longer-contiguous-segments-of-ones-than-zeros/ │ │ │ │ └── longer-contiguous-segments-of-ones-than-zeros.js │ │ │ ├── longest-nice-substring/ │ │ │ │ └── longest-nice-substring.js │ │ │ ├── longest-subsequence-with-limited-sum/ │ │ │ │ └── longest-subsequence-with-limited-sum.js │ │ │ ├── longest_palindrome.py │ │ │ ├── lowest-common-ancestor-of-a-binary-search-tree/ │ │ │ │ └── lowest-common-ancestor-of-a-binary-search-tree.js │ │ │ ├── lucky_numbers_in_a_matrix/ │ │ │ │ └── lucky_numbers_in_a_matrix.py │ │ │ ├── majority-element/ │ │ │ │ └── majority-element.js │ │ │ ├── make-array-zero-by-subtracting-equal-amounts/ │ │ │ │ └── make-array-zero-by-subtracting-equal-amounts.js │ │ │ ├── make-the-string-great/ │ │ │ │ └── make-the-string-great.js │ │ │ ├── matrix-cells-in-distance-order/ │ │ │ │ └── matrix-cells-in-distance-order.js │ │ │ ├── matrix_diagonal_sum/ │ │ │ │ └── matrix_diagonal_sum.py │ │ │ ├── matrix_negative_numbers/ │ │ │ │ └── matrix_negative_numbers.py │ │ │ ├── max-consecutive-ones/ │ │ │ │ └── max-consecutive-ones.js │ │ │ ├── maximum-69-number/ │ │ │ │ └── maximum-69-number.js │ │ │ ├── maximum-ascending-subarray-sum/ │ │ │ │ └── maximum-ascending-subarray-sum.js │ │ │ ├── maximum-count-of-positive-integer-and-negative-integer/ │ │ │ │ └── maximum-count-of-positive-integer-and-negative-integer.js │ │ │ ├── maximum-depth-of-binary-tree/ │ │ │ │ ├── maximum-depth-of-binary-tree-2.js │ │ │ │ └── maximum-depth-of-binary-tree.js │ │ │ ├── maximum-depth-of-n-ary-tree/ │ │ │ │ └── maximum-depth-of-n-ary-tree.js │ │ │ ├── maximum-number-of-balloons/ │ │ │ │ └── maximum-number-of-balloons.js │ │ │ ├── maximum-number-of-pairs-in-array/ │ │ │ │ └── maximum-number-of-pairs-in-array.js │ │ │ ├── maximum-odd-binary-number/ │ │ │ │ └── maximum-odd-binary-number.js │ │ │ ├── maximum-subarray/ │ │ │ │ └── maximum-subarray.js │ │ │ ├── maximum-sum-with-exactly-k-elements/ │ │ │ │ └── maximum-sum-with-exactly-k-elements.js │ │ │ ├── maximum-units-on-a-truck/ │ │ │ │ └── maximum-units-on-a-truck.py │ │ │ ├── maximum-value-of-a-string-in-an-array/ │ │ │ │ └── maximum-value-of-a-string-in-an-array.js │ │ │ ├── maximum_nesting_depth_of_the_parentheses/ │ │ │ │ └── maximum_nesting_depth_of_the_parentheses.py │ │ │ ├── maximum_number_of_balls_in_a_box/ │ │ │ │ └── maximum_number_of_balls_in_a_box.py │ │ │ ├── maximum_number_of_words_you_can_type/ │ │ │ │ └── maximum_number_of_words_you_can_type.js │ │ │ ├── maximum_population/ │ │ │ │ └── maximum_population.py │ │ │ ├── maximum_product/ │ │ │ │ └── maximum_product.py │ │ │ ├── maximum_product_difference_between_two_pairs/ │ │ │ │ └── maximum_product_difference_between_two_pairs.js │ │ │ ├── mean-of-array-after-removing-some-elements/ │ │ │ │ └── mean-of-array-after-removing-some-elements.js │ │ │ ├── merge-nodes-in-between-zeros/ │ │ │ │ ├── merge-nodes-in-between-zeros.js │ │ │ │ └── tests/ │ │ │ │ └── merge-nodes-in-between-zeros.test.js │ │ │ ├── merge-similar-items/ │ │ │ │ └── merge-similar-items.js │ │ │ ├── merge-sorted-array/ │ │ │ │ └── merge-sorted-array.js │ │ │ ├── merge-two-2d-arrays-by-summing-values/ │ │ │ │ └── merge-two-2d-arrays-by-summing-values.js │ │ │ ├── merge-two-binary-trees/ │ │ │ │ └── merge-two-binary-trees.js │ │ │ ├── merge-two-sorted-lists/ │ │ │ │ ├── merge-two-sorted-lists.js │ │ │ │ └── tests/ │ │ │ │ └── merge-two-sorted-lists.test.js │ │ │ ├── merge_strings_alternately/ │ │ │ │ └── merge_strings_alternately.py │ │ │ ├── merge_trees.py │ │ │ ├── merge_two_lists.py │ │ │ ├── middle-of-the-linked-list/ │ │ │ │ ├── middle-of-the-linked-list-fast-slow.js │ │ │ │ └── middle-of-the-linked-list.js │ │ │ ├── min-max-game/ │ │ │ │ └── min-max-game.js │ │ │ ├── minimize-string-length/ │ │ │ │ └── minimize-string-length.js │ │ │ ├── minimum-absolute-difference/ │ │ │ │ └── minimum-absolute-difference.js │ │ │ ├── minimum-absolute-difference-in-bst/ │ │ │ │ └── minimum-absolute-difference-in-bst.js │ │ │ ├── minimum-bit-flips-to-convert-number/ │ │ │ │ ├── minimum-bit-flips-to-convert-number.js │ │ │ │ └── tests/ │ │ │ │ └── minimum-bit-flips-to-convert-number.test.js │ │ │ ├── minimum-cost-to-move-chips-to-the-same-position/ │ │ │ │ └── minimum-cost-to-move-chips-to-the-same-position.js │ │ │ ├── minimum-depth-of-binary-tree/ │ │ │ │ └── minimum-depth-of-binary-tree.js │ │ │ ├── minimum-distance-between-bst-nodes/ │ │ │ │ └── minimum-distance-between-bst-nodes.js │ │ │ ├── minimum-number-game/ │ │ │ │ └── minimum-number-game.js │ │ │ ├── minimum-number-of-moves-to-seat-everyone/ │ │ │ │ ├── minimum-number-of-moves-to-seat-everyone.js │ │ │ │ └── tests/ │ │ │ │ └── minimum-number-of-moves-to-seat-everyone.test.js │ │ │ ├── minimum-number-of-operations-to-convert-time/ │ │ │ │ └── minimum-number-of-operations-to-convert-time.js │ │ │ ├── minimum-string-length-after-removing-substrings/ │ │ │ │ └── minimum-string-length-after-removing-substrings.js │ │ │ ├── minimum-subsequence-in-non-increasing-order/ │ │ │ │ └── minimum-subsequence-in-non-increasing-order.js │ │ │ ├── minimum-sum/ │ │ │ │ └── minimum-sum.js │ │ │ ├── minimum-sum-of-mountain-triplets-i/ │ │ │ │ └── minimum-sum-of-mountain-triplets-i.js │ │ │ ├── minimum-time-to-type-word-using-special-typewriter/ │ │ │ │ └── minimum-time-to-type-word-using-special-typewriter.js │ │ │ ├── minimum-value-to-get-positive-step-by-step-sum/ │ │ │ │ └── minimum-value-to-get-positive-step-by-step-sum.js │ │ │ ├── minimum_operations_to_make_the_array_increasing/ │ │ │ │ └── minimum_operations_to_make_the_array_increasing.py │ │ │ ├── missing-number/ │ │ │ │ └── missing-number.js │ │ │ ├── monotonic-array/ │ │ │ │ └── monotonic-array.js │ │ │ ├── most-words-found/ │ │ │ │ └── most-words-found.js │ │ │ ├── move-zeroes/ │ │ │ │ ├── move-zeroes-in-place.js │ │ │ │ └── move-zeroes.js │ │ │ ├── n_ary_tree_postorder_traversal/ │ │ │ │ └── n_ary_tree_postorder_traversal.py │ │ │ ├── n_ary_tree_preorder_traversal/ │ │ │ │ └── n_ary_tree_preorder_traversal.py │ │ │ ├── n_repeated_element_in_size_2n_array/ │ │ │ │ └── n_repeated_element_in_size_2n_array.py │ │ │ ├── neither-minimum-nor-maximum/ │ │ │ │ ├── neither-minimum-nor-maximum-on.js │ │ │ │ └── neither-minimum-nor-maximum.js │ │ │ ├── next-greater-element-i/ │ │ │ │ ├── next-greater-element-i-optimized.js │ │ │ │ ├── next-greater-element-i.js │ │ │ │ └── tests/ │ │ │ │ ├── next-greater-element-i-optimized.test.js │ │ │ │ └── next-greater-element-i.test.js │ │ │ ├── num_unique_emails/ │ │ │ │ └── num_unique_emails.py │ │ │ ├── number-of-1-bits/ │ │ │ │ └── number-of-1-bits.js │ │ │ ├── number-of-arithmetic-triplets/ │ │ │ │ └── number-of-arithmetic-triplets.js │ │ │ ├── number-of-common-factors/ │ │ │ │ └── number-of-common-factors.js │ │ │ ├── number-of-employees-who-met-the-target/ │ │ │ │ └── number-of-employees-who-met-the-target.js │ │ │ ├── number-of-even-and-odd-bits/ │ │ │ │ └── number-of-even-and-odd-bits.js │ │ │ ├── number-of-lines-to-write-string/ │ │ │ │ └── number-of-lines-to-write-string.js │ │ │ ├── number-of-senior-citizens/ │ │ │ │ ├── number-of-senior-citizens.js │ │ │ │ └── one-liner-number-of-senior-citizens.js │ │ │ ├── number-of-strings-that-appear-as-substrings-in-word/ │ │ │ │ └── number-of-strings-that-appear-as-substrings-in-word.js │ │ │ ├── number-of-unequal-triplets-in-array/ │ │ │ │ └── number-of-unequal-triplets-in-array.js │ │ │ ├── number_complement.py │ │ │ ├── number_of_good_pairs/ │ │ │ │ └── number_of_good_pairs.py │ │ │ ├── number_of_recent_calls/ │ │ │ │ └── number_of_recent_calls.py │ │ │ ├── number_of_students/ │ │ │ │ └── number_of_students.py │ │ │ ├── odd-string-difference/ │ │ │ │ └── odd-string-difference.js │ │ │ ├── odd_in_matrix/ │ │ │ │ └── odd_in_matrix.py │ │ │ ├── partition_labels.py │ │ │ ├── pascals-triangle/ │ │ │ │ └── pascals-triangle.js │ │ │ ├── path-sum/ │ │ │ │ └── path-sum.js │ │ │ ├── peak_index_mountain.py │ │ │ ├── percentage-of-letter-in-string/ │ │ │ │ └── percentage-of-letter-in-string.js │ │ │ ├── plus_one/ │ │ │ │ ├── plus_one.js │ │ │ │ └── plus_one.py │ │ │ ├── points-that-intersect-with-cars/ │ │ │ │ └── points-that-intersect-with-cars.js │ │ │ ├── power-of-two/ │ │ │ │ └── power-of-two.js │ │ │ ├── prime-number-of-set-bits-in-binary-representation/ │ │ │ │ └── prime-number-of-set-bits-in-binary-representation.js │ │ │ ├── projection-area-of-3d-shapes/ │ │ │ │ └── projection-area-of-3d-shapes.js │ │ │ ├── range_sum_of_bst/ │ │ │ │ └── range_sum_of_bst.py │ │ │ ├── rank-transform-of-an-array/ │ │ │ │ ├── rank-transform-of-an-array-less-memory.js │ │ │ │ └── rank-transform-of-an-array.js │ │ │ ├── ransom-note/ │ │ │ │ └── ransom-note.js │ │ │ ├── ransom_note/ │ │ │ │ └── ransom_note.py │ │ │ ├── reduce_zero/ │ │ │ │ └── reduce_zero.py │ │ │ ├── reformat-date/ │ │ │ │ └── reformat-date.js │ │ │ ├── reformat-phone-number/ │ │ │ │ └── reformat-phone-number.js │ │ │ ├── relative-ranks/ │ │ │ │ └── relative-ranks.js │ │ │ ├── relative-sort-array/ │ │ │ │ └── relative-sort-array.js │ │ │ ├── remove-duplicates-from-sorted-list/ │ │ │ │ └── remove-duplicates-from-sorted-list.js │ │ │ ├── remove-linked-list-elements/ │ │ │ │ └── remove-linked-list-elements.js │ │ │ ├── remove-outermost-parentheses/ │ │ │ │ ├── remove-outermost-parentheses.js │ │ │ │ └── tests/ │ │ │ │ └── remove-outermost-parentheses.test.js │ │ │ ├── remove-palindromic-subsequences/ │ │ │ │ └── remove-palindromic-subsequences.js │ │ │ ├── remove-trailing-zeros-from-a-string/ │ │ │ │ └── remove-trailing-zeros-from-a-string.js │ │ │ ├── remove_duplicates/ │ │ │ │ └── remove_duplicates.py │ │ │ ├── remove_duplicates.py │ │ │ ├── remove_duplicates_from_list.py │ │ │ ├── remove_element.py │ │ │ ├── replace_digits/ │ │ │ │ └── replace_digits.py │ │ │ ├── replace_elements/ │ │ │ │ └── replace_elements.py │ │ │ ├── reshape-the-matrix/ │ │ │ │ └── reshape-the-matrix.js │ │ │ ├── reverse-linked-list/ │ │ │ │ └── reverse-linked-list.js │ │ │ ├── reverse-only-letters/ │ │ │ │ └── reverse-only-letters.js │ │ │ ├── reverse-prefix-of-word/ │ │ │ │ ├── reverse-prefix-of-word.js │ │ │ │ └── tests/ │ │ │ │ └── reverse-prefix-of-word.test.js │ │ │ ├── reverse-string/ │ │ │ │ ├── reverse-string-in-place.js │ │ │ │ └── reverse-string.js │ │ │ ├── reverse-vowels-of-a-string/ │ │ │ │ └── reverse-vowels-of-a-string.js │ │ │ ├── reverse-words-in-a-string-iii/ │ │ │ │ └── reverse-words-in-a-string-iii.js │ │ │ ├── reverse_integer.py │ │ │ ├── reverse_string.py │ │ │ ├── reverse_vowels.py │ │ │ ├── reverse_words_string.py │ │ │ ├── rings-and-rods/ │ │ │ │ ├── rings-and-rods.js │ │ │ │ └── tests/ │ │ │ │ └── rings-and-rods.test.js │ │ │ ├── root-equals-sum-of-children/ │ │ │ │ └── index.js │ │ │ ├── row-with-maximum-ones/ │ │ │ │ └── row-with-maximum-ones.js │ │ │ ├── running_array_sum/ │ │ │ │ └── running_array_sum.py │ │ │ ├── same-tree/ │ │ │ │ └── same-tree.js │ │ │ ├── same_tree.py │ │ │ ├── search-in-a-binary-search-tree/ │ │ │ │ └── search-in-a-binary-search-tree.js │ │ │ ├── search-insert-position/ │ │ │ │ ├── search-insert-position-new.js │ │ │ │ └── search-insert-position.js │ │ │ ├── search_in_a_binary_search_tree/ │ │ │ │ └── search_in_a_binary_search_tree.py │ │ │ ├── second-largest-digit-in-a-string/ │ │ │ │ └── second-largest-digit-in-a-string.js │ │ │ ├── self_dividing_numbers.py │ │ │ ├── semi-ordered-permutation/ │ │ │ │ └── semi-ordered-permutation.js │ │ │ ├── separate-the-digits-in-an-array/ │ │ │ │ └── separate-the-digits-in-an-array.js │ │ │ ├── shortest_to_char/ │ │ │ │ └── shortest_to_char.py │ │ │ ├── shuffle_string/ │ │ │ │ └── shuffle_string.py │ │ │ ├── shuffle_the_array/ │ │ │ │ └── shuffle_the_array.py │ │ │ ├── sign_of_the_product_of_an_array/ │ │ │ │ └── sign_of_the_product_of_an_array.py │ │ │ ├── single-number/ │ │ │ │ └── single-number.js │ │ │ ├── single_number/ │ │ │ │ └── single_number.py │ │ │ ├── slowest-key/ │ │ │ │ └── slowest-key.js │ │ │ ├── smallest-even-multiple/ │ │ │ │ └── smallest-even-multiple.js │ │ │ ├── smallest-index-with-equal-value/ │ │ │ │ └── smallest-index-with-equal-value.js │ │ │ ├── smallest-range-i/ │ │ │ │ ├── optimized-smallest-range-i.js │ │ │ │ ├── smallest-range-i.js │ │ │ │ └── smallest-range-iI.js │ │ │ ├── smallest_numbers/ │ │ │ │ └── smallest_numbers.py │ │ │ ├── sort-array-by-increasing-frequency/ │ │ │ │ └── sort-array-by-increasing-frequency.js │ │ │ ├── sort-array-by-parity/ │ │ │ │ ├── sort-array-by-parity-two-loops.js │ │ │ │ └── sort-array-by-parity.js │ │ │ ├── sort-array-by-parity-ii/ │ │ │ │ ├── sort-array-by-parity-ii.js │ │ │ │ └── tests/ │ │ │ │ └── sort-array-by-parity-ii.test.js │ │ │ ├── sort-even-and-odd-indices-independently/ │ │ │ │ └── sort-even-and-odd-indices-independently.js │ │ │ ├── sort-integers-by-the-number-of-1-bits/ │ │ │ │ └── sort-integers-by-the-number-of-1-bits.js │ │ │ ├── sort-the-people/ │ │ │ │ └── sort-the-people.js │ │ │ ├── sort_array_by_parity/ │ │ │ │ └── sort_array_by_parity.py │ │ │ ├── sort_sentence/ │ │ │ │ └── sort_sentence.py │ │ │ ├── special-positions-in-a-binary-matrix/ │ │ │ │ ├── special-positions-in-a-binary-matrix-cache.js │ │ │ │ └── special-positions-in-a-binary-matrix.js │ │ │ ├── split-strings-by-separator/ │ │ │ │ └── split-strings-by-separator.js │ │ │ ├── split-with-minimum-sum/ │ │ │ │ └── split-with-minimum-sum.js │ │ │ ├── split_string_in_balanced_strings/ │ │ │ │ └── split_string_in_balanced_strings.py │ │ │ ├── squares-of-a-sorted-array/ │ │ │ │ ├── squares-of-a-sorted-array-on.js │ │ │ │ └── squares-of-a-sorted-array.js │ │ │ ├── squares_of_a_sorted_array/ │ │ │ │ └── squares_of_a_sorted_array.py │ │ │ ├── str_str/ │ │ │ │ └── str_str.py │ │ │ ├── string-matching-in-an-array/ │ │ │ │ └── string-matching-in-an-array.js │ │ │ ├── subarrays-distinct-element-sum-of-squares-i/ │ │ │ │ └── subarrays-distinct-element-sum-of-squares-i.js │ │ │ ├── subdomain_visit_count.py │ │ │ ├── substrings-of-size-three-with-distinct-characters/ │ │ │ │ └── substrings-of-size-three-with-distinct-characters.js │ │ │ ├── subtract_product_and_sum/ │ │ │ │ └── subtract_product_and_sum.py │ │ │ ├── subtree-of-another-tree/ │ │ │ │ └── subtree-of-another-tree.js │ │ │ ├── sum-multiples/ │ │ │ │ └── sum-multiples.js │ │ │ ├── sum-of-all-subset-xor-totals/ │ │ │ │ └── sum-of-all-subset-xor-totals.js │ │ │ ├── sum-of-digits-in-base-k/ │ │ │ │ └── sum-of-digits-in-base-k.js │ │ │ ├── sum-of-digits-of-string-after-convert/ │ │ │ │ └── sum-of-digits-of-string-after-convert.js │ │ │ ├── sum-of-left-leaves/ │ │ │ │ └── sum-of-left-leaves.js │ │ │ ├── sum-of-squares-of-special-elements/ │ │ │ │ └── sum-of-squares-of-special-elements.js │ │ │ ├── sum-of-values-at-indices-with-k-set-bits/ │ │ │ │ └── sum-of-values-at-indices-with-k-set-bits.js │ │ │ ├── sum_leaf_binary_numbers/ │ │ │ │ └── sum_leaf_binary_numbers.py │ │ │ ├── sum_of_all_odd_length_subarrays/ │ │ │ │ └── sum_of_all_odd_length_subarrays.py │ │ │ ├── sum_of_unique_elements/ │ │ │ │ └── sum_of_unique_elements.py │ │ │ ├── sum_zero/ │ │ │ │ └── sum_zero.py │ │ │ ├── symmetric-tree/ │ │ │ │ └── symmetric-tree.js │ │ │ ├── take-gifts-from-the-richest-pile/ │ │ │ │ └── take-gifts-from-the-richest-pile.js │ │ │ ├── three-consecutive-odds/ │ │ │ │ └── three-consecutive-odds.js │ │ │ ├── time-needed-to-buy-tickets/ │ │ │ │ └── time-needed-to-buy-tickets.js │ │ │ ├── to_lower_case/ │ │ │ │ └── to_lower_case.py │ │ │ ├── toeplitz-matrix/ │ │ │ │ └── toeplitz-matrix.js │ │ │ ├── transpose-matrix/ │ │ │ │ └── transpose-matrix.js │ │ │ ├── truncate_sentence/ │ │ │ │ └── truncate_sentence.py │ │ │ ├── two-furthest-houses-with-different-colors/ │ │ │ │ └── two-furthest-houses-with-different-colors.js │ │ │ ├── two-out-of-three/ │ │ │ │ └── two-out-of-three.js │ │ │ ├── two-sum/ │ │ │ │ └── two-sum.js │ │ │ ├── two-sum-iv-input-is-a-bst/ │ │ │ │ └── two-sum-iv-input-is-a-bst.js │ │ │ ├── two_sum.py │ │ │ ├── uncommon-words-from-two-sentences/ │ │ │ │ └── uncommon-words-from-two-sentences.js │ │ │ ├── unique-number-of-occurrences/ │ │ │ │ └── unique-number-of-occurrences.js │ │ │ ├── unique_morse_code_words.py │ │ │ ├── unique_number_of_occurrences/ │ │ │ │ └── unique_number_of_occurrences.py │ │ │ ├── univalued-binary-tree/ │ │ │ │ └── univalued-binary-tree.js │ │ │ ├── valid-anagram/ │ │ │ │ └── valid-anagram.js │ │ │ ├── valid-palindrome/ │ │ │ │ ├── valid-palindrome-2.js │ │ │ │ ├── valid-palindrome.js │ │ │ │ └── valid_palindrome.py │ │ │ ├── valid-parentheses/ │ │ │ │ └── valid-parentheses.js │ │ │ ├── water-bottles/ │ │ │ │ └── water-bottles.js │ │ │ ├── weakest_rows/ │ │ │ │ └── weakest_rows.py │ │ │ └── xor-operation-in-an-array/ │ │ │ └── xor-operation-in-an-array.js │ │ └── medium/ │ │ ├── 3sum/ │ │ │ └── 3sum-tle.js │ │ ├── add_two_numbers/ │ │ │ └── add_two_numbers.py │ │ ├── all_elements_in_two_binary_search_trees/ │ │ │ └── all_elements_in_two_binary_search_trees.py │ │ ├── arithmetic-subarrays/ │ │ │ └── arithmetic-subarrays.py │ │ ├── balance-a-binary-search-tree/ │ │ │ └── balance-a-binary-search-tree.js │ │ ├── binary-tree-inorder-traversal/ │ │ │ └── binary-tree-inorder-traversal.py │ │ ├── binary-tree-level-order-traversal/ │ │ │ └── binary-tree-level-order-traversal.js │ │ ├── bst_from_pre_order_traversal/ │ │ │ └── bst_from_pre_order_traversal.py │ │ ├── bst_to_greatest/ │ │ │ └── bst_to_greatest.py │ │ ├── clone-graph/ │ │ │ └── clone-graph.js │ │ ├── cloned_binary_tree/ │ │ │ └── cloned_binary_tree.py │ │ ├── count-nodes-equal-to-average-of-subtree/ │ │ │ └── count-nodes-equal-to-average-of-subtree.js │ │ ├── count-number-of-distinct-integers-after-reverse-operations/ │ │ │ ├── count-number-of-distinct-integers-after-reverse-operations-numbers.js │ │ │ └── count-number-of-distinct-integers-after-reverse-operations.js │ │ ├── count-sorted-vowel-strings/ │ │ │ └── count-sorted-vowel-strings.js │ │ ├── count-sub-islands/ │ │ │ ├── count-sub-islands-tle.js │ │ │ └── count-sub-islands.js │ │ ├── count_points/ │ │ │ └── count_points.py │ │ ├── counter_number_of_teams/ │ │ │ └── counter_number_of_teams.py │ │ ├── deck_revealed_increasing/ │ │ │ └── deck_revealed_increasing.py │ │ ├── decode-string/ │ │ │ ├── decode-string.js │ │ │ └── tests/ │ │ │ └── decode-string.test.js │ │ ├── deepest_leaves_sum/ │ │ │ └── deepest_leaves_sum.py │ │ ├── delete-node-in-a-linked-list/ │ │ │ ├── better-delete-node-in-a-linked-list.js │ │ │ └── delete-node-in-a-linked-list.js │ │ ├── design-a-stack-with-increment-operation/ │ │ │ ├── design-a-stack-with-increment-operation.js │ │ │ └── tests/ │ │ │ └── design-a-stack-with-increment-operation.test.js │ │ ├── design-add-and-search-words-data-structure/ │ │ │ └── design-add-and-search-words-data-structure.js │ │ ├── difference-between-ones-and-zeros-in-row-and-column/ │ │ │ └── difference-between-ones-and-zeros-in-row-and-column.js │ │ ├── encode_and_decode_tinyurl/ │ │ │ └── encode_and_decode_tinyurl.py │ │ ├── execution-of-all-suffix-instructions-staying-in-a-grid/ │ │ │ └── execution-of-all-suffix-instructions-staying-in-a-grid.js │ │ ├── find-the-original-array-of-prefix-xor/ │ │ │ ├── README.md │ │ │ └── find-the-original-array-of-prefix-xor.js │ │ ├── find-the-winner-of-the-circular-game/ │ │ │ ├── find-the-winner-of-the-circular-game.js │ │ │ └── queue-find-the-winner-of-the-circular-game.js │ │ ├── find-triangular-sum-of-an-array/ │ │ │ ├── find-triangular-sum-of-an-array.js │ │ │ └── tests/ │ │ │ └── find-triangular-sum-of-an-array.test.js │ │ ├── find-valid-matrix-given-row-and-column-sums/ │ │ │ └── find-valid-matrix-given-row-and-column-sums.js │ │ ├── find_and_replace_pattern/ │ │ │ └── find_and_replace_pattern.py │ │ ├── finding_pairs_with_a_certain_sum/ │ │ │ └── finding_pairs_with_a_certain_sum.py │ │ ├── finding_the_users_active_minutes/ │ │ │ └── finding_the_users_active_minutes.py │ │ ├── fraction_to_decimal/ │ │ │ └── fraction_to_decimal.py │ │ ├── group-anagrams/ │ │ │ └── group-anagrams.js │ │ ├── group_the_people/ │ │ │ └── group_the_people.py │ │ ├── insert-greatest-common-divisors-in-linked-list/ │ │ │ └── insert-greatest-common-divisors-in-linked-list.js │ │ ├── insert-into-a-binary-search-tree/ │ │ │ └── insert-into-a-binary-search-tree.js │ │ ├── insert_bst/ │ │ │ └── insert_bst.py │ │ ├── keep_city_skyline/ │ │ │ └── keep_city_skyline.py │ │ ├── kth-smallest-element-in-a-bst/ │ │ │ ├── kth-smallest-element-in-a-bst-1.js │ │ │ ├── kth-smallest-element-in-a-bst-2.js │ │ │ └── kth-smallest-element-in-a-bst.js │ │ ├── letter_tile_possibilities/ │ │ │ └── letter_tile_possibilities.py │ │ ├── longest-substring-without-repeating-characters/ │ │ │ └── longest-substring-without-repeating-characters.js │ │ ├── max-area-of-island/ │ │ │ └── max-area-of-island.js │ │ ├── max_coins/ │ │ │ └── max_coins.py │ │ ├── maximum-sum-of-an-hourglass/ │ │ │ └── maximum-sum-of-an-hourglass.js │ │ ├── maximum_binary_tree/ │ │ │ └── maximum_binary_tree.py │ │ ├── median_tree/ │ │ │ └── median_tree.py │ │ ├── merge-nodes-in-between-zeros/ │ │ │ ├── merge-nodes-in-between-zeros.js │ │ │ └── tests/ │ │ │ └── merge-nodes-in-between-zeros.test.js │ │ ├── min-cost-climbing-stairs/ │ │ │ └── min-cost-climbing-stairs.js │ │ ├── min_operations/ │ │ │ └── min_operations.py │ │ ├── min_pair_sum/ │ │ │ └── min_pair_sum.py │ │ ├── min_partitions/ │ │ │ └── min_partitions.py │ │ ├── minimum-add-to-make-parentheses-valid/ │ │ │ └── minimum-add-to-make-parentheses-valid.js │ │ ├── minimum-amount-of-time-to-collect-garbage/ │ │ │ └── minimum-amount-of-time-to-collect-garbage.js │ │ ├── minimum-cost-of-buying-candies-with-discount/ │ │ │ └── minimum-cost-of-buying-candies-with-discount.js │ │ ├── minimum-number-of-steps-to-make-two-strings-anagram/ │ │ │ ├── README.md │ │ │ └── minimum-number-of-steps-to-make-two-strings-anagram.js │ │ ├── minimum_number_of_operations_to_move_all_balls_to_each_box/ │ │ │ └── minimum_number_of_operations_to_move_all_balls_to_each_box.py │ │ ├── number-of-closed-islands/ │ │ │ └── number-of-closed-islands.js │ │ ├── number-of-enclaves/ │ │ │ └── number-of-enclaves.js │ │ ├── number-of-islands/ │ │ │ └── number-of-islands.js │ │ ├── number-of-laser-beams-in-a-bank/ │ │ │ ├── number-of-laser-beams-in-a-bank.js │ │ │ └── tests/ │ │ │ └── number-of-laser-beams-in-a-bank.test.js │ │ ├── optimal-partition-of-string/ │ │ │ ├── optimal-partition-of-string.js │ │ │ └── optimized-optimal-partition-of-string.js │ │ ├── pair-sum/ │ │ │ ├── pair-sum.js │ │ │ └── tests/ │ │ │ └── pair-sum.test.js │ │ ├── partition-array-according-to-given-pivot/ │ │ │ ├── partition-array-according-to-given-pivot.js │ │ │ └── tests/ │ │ │ └── partition-array-according-to-given-pivot.test.js │ │ ├── permutation-in-string/ │ │ │ ├── permutation-in-string-sliding-window.js │ │ │ └── permutation-in-string.js │ │ ├── populating-next-right-pointers-in-each-node/ │ │ │ ├── populating-next-right-pointers-in-each-node-simpler.js │ │ │ └── populating-next-right-pointers-in-each-node.js │ │ ├── process_queries/ │ │ │ └── process_queries.py │ │ ├── product-of-array-except-self/ │ │ │ └── product-of-array-except-self.js │ │ ├── rearrange-array-elements-by-sign/ │ │ │ ├── rearrange-array-elements-by-sign.js │ │ │ └── tests/ │ │ │ └── rearrange-array-elements-by-sign.test.js │ │ ├── reduce_array_size_to_the_half/ │ │ │ └── reduce_array_size_to_the_half.py │ │ ├── remove-nth-node-from-end-of-list/ │ │ │ ├── remove-nth-node-from-end-of-list-fast-slow.js │ │ │ └── remove-nth-node-from-end-of-list.js │ │ ├── rotate-array/ │ │ │ ├── rotate-array-optimized.js │ │ │ └── rotate-array.js │ │ ├── rotate-image/ │ │ │ └── rotate-image.js │ │ ├── search-a-2d-matrix/ │ │ │ ├── search-a-2d-matrix.js │ │ │ └── search-a-2d-matrix.py │ │ ├── search-a-2d-matrix-ii/ │ │ │ └── search-a-2d-matrix-ii.py │ │ ├── set-matrix-zeroes/ │ │ │ └── set-matrix-zeroes.js │ │ ├── sort-the-students-by-their-kth-score/ │ │ │ └── sort-the-students-by-their-kth-score.js │ │ ├── sort_the_matrix_diagonally/ │ │ │ └── sort_the_matrix_diagonally.py │ │ ├── string-compression/ │ │ │ ├── string-compression-copy.js │ │ │ └── string-compression.js │ │ ├── subrectangle_queries/ │ │ │ └── subrectangle_queries.py │ │ ├── sum_of_nodes/ │ │ │ └── sum_of_nodes.py │ │ ├── two-sum-ii-input-array-is-sorted/ │ │ │ ├── two-sum-ii-input-array-is-sorted-2.js │ │ │ └── two-sum-ii-input-array-is-sorted.js │ │ ├── valid-sudoku/ │ │ │ └── valid-sudoku.js │ │ ├── validate-binary-search-tree/ │ │ │ ├── validate-binary-search-tree-2.js │ │ │ ├── validate-binary-search-tree-almost-right.js │ │ │ └── validate-binary-search-tree.js │ │ └── watering-plants/ │ │ ├── tests/ │ │ │ └── watering-plants.test.js │ │ └── watering-plants.js │ ├── python/ │ │ └── string.py │ └── top-problems/ │ ├── are-anagrams.js │ ├── first-and-last-index.js │ ├── kth-largest.js │ ├── min-sliding-window.js │ └── tests/ │ ├── are-anagrams.test.js │ ├── first-and-last-index.test.js │ └── kth-largest.test.js ├── college/ │ ├── graph/ │ │ └── atoms.py │ └── web/ │ ├── css/ │ │ ├── estilos.css │ │ └── index.html │ ├── index.html │ ├── js.js │ └── loop.js ├── competitive-programming/ │ ├── 4clojure/ │ │ ├── problem01.clj │ │ ├── problem02.clj │ │ ├── problem03.clj │ │ ├── problem04.clj │ │ ├── problem05.clj │ │ ├── problem06.clj │ │ ├── problem07.clj │ │ ├── problem19.clj │ │ └── problem20.clj │ ├── acm-icpc-br/ │ │ ├── regionals_2011/ │ │ │ ├── armstrong.cpp │ │ │ ├── calculadora.cpp │ │ │ ├── cartoes.cpp │ │ │ ├── concurso.cpp │ │ │ ├── coral.cpp │ │ │ ├── elevador.cpp │ │ │ ├── estacionamento.cpp │ │ │ ├── extenso.cpp │ │ │ ├── goldbach.cpp │ │ │ ├── matriz_esparsa.cpp │ │ │ ├── pascal.cpp │ │ │ ├── polinomio.cpp │ │ │ ├── quadrado.cpp │ │ │ └── vagas.cpp │ │ ├── regionals_2017_1/ │ │ │ └── A.cpp │ │ └── regionals_2017_2/ │ │ ├── D.cpp │ │ ├── F.cpp │ │ ├── J.py │ │ └── M.cpp │ ├── codeforces/ │ │ └── div2/ │ │ ├── black_square.cpp │ │ ├── karen_and_morning.cpp │ │ ├── keyboard_layouts.cpp │ │ ├── the_child_and_the_homework.cpp │ │ ├── the_child_and_toy.cpp │ │ └── valera_and_plates.cpp │ ├── exercism/ │ │ ├── clojure/ │ │ │ ├── armstrong-numbers/ │ │ │ │ ├── .exercism/ │ │ │ │ │ └── metadata.json │ │ │ │ ├── .lein-failures │ │ │ │ ├── .lein-repl-history │ │ │ │ ├── README.md │ │ │ │ ├── project.clj │ │ │ │ ├── src/ │ │ │ │ │ └── armstrong_numbers.clj │ │ │ │ ├── target/ │ │ │ │ │ ├── classes/ │ │ │ │ │ │ └── META-INF/ │ │ │ │ │ │ └── maven/ │ │ │ │ │ │ └── armstrong-numbers/ │ │ │ │ │ │ └── armstrong-numbers/ │ │ │ │ │ │ └── pom.properties │ │ │ │ │ └── stale/ │ │ │ │ │ └── leiningen.core.classpath.extract-native-dependencies │ │ │ │ └── test/ │ │ │ │ └── armstrong_numbers_test.clj │ │ │ ├── hello-world/ │ │ │ │ ├── README.md │ │ │ │ ├── project.clj │ │ │ │ ├── src/ │ │ │ │ │ └── hello-world.clj │ │ │ │ └── test/ │ │ │ │ └── hello-world-test.clj │ │ │ └── two-fer/ │ │ │ ├── .exercism/ │ │ │ │ └── metadata.json │ │ │ ├── .lein-failures │ │ │ ├── .nrepl-port │ │ │ ├── README.md │ │ │ ├── project.clj │ │ │ ├── src/ │ │ │ │ └── two_fer.clj │ │ │ ├── target/ │ │ │ │ ├── classes/ │ │ │ │ │ └── META-INF/ │ │ │ │ │ └── maven/ │ │ │ │ │ └── two-fer/ │ │ │ │ │ └── two-fer/ │ │ │ │ │ └── pom.properties │ │ │ │ ├── repl-port │ │ │ │ └── stale/ │ │ │ │ └── leiningen.core.classpath.extract-native-dependencies │ │ │ └── test/ │ │ │ └── two_fer_test.clj │ │ └── javascript/ │ │ ├── allergies.js │ │ ├── collatz-conjecture.js │ │ ├── count-words.js │ │ ├── etl.js │ │ ├── flatten-array.js │ │ ├── gigasecond.js │ │ ├── hello-world.js │ │ ├── leap.js │ │ ├── perfect-numbers.js │ │ ├── phone-number.js │ │ ├── resistor-color.js │ │ ├── resistor-colors.js │ │ ├── reverse-string.js │ │ ├── sublist.js │ │ ├── sum-of-multiples.js │ │ ├── triangle.js │ │ └── two-fer.js │ ├── hacker-rank/ │ │ ├── algorithms/ │ │ │ ├── strings/ │ │ │ │ └── palindrome_index.py │ │ │ └── warmup/ │ │ │ ├── birthday_cake_candles.py │ │ │ └── mini_max_sum.py │ │ ├── cpp/ │ │ │ └── introduction/ │ │ │ ├── angry_professor.cpp │ │ │ ├── arrays_introduction.cpp │ │ │ ├── diagonal_difference.cpp │ │ │ ├── input_and_output.cpp │ │ │ ├── library_fine.cpp │ │ │ ├── plus_minus.cpp │ │ │ ├── staircase.cpp │ │ │ ├── time_conversion.cpp │ │ │ ├── vector_erase.cpp │ │ │ └── vector_sort.cpp │ │ ├── data_structures/ │ │ │ └── trees/ │ │ │ ├── in_order_traversal.py │ │ │ ├── post_order_traversal.py │ │ │ └── pre_order_traversal.py │ │ ├── functional-programming/ │ │ │ ├── array_of_n_elements/ │ │ │ │ ├── array_of_n_elements.clj │ │ │ │ └── array_of_n_elements_without_range.clj │ │ │ ├── basics/ │ │ │ │ ├── hello_world.clj │ │ │ │ ├── hello_world_n_times.clj │ │ │ │ └── solve_me_first.clj │ │ │ ├── eval_ex/ │ │ │ │ └── main.clj │ │ │ ├── filter_array/ │ │ │ │ └── filter_array.clj │ │ │ ├── filter_positions_in_a_list/ │ │ │ │ └── filter_positions_in_a_list.clj │ │ │ ├── list_length/ │ │ │ │ ├── list_length.clj │ │ │ │ └── list_length_reduce.clj │ │ │ ├── list_replication/ │ │ │ │ └── list_replication.clj │ │ │ ├── reverse_a_list/ │ │ │ │ ├── reverse_a_list.clj │ │ │ │ ├── reverse_a_list_into.clj │ │ │ │ └── reverse_a_list_reduce.clj │ │ │ ├── sum_of_odd_elements/ │ │ │ │ └── sum_of_odd_elements.clj │ │ │ └── update_list/ │ │ │ ├── update_list.clj │ │ │ ├── update_list_anonymous.clj │ │ │ ├── update_list_map.clj │ │ │ └── update_list_map_anonymous.clj │ │ └── python/ │ │ ├── basic_data_types/ │ │ │ ├── finding_the_percentage.py │ │ │ ├── lists.py │ │ │ ├── nested_list.py │ │ │ ├── runner_up_score.py │ │ │ └── tuple.py │ │ ├── introduction/ │ │ │ ├── arithmetic_operators.py │ │ │ ├── division.py │ │ │ └── if_else.py │ │ ├── sets/ │ │ │ └── intro_to_sets.py │ │ └── strings/ │ │ ├── find_a_string.py │ │ ├── mutate_string.py │ │ ├── split_and_join.py │ │ ├── string_validators.py │ │ ├── swap_case.py │ │ ├── text_wrap.py │ │ └── whats_your_name.py │ ├── interfatecs/ │ │ ├── 1_2016/ │ │ │ ├── a.cpp │ │ │ ├── b.cpp │ │ │ ├── g.cpp │ │ │ └── i.cpp │ │ └── 1_2018/ │ │ ├── a.cpp │ │ ├── b.cpp │ │ ├── c.cpp │ │ ├── d.py │ │ ├── e.py │ │ ├── f.py │ │ ├── g.cpp │ │ ├── h.cpp │ │ ├── i.py │ │ └── j.cpp │ ├── spoj-br/ │ │ ├── aero.cpp │ │ ├── bafo.cpp │ │ ├── bapostas.cpp │ │ ├── bit.cpp │ │ ├── calcula.cpp │ │ ├── calculadora.cpp │ │ ├── dentista.cpp │ │ ├── desculpa.cpp │ │ ├── eleicoes1.cpp │ │ ├── eleicoes2.cpp │ │ ├── estagio.cpp │ │ ├── fatorial.cpp │ │ ├── feyman.cpp │ │ ├── fliperam.cpp │ │ ├── gangorra.cpp │ │ ├── guardacosta.cpp │ │ ├── impedido.cpp │ │ ├── letra.cpp │ │ ├── loopmusi.cpp │ │ ├── lua.cpp │ │ ├── macaco.cpp │ │ ├── minhoca.cpp │ │ ├── miojo.cpp │ │ ├── obi.cpp │ │ ├── obihanoi.cpp │ │ ├── parprox.cpp │ │ ├── peca.cpp │ │ ├── primo.cpp │ │ ├── rumo9s.cpp │ │ ├── saldo.cpp │ │ ├── saldo13.cpp │ │ ├── sorvete.cpp │ │ ├── sudoku.cpp │ │ ├── telefone.cpp │ │ ├── transporte.cpp │ │ ├── troco13.cpp │ │ ├── vivo.cpp │ │ └── wcw.cpp │ ├── timus/ │ │ └── a+b_problem.cpp │ ├── ucoder/ │ │ ├── armstrong_numbers.cpp │ │ ├── historico_de_comandos.cpp │ │ ├── imperador_cassius.cpp │ │ ├── matriz_esparsa.cpp │ │ ├── obi.cpp │ │ └── tsetse.cpp │ ├── uri/ │ │ ├── 3d_virtual_museum.cpp │ │ ├── a_long_time_ago.cpp │ │ ├── above_average.cpp │ │ ├── above_secundary_diagonal.cpp │ │ ├── above_the_main_diagonal.cpp │ │ ├── abracadabra.cpp │ │ ├── advancing_letters.cpp │ │ ├── age_in_day.cpp │ │ ├── ages.cpp │ │ ├── alarm_clock.cpp │ │ ├── alliteration.cpp │ │ ├── andys_first_dictionary.cpp │ │ ├── angry_ducks.cpp │ │ ├── animal.cpp │ │ ├── approximate_number_of_primes.cpp │ │ ├── area.cpp │ │ ├── area_of_circle.cpp │ │ ├── arranging_tasks.cpp │ │ ├── array_123.cpp │ │ ├── array_change_1.cpp │ │ ├── array_fill_1.cpp │ │ ├── array_fill_2.cpp │ │ ├── array_fill_3.cpp │ │ ├── array_fill_4.cpp │ │ ├── array_hash.cpp │ │ ├── array_replacement_1.cpp │ │ ├── array_selection_1.cpp │ │ ├── as_abas_de_pericles.cpp │ │ ├── ascending_and_descending.cpp │ │ ├── assigning_teams.cpp │ │ ├── automated_checking_machine.cpp │ │ ├── average_1.cpp │ │ ├── average_2.cpp │ │ ├── average_3.cpp │ │ ├── average_speed.cpp │ │ ├── back_to_high_school_physics.cpp │ │ ├── bacteria_1.cpp │ │ ├── banknotes.cpp │ │ ├── banknotes_and_coins.cpp │ │ ├── baskharas_formula.cpp │ │ ├── batmain.cpp │ │ ├── bazinga.cpp │ │ ├── below_the_main_diagonal.cpp │ │ ├── below_the_secundary_diagonal.cpp │ │ ├── bill.cpp │ │ ├── bingo.cpp │ │ ├── bla.cpp │ │ ├── blobs.cpp │ │ ├── bloggo_shotcuts.cpp │ │ ├── bob_conduit.cpp │ │ ├── bodybuilder.cpp │ │ ├── brazil_world_cup.cpp │ │ ├── brazilian_economy.cpp │ │ ├── brick_game.cpp │ │ ├── bubbles_and_bucket.cpp │ │ ├── bubbles_and_bucket_2.cpp │ │ ├── building_houses.cpp │ │ ├── building_walls.cpp │ │ ├── buttlerflies.cpp │ │ ├── c_mais_ou_menos.cpp │ │ ├── caeser_cipher.cpp │ │ ├── cannon.cpp │ │ ├── canteen_queue.cpp │ │ ├── cash_roial.cpp │ │ ├── chinese_whispers.cpp │ │ ├── chirrin_chirrion.cpp │ │ ├── chocolate_factory.cpp │ │ ├── christmas_decoration.cpp │ │ ├── christmas_olympic.cpp │ │ ├── christmas_trapeziums.cpp │ │ ├── christmas_tree.cpp │ │ ├── close_the_doors.cpp │ │ ├── coast_guard.cpp │ │ ├── coffee_machine.cpp │ │ ├── colision.cpp │ │ ├── collectable_cards.cpp │ │ ├── colourful_flowers.cpp │ │ ├── column_in_array.cpp │ │ ├── combiner.cpp │ │ ├── compare_substring.cpp │ │ ├── complete_sequence.cpp │ │ ├── consumption.cpp │ │ ├── contando_ciclos.cpp │ │ ├── contest.cpp │ │ ├── contract_revision.cpp │ │ ├── converting_to_hexadecimal.cpp │ │ ├── coordinates_of_a_point.cpp │ │ ├── correct_colourful_flower.cpp │ │ ├── corrida.cpp │ │ ├── counting_crow.cpp │ │ ├── counting_sheeps.cpp │ │ ├── cutoff_rounder.cpp │ │ ├── cutoff_rounder_2.cpp │ │ ├── dancing_sentence.cpp │ │ ├── dangerous_dive.cpp │ │ ├── dating_online.cpp │ │ ├── deciphering_the_encrypted_card.cpp │ │ ├── delaunay_triangulation.cpp │ │ ├── desafio_de_bino.cpp │ │ ├── detective_watson_1.cpp │ │ ├── detective_watson_2.cpp │ │ ├── diamonds_and_sand.cpp │ │ ├── diet_plan.cpp │ │ ├── difference.cpp │ │ ├── different_digits.cpp │ │ ├── difn.cpp │ │ ├── dijkstra.cpp │ │ ├── discovering_password.cpp │ │ ├── distance.cpp │ │ ├── distance_between_two_points.cpp │ │ ├── dividers.cpp │ │ ├── dividing_x_by_y.cpp │ │ ├── diving.cpp │ │ ├── division_of_nlogonia.cpp │ │ ├── divisors_1.cpp │ │ ├── dracarys.cpp │ │ ├── drought.cpp │ │ ├── easy_difference_dates.cpp │ │ ├── easy_fibonacci.cpp │ │ ├── easy_problem_from_rujia_liu_1.cpp │ │ ├── easy_problem_from_rujia_liu_2.cpp │ │ ├── eletrical_outlet.cpp │ │ ├── encryption.cpp │ │ ├── engine_failure.cpp │ │ ├── erasing_and_winning.cpp │ │ ├── estimating_the_mean.cpp │ │ ├── etiquetas_de_noel.cpp │ │ ├── even_and_odd.cpp │ │ ├── even_between_five_numbers.cpp │ │ ├── even_numbers.cpp │ │ ├── even_or_odd.cpp │ │ ├── even_square.cpp │ │ ├── event.cpp │ │ ├── event_time.cpp │ │ ├── exceeding_z.cpp │ │ ├── exchanging_cards.cpp │ │ ├── experiments.cpp │ │ ├── extremely_basic.cpp │ │ ├── face_2015_free_gift.cpp │ │ ├── factorial.cpp │ │ ├── factorial_again.cpp │ │ ├── factorial_sum.cpp │ │ ├── fake_tickets.cpp │ │ ├── fans_and_ballons.cpp │ │ ├── farm_robot.cpp │ │ ├── fase.cpp │ │ ├── fast_fibonacci.cpp │ │ ├── fast_prime_number.cpp │ │ ├── feedback.cpp │ │ ├── feyman.cpp │ │ ├── fibonacci_again.cpp │ │ ├── fibonacci_array.cpp │ │ ├── fila_do_supermercado.cpp │ │ ├── fire_flowers.cpp │ │ ├── fit_or_dont_fit_1.cpp │ │ ├── fit_or_dont_fit_2.cpp │ │ ├── fixed_password.cpp │ │ ├── flavious_josephus_legend.cpp │ │ ├── flavious_josephus_legend2.cpp │ │ ├── flavious_josephus_legend3.cpp │ │ ├── flowers_flourish_from_france.cpp │ │ ├── football.cpp │ │ ├── frequent_asked_questions.cpp │ │ ├── friends_of_habey.cpp │ │ ├── fuel_spent.cpp │ │ ├── functions.cpp │ │ ├── galopeira.cpp │ │ ├── game_of_the_greatness.cpp │ │ ├── general_exam.cpp │ │ ├── getline_fruits.cpp │ │ ├── getline_one.cpp │ │ ├── getline_three_shoes.cpp │ │ ├── going_to_the_market.cpp │ │ ├── grains_in_a_chess_board.cpp │ │ ├── grenais.cpp │ │ ├── growing_sequences.cpp │ │ ├── guess_what.cpp │ │ ├── guilherme_and_his_kites.cpp │ │ ├── guru_da_sorte.cpp │ │ ├── hailstone_sequences.cpp │ │ ├── hall_of_murderers.cpp │ │ ├── hall_of_murderers_2.cpp │ │ ├── hall_of_murderers_3.cpp │ │ ├── hamekameka.cpp │ │ ├── handball.cpp │ │ ├── hardwood_species.cpp │ │ ├── hash_tables.cpp │ │ ├── hashmat_the_brave_warrior.cpp │ │ ├── hay_points.cpp │ │ ├── he_is_offside!.cpp │ │ ├── head_or_tails.cpp │ │ ├── height.cpp │ │ ├── hello_galaxy.cpp │ │ ├── help!.cpp │ │ ├── help_girafales.cpp │ │ ├── help_seu_madruga.cpp │ │ ├── help_seu_madruga_int.cpp │ │ ├── help_the_federation.cpp │ │ ├── hexagonal_tiles_1.cpp │ │ ├── hexagonal_tiles_2.cpp │ │ ├── hidden_message.cpp │ │ ├── highest_and_position.cpp │ │ ├── hohoho.cpp │ │ ├── honey_reservoir.cpp │ │ ├── hours_and_minutes.cpp │ │ ├── how_easy.cpp │ │ ├── huehue.cpp │ │ ├── i_am_toorg.cpp │ │ ├── ice_statuses.cpp │ │ ├── identifying_tea.cpp │ │ ├── image.cpp │ │ ├── impar_par_roubo.cpp │ │ ├── inferior_area.cpp │ │ ├── inside_out.cpp │ │ ├── international_chat.cpp │ │ ├── internship.cpp │ │ ├── interval.cpp │ │ ├── interval2.cpp │ │ ├── inverse_numbers.cpp │ │ ├── is_triangle.cpp │ │ ├── jetiqui.cpp │ │ ├── jingle_composing.cpp │ │ ├── jogatina_ufpa.cpp │ │ ├── jogo_da_boca.py │ │ ├── jollo.cpp │ │ ├── joulupukki.cpp │ │ ├── jumping_frog.cpp │ │ ├── just_in_time.cpp │ │ ├── justifier.cpp │ │ ├── justifier_2.cpp │ │ ├── kage_bunshin_no_jutsu.cpp │ │ ├── kiloman.cpp │ │ ├── koch_snowflake.cpp │ │ ├── lap.cpp │ │ ├── laser_sculpture.cpp │ │ ├── last_analogimon.cpp │ │ ├── laundry.cpp │ │ ├── leaders_impeachment.cpp │ │ ├── led.cpp │ │ ├── left_area.cpp │ │ ├── libertadores_1.cpp │ │ ├── libertadores_2.cpp │ │ ├── line_in_array.cpp │ │ ├── linear_parking_lot.cpp │ │ ├── little_ant.cpp │ │ ├── little_ducks.py │ │ ├── logical_sequence.cpp │ │ ├── logical_sequence_2.cpp │ │ ├── lost_boots.cpp │ │ ├── lowest_number_and_position.cpp │ │ ├── lu_di_oh.cpp │ │ ├── lucro.cpp │ │ ├── lucro_otimizado.cpp │ │ ├── macpronalts.cpp │ │ ├── maesters_map.cpp │ │ ├── mean_median_problem.cpp │ │ ├── medal_table.cpp │ │ ├── merry_christmaaaas.cpp │ │ ├── mirror_sequence.cpp │ │ ├── mjolnir.cpp │ │ ├── monetary_formatting.cpp │ │ ├── montanha_russa.cpp │ │ ├── month.cpp │ │ ├── moon_phases.cpp │ │ ├── morse.cpp │ │ ├── motoboy.cpp │ │ ├── multiple_of_13.cpp │ │ ├── multiple_reading.cpp │ │ ├── multiples.cpp │ │ ├── multiplication_table.cpp │ │ ├── musical_loop.cpp │ │ ├── name_at_form.cpp │ │ ├── natural_sum.cpp │ │ ├── new_record.cpp │ │ ├── nine.cpp │ │ ├── number_frequence.cpp │ │ ├── obi_uri.cpp │ │ ├── odd_numbers.cpp │ │ ├── og.cpp │ │ ├── one_two_three.cpp │ │ ├── operator_game.cpp │ │ ├── optical_reader.cpp │ │ ├── our_days_are_never_coming_back.cpp │ │ ├── painel_led.cpp │ │ ├── palindrome_game.cpp │ │ ├── pandorgas.cpp │ │ ├── pao_de_queijo_sweeper.cpp │ │ ├── parafusos_e_porcas.cpp │ │ ├── parenthesis_balance.cpp │ │ ├── parity.cpp │ │ ├── pascal_library.cpp │ │ ├── password.cpp │ │ ├── password_validator.cpp │ │ ├── paulas_mathematic_game.cpp │ │ ├── peaks_and_valleys.cpp │ │ ├── pedrinhos_christmas.cpp │ │ ├── pepe.cpp │ │ ├── perfect_number.cpp │ │ ├── phin_bonati.cpp │ │ ├── pizza_pre_bh.cpp │ │ ├── pokemon.cpp │ │ ├── pomekon_collection.cpp │ │ ├── pomekons_battle.cpp │ │ ├── population_increase.cpp │ │ ├── positive_numbers.cpp │ │ ├── positives_and_average.cpp │ │ ├── power_crisis.cpp │ │ ├── preface.cpp │ │ ├── presents.cpp │ │ ├── primary_arithmatic.cpp │ │ ├── prime_number.cpp │ │ ├── pum.cpp │ │ ├── quadrant.cpp │ │ ├── queen.cpp │ │ ├── radares.cpp │ │ ├── rails.cpp │ │ ├── rails_again.cpp │ │ ├── reading_books.cpp │ │ ├── regular_simple_polygon.cpp │ │ ├── remaining2.cpp │ │ ├── removing_letter.cpp │ │ ├── rest_of_a_division.cpp │ │ ├── right_area.cpp │ │ ├── rlj.cpp │ │ ├── robot_instructions.cpp │ │ ├── rock_paper_airstrike.cpp │ │ ├── rock_paper_scissors_lizard_spock.cpp │ │ ├── roman_numerals_for_page_numbers.cpp │ │ ├── rot13.cpp │ │ ├── s_sequence.cpp │ │ ├── s_sequence_2.cpp │ │ ├── salary.cpp │ │ ├── salary_with_bonus.cpp │ │ ├── santas_translator.cpp │ │ ├── scientific_notation.cpp │ │ ├── score_validation.cpp │ │ ├── searching_for_nessy.cpp │ │ ├── searching_subsequences.cpp │ │ ├── selection_test_1.cpp │ │ ├── sequence_ij_1.cpp │ │ ├── sequence_ij_2.cpp │ │ ├── sequence_ij_3.cpp │ │ ├── sequence_ij_4.cpp │ │ ├── sequence_of_numbers_and_sum.cpp │ │ ├── sequence_of_sequence.cpp │ │ ├── seven.cpp │ │ ├── several_scores_with_validation.cpp │ │ ├── short_attendance.cpp │ │ ├── short_story.cpp │ │ ├── simple_calculate.cpp │ │ ├── simple_factorial.cpp │ │ ├── simple_prod.cpp │ │ ├── simple_sort.cpp │ │ ├── simple_sum.cpp │ │ ├── simulator.cpp │ │ ├── six_odd_numbers.cpp │ │ ├── snack.cpp │ │ ├── sort_by_length.cpp │ │ ├── sort_sort_and_sort.cpp │ │ ├── sphere.cpp │ │ ├── spurs_rock.cpp │ │ ├── square_array_4.cpp │ │ ├── square_game.cpp │ │ ├── square_matrix_1.cpp │ │ ├── square_matrix_2.cpp │ │ ├── square_matrix_3.cpp │ │ ├── square_root_of_10.cpp │ │ ├── square_root_of_2.cpp │ │ ├── square_spiral.cpp │ │ ├── squared_and_cubic.cpp │ │ ├── ssn_1.cpp │ │ ├── star_trek.cpp │ │ ├── start_grid.cpp │ │ ├── stick_collector_robot.cpp │ │ ├── sticks_game.cpp │ │ ├── strategy_game.cpp │ │ ├── subprime.cpp │ │ ├── sucessor_par.cpp │ │ ├── sudoku.cpp │ │ ├── sum_of_consecutive_even_numbers.cpp │ │ ├── sum_of_consecutive_odd_numbers_3.cpp │ │ ├── sum_of_consecutive_odd_numbers_I.cpp │ │ ├── sum_of_consecutive_odd_numbers_II.cpp │ │ ├── sum_of_two_squares.cpp │ │ ├── summer_camp.cpp │ │ ├── summing_consecutive_integers.cpp │ │ ├── sunday_morning.cpp │ │ ├── superior_area.cpp │ │ ├── system_of_download.cpp │ │ ├── taxes_of_project.cpp │ │ ├── tda_rational_1.cpp │ │ ├── tda_rational_2.cpp │ │ ├── tell_me_the_frequencies.cpp │ │ ├── the_chosen.cpp │ │ ├── the_force_awakens.cpp │ │ ├── the_greater_one_digit_number.cpp │ │ ├── the_greatest.cpp │ │ ├── the_library_of_mr_severino.cpp │ │ ├── the_motion_picture.cpp │ │ ├── the_pythagorean_theorem.cpp │ │ ├── the_race_of_slugs.cpp │ │ ├── the_return_of_radar.cpp │ │ ├── the_return_of_the_king.cpp │ │ ├── the_square_game.cpp │ │ ├── the_wrath_of_khan.cpp │ │ ├── theons_answer.cpp │ │ ├── threebonacci_sequence.cpp │ │ ├── throwing_cards_away.cpp │ │ ├── time_conversion.cpp │ │ ├── time_zone.cpp │ │ ├── to_care_or_not_to_care.cpp │ │ ├── to_care_or_not_to_care2.cpp │ │ ├── top_n.cpp │ │ ├── tornado.cpp │ │ ├── train_swaping.cpp │ │ ├── tri-du.cpp │ │ ├── triangle.cpp │ │ ├── triangle_types.cpp │ │ ├── triangles.cpp │ │ ├── tribol.cpp │ │ ├── trinomial_triangle.cpp │ │ ├── tshirt2.cpp │ │ ├── tshirts.cpp │ │ ├── tug_of_war.cpp │ │ ├── turma_jb6.cpp │ │ ├── turn_left.cpp │ │ ├── turn_left2.cpp │ │ ├── tustin_and_his_new_die.cpp │ │ ├── twilight_at_portland.cpp │ │ ├── twitting.cpp │ │ ├── two_bills.cpp │ │ ├── type_of_fuel.cpp │ │ ├── upset_fracil.cpp │ │ ├── uri.cpp │ │ ├── vai_na_sort.cpp │ │ ├── variations.cpp │ │ ├── virus.cpp │ │ ├── vitoria_and_her_indecision.cpp │ │ ├── volleyball.cpp │ │ ├── weighted_averages.cpp │ │ ├── welcome_to_the_winter.cpp │ │ ├── wertyu.cpp │ │ ├── where_is_the_marble.cpp │ │ ├── which_triangle.cpp │ │ ├── who_turn_is_it.cpp │ │ ├── wills_message.cpp │ │ ├── world_cup.cpp │ │ ├── zero_means_zero.cpp │ │ └── zero_or_one.cpp │ ├── uva/ │ │ └── 280-vertex.cpp │ └── weekend-code-challenge/ │ ├── 01-object-to-array-of-objects/ │ │ ├── README.md │ │ └── soluition1.js │ ├── 02-my-likes/ │ │ ├── README.md │ │ ├── solution1.js │ │ └── solution2.js │ ├── 03-ch-ch-ch-changes/ │ │ ├── README.md │ │ └── solution.js │ ├── 07-zero-to-hero/ │ │ ├── README.md │ │ └── solution1.js │ ├── 08-first-non-repeat/ │ │ ├── README.md │ │ └── solution1.js │ ├── 09-big-three/ │ │ ├── README.md │ │ ├── solution1.js │ │ └── solution2.js │ ├── 10-get-the-photo/ │ │ ├── README.md │ │ └── solution1.js │ └── 11-threes-a-crowd/ │ ├── README.md │ └── solution1.js ├── computer_science/ │ ├── README.md │ ├── algorithms/ │ │ ├── binary-search/ │ │ │ ├── binary-search.js │ │ │ └── tests/ │ │ │ └── binary-search.test.js │ │ ├── bubble-sort/ │ │ │ ├── bubble-sort.js │ │ │ └── tests/ │ │ │ └── bubble-sort.test.js │ │ ├── dynamic_programming/ │ │ │ ├── factorial.cpp │ │ │ └── fibonacci.cpp │ │ ├── find_kth_element/ │ │ │ └── find_kth_element_1.cpp │ │ ├── graphs/ │ │ │ ├── bfs.cpp │ │ │ └── dfs.cpp │ │ ├── is-prime/ │ │ │ └── is-prime.js │ │ ├── kadane/ │ │ │ └── kadane.js │ │ ├── knapsack/ │ │ │ ├── knapsack1.cpp │ │ │ └── knapsack2.cpp │ │ ├── least_common_multiple/ │ │ │ └── least_common_multiple.cpp │ │ ├── linear-search/ │ │ │ ├── linear-search.js │ │ │ └── tests/ │ │ │ └── linear-search.test.js │ │ ├── maximum_subsequence_sum/ │ │ │ ├── maximum_subsequence_sum_1.cpp │ │ │ └── maximum_subsequence_sum_2.cpp │ │ ├── min_and_max/ │ │ │ └── minimax.cpp │ │ ├── parse_strings/ │ │ │ └── parse_strings.cpp │ │ ├── pointers/ │ │ │ └── pointer.cpp │ │ ├── prime_number/ │ │ │ └── prime_number.cpp │ │ ├── recursion/ │ │ │ ├── fibonacci/ │ │ │ │ ├── fibonacci.c │ │ │ │ └── fibonacci.py │ │ │ ├── log_2.c │ │ │ ├── palindromo.c │ │ │ ├── regua.c │ │ │ ├── reverse.c │ │ │ └── sum.py │ │ ├── reverse-string/ │ │ │ ├── reverse-string-in-place.js │ │ │ ├── reverse-string.js │ │ │ └── tests/ │ │ │ └── reverse-string.test.js │ │ ├── search/ │ │ │ ├── binary_search.cpp │ │ │ ├── binary_search.py │ │ │ ├── recursive_binary_search.py │ │ │ └── sequential_search.py │ │ ├── segment-tree/ │ │ │ └── sum/ │ │ │ └── lazy_update.cpp │ │ ├── sorting/ │ │ │ ├── bubble_sort/ │ │ │ │ ├── bubble_sort.cpp │ │ │ │ ├── bubble_sort.py │ │ │ │ └── test_bubble_sort.py │ │ │ ├── insertion_sort.cpp │ │ │ ├── merge_sort.cpp │ │ │ ├── reverse_insertion_sort.cpp │ │ │ ├── selection_sort.cpp │ │ │ └── string_insertion_sort.cpp │ │ ├── string_to_int/ │ │ │ └── string_to_int.cpp │ │ └── subset/ │ │ └── subset.js │ ├── big_o/ │ │ ├── README.md │ │ ├── example1.py │ │ ├── example10.py │ │ ├── example11.py │ │ ├── example12.py │ │ ├── example13.py │ │ ├── example14.py │ │ ├── example15.py │ │ ├── example16.py │ │ ├── example17.py │ │ ├── example18.py │ │ ├── example19.py │ │ ├── example2.py │ │ ├── example20.py │ │ ├── example21.py │ │ ├── example22.py │ │ ├── example3.py │ │ ├── example4.py │ │ ├── example5.py │ │ ├── example6.py │ │ ├── example7.py │ │ └── example9.py │ └── data_structures/ │ ├── array/ │ │ ├── array.cpp │ │ ├── big_o.py │ │ ├── list.py │ │ └── vectors.cpp │ ├── binary-heap/ │ │ ├── README.md │ │ ├── min-heap.js │ │ └── min-heap.test.js │ ├── binary_search_tree/ │ │ ├── BinarySearchTree/ │ │ │ ├── index.js │ │ │ └── index.test.js │ │ ├── big_o.py │ │ ├── binary_search_tree.py │ │ ├── test_binary_search_tree.py │ │ └── test_node.py │ ├── binary_search_tree_without_node/ │ │ ├── binary_search_tree.py │ │ └── test_binary_search_tree.py │ ├── binary_tree/ │ │ ├── BinaryTree/ │ │ │ ├── index.js │ │ │ └── index.test.js │ │ ├── big_o.py │ │ ├── binary_tree.py │ │ └── test_binary_tree.py │ ├── graph/ │ │ ├── AdjacentListGraph/ │ │ │ ├── AdjacentListGraph.js │ │ │ └── example.js │ │ ├── README.md │ │ ├── adjacency_list.cpp │ │ ├── graph.js │ │ ├── graph.py │ │ └── test_graph.py │ ├── hash_table/ │ │ ├── big_o.py │ │ ├── dictionary.py │ │ └── maps.cpp │ ├── linked_list/ │ │ ├── big-o.js │ │ ├── big_o.py │ │ ├── linked-list.js │ │ ├── linked_list.py │ │ ├── test_linked_list.py │ │ ├── test_node.py │ │ └── tests/ │ │ └── linked-list.test.js │ ├── queue/ │ │ ├── big_o.py │ │ ├── queue.js │ │ ├── queue.py │ │ └── tests/ │ │ └── queue.test.js │ ├── segment_tree/ │ │ ├── frequency.cpp │ │ ├── max.cpp │ │ ├── min.cpp │ │ └── sum.cpp │ ├── set/ │ │ ├── set.js │ │ ├── sets.cpp │ │ └── tests/ │ │ └── set.test.js │ ├── stack/ │ │ ├── deque_api.py │ │ ├── stack.cpp │ │ ├── stack.js │ │ ├── stack.py │ │ ├── stack_class.js │ │ └── stack_closure.js │ └── string/ │ └── strings.cpp ├── package.json ├── problem-solving.md └── system-design.md ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/push-ci.yml ================================================ name: Push CI on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Read .nvmrc run: echo "##[set-output name=NVMRC;]$(cat .nvmrc)" id: nvm - name: Use Node.js (.nvmrc) uses: actions/setup-node@v2 with: node-version: '${{ steps.nvm.outputs.NVMRC }}' - name: Install dependencies run: yarn - name: Test run: yarn test ================================================ FILE: .gitignore ================================================ *.pyc __pycache__ .pytest_cache # dependencies /node_modules /.pnp .pnp.js # testing /coverage # production /build # misc .DS_Store *.pem # debug npm-debug.log* yarn-debug.log* yarn-error.log* # typescript *.tsbuildinfo .eslintcache /local ================================================ FILE: .nvmrc ================================================ v20.4.0 ================================================ FILE: .prettierrc ================================================ { "trailingComma": "es5", "tabWidth": 2, "singleQuote": true } ================================================ FILE: .vscode/settings.json ================================================ { "[javascript]": { "editor.defaultFormatter": "esbenp.prettier-vscode" } } ================================================ FILE: FUNDING.yml ================================================ github: [imteekay] custom: [https://teekay.substack.com] ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) TK Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # Algorithms & Data Structures ## Introduction - [🎥 Algorithms and Data Structures Tutorial](https://www.youtube.com/watch?v=8hly31xKli0&ab_channel=freeCodeCamp.org) - [🎥 Data Structures and Algorithms in JavaScript](https://www.youtube.com/playlist?list=PLWKjhJtqVAbkso-IbgiiP48n-O-JQA9PJ) - [🎥 Introduction to Algorithms](https://www.youtube.com/playlist?list=PLUl4u3cNGP63EdVPNLG3ToM6LaEUuStEY) - [🎥 Python Algorithms for Interviews](https://www.youtube.com/watch?v=p65AHm9MX80) - [📝 Introduction of Data Structure and algorithm](https://www.scaler.com/topics/data-structures) - [📝 Top 10 algorithms in interview questions](https://www.geeksforgeeks.org/top-10-algorithms-in-interview-questions) - [📝 Useful links about algorithms](https://leetcode.com/discuss/general-discussion/665604/important-and-useful-links-from-all-over-the-Leetcode) - [Leetcode lists](https://docs.google.com/document/d/1lHB0yI7UDcllyCQYqxCHLmFM1F4THDCfrj7_3zC6sDE/edit?tab=t.0) ## Big-O notation and design - [🎥 Big O Notation w/ Gayle](https://www.youtube.com/watch?v=v4cd1O4zkGw&ab_channel=HackerRank) - [🎥 Design and Analysis of Algorithms — MIT](https://www.youtube.com/playlist?list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp) - [💻 Big O](computer_science/big_o) - [📝 Know your complexities: Big-O cheat sheet](https://www.bigocheatsheet.com) - [📝 Big O in DS](./big-o.md) - [📝 Computational complexity part one](https://www.topcoder.com/thrive/articles/Computational%20Complexity%20part%20one) - [📝 Computational complexity part two](https://www.topcoder.com/thrive/articles/Computational%20Complexity%20part%20two) ## Data Structures - [🎥 Data Structures Easy to Advanced Course - Full Tutorial from a Google Engineer](https://www.youtube.com/watch?v=RBSGKlAvoiM) - [💻 Data Structures and Algorithms cheat sheet](https://github.com/TSiege/Tech-Interview-Cheat-Sheet) - [📝 What is Data Structure?](https://www.scaler.com/topics/data-structures/what-is-data-structure) ### Stack - [📝 Stack Data Structure in JavaScript](https://www.iamtk.co/series/data-structures-in-javascript/stack-data-structure) - [📝 Stack Data Structure Practice Problems](https://medium.com/techie-delight/stack-data-structure-practice-problems-and-interview-questions-9f08a35a7f19) - [📝 Stack Data Structure](https://www.iamtk.co/series/data-structures/stack-data-structure) ### Queues - [📝 Queue Data Structure in JavaScript](https://www.iamtk.co/series/data-structures-in-javascript/queue-data-structure) - [📝 Queue Data Structure](https://www.iamtk.co/series/data-structures/queue-data-structure) - [📝 Queue Data Structure](https://www.scaler.com/topics/data-structures/queue-in-data-structure) ### Linked Lists - [🎥 Linked Lists for Technical Interviews](https://www.youtube.com/watch?v=Hj_rA0dhr2I&ab_channel=freeCodeCamp.org) - [📝 Linked Lists Data Structure in JavaScript](https://www.iamtk.co/series/data-structures-in-javascript/linked-list-data-structure) - [📝 Linked Lists Data Structure](https://www.iamtk.co/series/data-structures/linked-list-data-structure) - [📝 Linked Lists Data Structure](https://www.scaler.com/topics/linked-list) ### Trees - [🎥 Binary Tree Algorithms for Technical Interviews](https://www.youtube.com/watch?v=fAAZixBzIAI&ab_channel=freeCodeCamp.org) - [📝 Tree Data Structure](https://www.iamtk.co/series/data-structures/tree-data-structure) - [📝 Tree Data Structure](https://www.scaler.com/topics/data-structures/tree-data-structure) ### Graphs - [🎥 Breadth First Search & Depth First Search](https://www.youtube.com/watch?v=pcKY4hjDrxk&ab_channel=AbdulBari) - [🎥 Graph Algorithms for Technical Interviews](https://www.youtube.com/watch?v=tWVWeAqZ0WU&ab_channel=freeCodeCamp.org) - [🎥 Graph data structure — Part 1](https://www.youtube.com/watch?v=JDP1OVgoa0Q&ab_channel=JunminLee) - [🎥 Graph data structure — Part 2](https://www.youtube.com/watch?v=bSZ57h7GN2w&ab_channel=JunminLee) - [🎥 Graph Search Algorithms in 100 Seconds](https://www.youtube.com/watch?v=cWNEl4HE2OE&ab_channel=Fireship) - [📝 Depth First Search](https://www.hackerearth.com/practice/algorithms/graphs/depth-first-search/tutorial) - [📝 Graph in Data Structure](https://www.scaler.com/topics/data-structures/graph-in-data-structure) ## Algorithms - [🎥 Problem Patterns](https://designgurus.org/course/grokking-the-coding-interview) - [🎥 Programação Dinamica](https://www.youtube.com/watch?v=qp9UOJ0XUlg&ab_channel=GubnunBR) - [📝 3 Tricks To Master Linked List Problems](https://medium.com/interviewnoodle/leetcode-3-tricks-to-master-linked-list-problems-8647a74a5f1c) - [📝 3 Tricks To Master String Problems](https://medium.com/interviewnoodle/leetcode-3-tricks-to-master-string-problems-bf10079df639) - [📝 5 Tricks To Solve Any Interval/Conflict Schedule Related Problems](https://medium.com/interviewnoodle/leetcode-5-tricks-to-solve-any-interval-conflict-schedule-related-problems-3f33d6e5af55) - [📝 Coding Patterns - Backtracking](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-thes-patterns-backtracking-b683aa8bd8ac) - [📝 Coding Patterns - BFS](https://iorilan.medium.com/after-finished-1000-leetcode-medium-level-i-found-some-patterns-bfs-63783cbd2c70) - [📝 Coding Patterns - DFS](https://iorilan.medium.com/after-finished-1000-leetcode-medium-level-i-found-some-patterns-dfs-77e584425474) - [📝 Coding Patterns - Dynamic Programming](https://iorilan.medium.com/after-solved-1000-leetcode-medium-level-i-found-these-patterns-dynamic-programming-205226223f4e) - [📝 Coding Patterns - Mono-Stack](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-thes-patterns-mono-stack-40ce6067abfe) - [📝 Coding Patterns - Presum, Greedy, intervals](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-these-patterns-presum-greedy-intervals-511d899bcee3) - [📝 Coding Patterns - Sliding Window, 2 Pointer, String](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-these-patterns-sliding-window-2-pointer-string-18332ca4861) - [📝 Coding Patterns - UnionFind, Devide And Conquer, Toposort](https://iorilan.medium.com/after-solved-1000-medium-leetcode-found-these-patterns-unionfind-devide-and-conquer-toposort-9210dfc90223) - [📝 Coding Patterns — Binary Search, Trie, Heap](https://medium.com/@iorilan/after-solved-1000-medium-leetcode-found-these-patterns-binary-search-trie-heap-8dc5c82e9e94) - [📝 Find Kth Largest/Smallest Element Without Sorting](https://medium.com/interviewnoodle/leetcode-find-kth-largest-smallest-element-without-sorting-77b92c75c890) - [📝 Grokking LeetCode: A Smarter Way to Prepare for Coding Interviews](https://interviewnoodle.com/grokking-leetcode-a-smarter-way-to-prepare-for-coding-interviews-e86d5c9fe4e1) - [📝 Let's implement a Bloom Filter](https://onatm.dev/2020/08/10/let-s-implement-a-bloom-filter) - [📝 Master 2D matrix/maze traversal](https://medium.com/interviewnoodle/leetcode-master-2d-matrix-maze-traversal-ec9f2e0bc300) - [📝 Recursive descent parsing](https://austinhenley.com/blog/teenytinycompiler2.html) ## Coding Interviews Build the the foundation by learning the fundamental algorithms and data structures: - Fundamental Algorithms - [ ] Sorting - [ ] Merge Sort - [ ] Quick Sort - [ ] Bucket Sort - [ ] Heap Sort - [ ] Counting Sort - [x] Searching - [x] [Binary Search](computer_science/algorithms/binary-search/binary-search.js) - [x] [Tree Depth First Search](computer_science/data_structures/binary_search_tree) - [x] [Tree Breadth First Search](computer_science/data_structures/binary_search_tree) - [ ] Graph Depth First Search - [ ] Graph Breadth First Search - [ ] Dynamic Programming - [x] [String / Array: reverse](computer_science/algorithms/reverse-string/reverse-string.js) - [x] [Linked list: insertion, deletion](computer_science/data_structures/linked_list) - Fundamental Data Structures - [x] [Stack](computer_science/data_structures/stack) - [x] [Queue](computer_science/data_structures/queue) - [x] [Linked List](computer_science/data_structures/linked_list) - [x] [Hash Map](computer_science/data_structures/hash_table) - [ ] Heap - [ ] Priority Queue - [ ] Tree - [x] [Binary Search Tree](computer_science/data_structures/binary_search_tree) - [ ] AVL Tree - [ ] Red-Black Tree - [ ] Segment Tree - [ ] Fenwick Tree (Binary Indexed Tree) - [x] [Graph](computer_science/data_structures/graph) - Time & Space Complexity - [ ] Space complexity for all algorithms / data structures - [ ] Runtime complexity for all algorithms / data structures - [ ] Make comparisons between algorithms and data structures ### Preparation - [🎥 10 Common Coding Interview Problems](https://www.youtube.com/watch?v=Peq4GCPNC5c&ab_channel=freeCodeCamp.org) - [🎥 8 Most Popular Microsoft Coding Interview Questions Solved Step by Step](https://www.youtube.com/watch?v=1P3xh7CGSU8&ab_channel=SCALER) - [🎥 Crack Your Dream Tech Interviews](https://www.youtube.com/watch?v=hm53n8tqbTo&ab_channel=Exaltitude) - [🎥 Data Structures and Algorithms in Java | Free course | Animations and Implementations](https://www.youtube.com/watch?v=6iCHf7OZn6c&list=PL6Zs6LgrJj3tDXv8a_elC6eT_4R5gfX4d&ab_channel=DineshVaryani) - [🎥 Google's Career Page - Interview Tips](https://www.youtube.com/watch?v=VXE1eBIulKg&ab_channel=JeffHSipe-PracticeInterviews) - [🎥 How to Crack The Coding Interview? | Important LeetCode Questions | Preparation Tips](https://www.youtube.com/watch?v=cM4o7_UY9vM&ab_channel=DineshVaryani) - [🎥 How To Study For Coding Interviews Efficiently](https://www.youtube.com/watch?v=2nVFdxJJdLw&ab_channel=ConnerArdman) - [🎥 Joining the Uber Eng Team - Coding Interview](https://www.youtube.com/watch?v=xxAnIoIxWGM) - [📝 3-month plan for Cracking the Coding Interview](https://medium.com/interviewnoodle/3-month-plan-for-cracking-the-coding-interview-5534f0ad7595) - [📝 Algorithm Problem Solving](./problem-solving.md) - [📝 Algorithm Template](https://docs.google.com/document/d/1TKNUaBdgzEoPaD8LNexz9JlquRKc1ZSBnNJuZmhFp4Y/edit) - [📝 Amazon's Interview Guide](https://www.linkedin.com/posts/arslanahmad_systemdesign-sde-datastructures-activity-7074384240607428608-D9AH) - [📝 Before the interview](http://blog.gainlo.co/index.php/2017/02/18/chapter-1-get-interview-google-complete-guide-google-interview-preparation) - [📝 Blind Curated 75](https://leetcode.com/list/x84cr1pj) - [📝 Brian Bi considerations](https://qr.ae/TSJE9l) - [📝 Build a Solid Foundation – The Complete Guide to Google Interview Preparation](http://blog.gainlo.co/index.php/2017/02/24/chapter-2-build-solid-foundation-complete-guide-google-interview-preparation) - [📝 Build a Solid Foundation – The Complete Guide to Google Interview Preparation](http://blog.gainlo.co/index.php/2017/02/24/chapter-2-build-solid-foundation-complete-guide-google-interview-preparation) - [📝 Coding Interview Prep Guide](https://formation.dev/guide) - [📝 Crack The Coding Interview Spreadsheet - Leetcode](https://docs.google.com/spreadsheets/d/1pnI8HmSMPcfwrCCu7wYETCXaKDig4VucZDpcjVRuYrE/edit#gid=237636947) - [📝 Deliberate practice coding interviews](https://www.linkedin.com/feed/update/urn:li:activity:7102397119537303554) - [📝 Don’t Study 500 LeetCode Problems, Do This Instead](https://medium.com/@brianjenney/dont-study-500-leetcode-problems-do-this-instead-28181ebb1eb1) - [📝 Facebook Interview Guide](https://www.linkedin.com/posts/arslanahmad_fb-meta-sde-activity-6980448214105669632-5-9e) - [📝 From Zero to Hero in Problem Solving](https://1162429.medium.com/from-zero-to-hero-in-problem-solving-c616641b5639) - [📝 Get an Interview with Google – The Complete Guide to Google Interview Preparation](http://blog.gainlo.co/index.php/2017/02/18/chapter-1-get-interview-google-complete-guide-google-interview-preparation) - [📝 Google devtip: DS & Algorithms](https://techdevguide.withgoogle.com/paths/data-structures-and-algorithms) - [📝 Google devtip: Interview Prep](https://techdevguide.withgoogle.com/paths/interview) - [📝 Google devtip: Software Engineering Principles](https://techdevguide.withgoogle.com/paths/principles) - [📝 Google Interview Guide](https://www.linkedin.com/posts/arslanahmad_google-datastructures-algorithms-activity-7076187648985350144-fYbP) - [📝 Google Interview Preparation](http://blog.gainlo.co/index.php/category/google-interview-preparation) - [📝 How I build a habit to leetcode](https://medium.com/@chuayewwee/how-i-build-a-habit-to-leetcode-23b1fdb5e0d9) - [📝 How to Land a Front-end Software Engineer job at Big Tech Companies such as Google, Facebook, and Twitter](https://javascript.plainenglish.io/how-to-land-a-software-engineer-job-in-google-facebook-and-twitter-44e49906e87) - [📝 How to study Data Structures and Algorithms while working a full-time job?](https://medium.com/@pepcoding/how-to-study-data-structures-and-algorithms-while-working-a-full-time-job-8ac21c93da5e) - [📝 knock a technical interview](https://qr.ae/TSJEkK) - [📝 Meta's Career Page - Interview Prep](https://www.metacareers.com/profile/trial/?redirect=job_details&chooseView=Hello%20World) - [📝 Microsoft's Interview Guide](https://www.linkedin.com/posts/arslanahmad_microsoft-sde-datastructures-activity-7073219389096947712-ARqi) - [📝 Must Do Easy Questions](https://leetcode.com/list/xip8yt56) - [📝 Must Do Medium Questions](https://leetcode.com/list/xineettm) - [📝 Prep by elliotbot](https://old.reddit.com/r/cscareerquestions/comments/6278bi/my_journey_and_tips_29_gpa_at_a_noname_liberal) - [📝 Programming Interview Questions](http://www.ardendertat.com/2012/01/09/programming-interview-questions) - [📝 Recruiter's view](https://qr.ae/TSJE3x) - [📝 Software Engineer interview preparation](https://www.mauriciopoppe.com/notes/misc/software-engineer-interview-preparation) - [📝 System Design](./system-design.md) - [📝 Taejun's preparation](https://qr.ae/TSJEJv) - [📝 The ultimate guide to preparing for the coding interview](https://medium.com/free-code-camp/the-ultimate-guide-to-preparing-for-the-coding-interview-183251ee36c9) ### Interview - [🎥 Google Coding Interview](https://www.youtube.com/watch?v=rw4s4M3hFfs&ab_channel=Cl%C3%A9mentMihailescu) - [📝 A “strong yes” technical interview.](https://medium.com/@paulanthonysalvatore/a-strong-yes-technical-interview-195fb851d836) - [📝 Green flags in a interview](https://qr.ae/TSJEQA) ### Platforms to learn - [Cracking the Coding Interview](coding_interviews/cracking-the-coding-interview) - [Binary Search](https://binarysearch.com) - [InterviewBit algorithms course](https://www.interviewbit.com/courses/programming) - [Leetcode Patterns](https://seanprashad.com/leetcode-patterns) - [Scaler Topics](https://www.scaler.com/topics) - [Structy](https://structy.net) - [Leetcode](coding_interviews/leetcode) - [algoexpert](coding_interviews/algoexpert) - [LabEx Interview Questions](https://labex.io/interview-questions) ### Competitive Programming - [Codeforces](competitive-programming/codeforces) - [Hacker Rank](competitive-programming/hacker-rank) - [SPOJ BR](competitive-programming/spoj-br) - [Timus](competitive-programming/timus) - [UCoder](competitive-programming/ucoder) - [URI Online Judge](competitive-programming/uri) - [UVa Online Judge](competitive-programming/uva) ## Computer Science ### Computing - [🎥 Software as Computational Media](https://www.youtube.com/watch?v=I-aGF-47hqI&ab_channel=ACMSIGPLAN) - [🎥 Tools & Craft: Andy Matuschak - Software and Computing](https://www.youtube.com/watch?v=bcrcaTuvpBk&ab_channel=Notion) ### Theory - [🎥 A Unified Theory of Garbage Collection](https://www.youtube.com/watch?v=XtUtfARSIv8&ab_channel=PapersWeLove) - [📝 Computer Organization - Performance](https://www.csie.nuk.edu.tw/~kcf/course/95_Spring/Organization/Chapter4_Performance.pdf) - [📝 Computer Organization | Performance of Computer](https://www.geeksforgeeks.org/computer-organization-performance-of-computer) ### Courses - [🎥 Intro to Theoretical Computer Science](https://classroom.udacity.com/courses/cs313) - [🎥 MIT 6.042J Mathematics for Computer Science](https://www.youtube.com/playlist?list=PLUl4u3cNGP60UlabZBeeqOuoLuj_KNphQ) - [🎥 MIT 6.006 Introduction to Algorithms](https://www.youtube.com/playlist?list=PLUl4u3cNGP63EdVPNLG3ToM6LaEUuStEY) - [🎥 MIT 6.046J Design and Analysis of Algorithms](https://www.youtube.com/playlist?list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp) ## License [MIT](/LICENSE) © [TK](https://iamtk.co) ================================================ FILE: big-o.md ================================================ # Big O | Big O Notation | Type | Computations for 10 elements | Computations for 100 elements | Computations for 1000 elements | | -------------- | ----------- | ---------------------------- | ----------------------------- | ------------------------------ | | **O(1)** | Constant | 1 | 1 | 1 | | **O(log N)** | Logarithmic | 3 | 6 | 9 | | **O(N)** | Linear | 10 | 100 | 1000 | | **O(N log N)** | n log(N) | 30 | 600 | 9000 | | **O(N^2)** | Quadratic | 100 | 10000 | 1000000 | | **O(2^N)** | Exponential | 1024 | 1.26e+29 | 1.07e+301 | | **O(N!)** | Factorial | 3628800 | 9.3e+157 | 4.02e+2567 | ### Data Structure Operations Complexity | Data Structure | Access | Search | Insertion | Deletion | | ---------------------- | :----: | :----: | :-------: | :------: | | **Array** | 1 | N | N | N | | **Stack** | N | N | 1 | 1 | | **Queue** | N | N | 1 | 1 | | **Linked List** | N | N | 1 | N | | **Hash Table** | 1 | N | N | N | | **Binary Search Tree** | N | N | N | N | ================================================ FILE: coding_interviews/README.md ================================================ # Interview Traning ## Tech Interview Preparation ### Before the interview - Referral Is The Core - Talk to some friends at this Tech companies - Resume - Concise and easy to understand - Single page - Balance between details and simplicity - Clear to anyone without relevant background and at the same time give people some ideas about the complexity - Review and feedback - Technical Questions - Draw an example: - Specific. It should use real numbers or strings (if applicable to the problem). - Sufficiently large. Most examples are too small, by about 50%. - Not a special case. Be careful. It's very easy to inadvertently draw a special case. If there's any way your example is a special case (even if you think it probably won't be a big deal), you should fix it. ### Build a Solid Foundation Some questions to have in mind: - How to do a search in a graph? What are the pros and cons of each approach? How to decide which one to use? - For a list of objects, you can use linked list, array, stack, queue and other data structures. How would you decide which one to use? What is the biggest advantage/disadvantage? - What’s the difference between dynamic programming and recursion? How do you compare a recursive solution and its iterative version? - If I want to improve my solution from O(n^2) time complexity to O(nlogn), what algorithms come to your mind? How about O(n)? ### Algorithm Design Canvas #### Constraints - Constraints: Strings, Arrays, Numbers - range of values: min and max values for any key value - How many elements can be in the array? - How large can each element be? If it’s a string, how long? If it’s a number, what is the minimum and maximum value? - What is in each element? If it’s a number, is it an integer or a floating point? If it’s a string, is it single-byte or multibyte (unicode)? - If the problem involves finding a subsequence, does “subsequence” mean that the elements must be adjacent, or is there no such requirement? - Does the array contain unique numbers or can they be repeated (this is sometimes relevant)? - Constraints: Grids/Mazes - For problems where some actor (e.g. a robot) is moving in a grid or maze, what moves are allowed? Can the robot move diagonally (hence 8 valid moves), or only horizontally/vertically (hence only 4 valid moves)? - Are all cells in the grid allowed, or can there be obstacles? - If the actor is trying to get from cell A to cell B, are cells A and B guaranteed to be different from each other? - If the actor is trying to get from cell A to cell B, is it guaranteed that there’s a path between the two cells? - Constraints: Graphs - How many nodes can the graph have? - How many edges can the graph have? - If the edges have weights, what is the range for the weights? - Can there be loops in the graph? Can there be negative-sum loops in the graph? - Is the graph directed or undirected? - Does the graph have multiple edges and/or self-loops? - Constraints: Return Values - What should my method return? For example, if I’m trying to find the longest subsequence of increasing numbers in an array, should I return the length, the start index, or both? - If there are multiple solutions to the problem, which one should be returned? - If it should return multiple values, do you have any preference on what to return? E.g. should it return an object, a tuple, an array, or pass the output parameters as input references? (This may not be applicable in languages allowing you to return multiple values, e.g. Python) - What should I do/return if the input is invalid / does not match the constraints? Options may be to do nothing (always assume the input is correct), raise an exception, or return some specific value. - In problems where you’re supposed to find something (e.g. a number in an array), what should be returned if the element is not present? ### Things to know when stuck - Always consider hash tables (dictionaries) with their O(1)-ness. ("Tip: using a dictionary is the most common way to get from a brute force approach to something more clever. It should always be your first thought.") - If at all array-related, try sorting first. - If search-related, consider binary search. - Start with a brute force solution, look for repeat work in that solution, and modify it to only do that work once. Space-time trade-off! That is, for better time complexity, try using auxiliary data structures. E.g., do something in a single pass over an array—O(N) time—by using a hash table—O(N) space—vs. doing something in multiple passes—O(N ^ 2)—without using any extra space—O(1). What information can I store to save time? (Another example: O(1) get_max method for a Stack class stores extra information (the max at and below each element) to save time (instead of iterating through the stack O(N)).) - Try a greedy solution: Iterate through the problem space taking the optimal solution "so far" until the end. (Optimal if the problem has "optimal substructure," which means stitching together optimal solutions to subproblems yields an optimal solution.) - Remember that I can use two pointers (e.g., to get the midpoint by having one pointer go twice as fast, or in a sum problem by having the pointers work inward from either end, or to test if a string is a palindrome). - If the problem involves parsing or tree/graph traversal (or reversal in some way), consider using a stack. - Does solving the problem for size (N – 1) make solving it for size N any easier? If so, try to solve recursively and/or with dynamic programming. (Using the max/min function can help a lot in recursive or dynamic programming problems.) - A lot of problems can be treated as graph problems and/or use breadth-first or depth-first traversal. - If you have a lot of strings, try putting them in a prefix tree / trie. - Any time you repeatedly have to take the min or max of a dynamic collection, think heaps. (If you don’t need to insert random elements, prefer a sorted array.) ### Common problems and approaches - subsequence - consecutive sequence vs non-consecutive sequence - consecutive sequence: [1, 2, 3] is the consecutive sequence of [1, 2, 3, 4, 5] - non-consecutive sequence: [1, 3, 5] is the non-consecutive sequence of [1, 2, 3, 4, 5] - binary search - [problem](/coding_interviews/leetcode/easy/guess-number-higher-or-lower/guess-number-higher-or-lower.js) ================================================ FILE: coding_interviews/algoexpert/README.md ================================================ # AlgoExpert ================================================ FILE: coding_interviews/algoexpert/array-of-products/array-of-products-optimized.js ================================================ /** * * Write a function that takes in a non-empty array of integers and returns * an array of the same length, where each element in the output array is * equal to the product of every other number in the input array. * In other words, the value at output[i] is equal to the product of * every number in the input array other than input[i]. * Note that you're expected to solve this problem without using division. * * Input: array = [5, 1, 4, 2] * Output: [8, 40, 10, 20] */ // Runtime: O(N), N = length of array // Space: O(N) function initOutput(length) { let output = []; while (length--) { output.push(1); } return output; } function arrayOfProducts(array) { let left = 1; let right = 1; let length = array.length; let output = initOutput(length); for (let index = 0; index < length; index++) { output[index] *= left; output[length - index - 1] *= right; left *= array[index]; right *= array[length - index - 1]; } return output; } ================================================ FILE: coding_interviews/algoexpert/array-of-products/array-of-products.js ================================================ /** * * Write a function that takes in a non-empty array of integers and returns * an array of the same length, where each element in the output array is * equal to the product of every other number in the input array. * In other words, the value at output[i] is equal to the product of * every number in the input array other than input[i]. * Note that you're expected to solve this problem without using division. * * Input: array = [5, 1, 4, 2] * Output: [8, 40, 10, 20] */ // Runtime: O(N^2), N = length of array // Space: O(N) function initOutput(length) { let output = []; while (length--) { output.push(1); } return output; } function arrayOfProducts(array) { let output = initOutput(array.length); for (let index = 0; index < array.length; index++) { for (let outputIndex = 0; outputIndex < output.length; outputIndex++) { if (index !== outputIndex) { output[outputIndex] *= array[index]; } } } return output; } ================================================ FILE: coding_interviews/algoexpert/best-seat/best-seat.js ================================================ /** * You walk into a theatre you're about to see a show in. The usher within * the theatre walks you to your row and mentions you're allowed to sit * anywhere within the given row. Naturally you'd like to sit in the seat * that gives you the most space. You also would prefer this space to be * evenly distributed on either side of you (e.g. if there are three empty * seats in a row, you would prefer to sit in the middle of those three seats). * Given the theatre row represented as an integer array, return the seat * index of where you should sit. Ones represent occupied seats and zeroes * represent empty seats. * * You may assume that someone is always sitting in the first and last seat * of the row. Whenever there are two equally good seats, you should sit in * the seat with the lower index. If there is no seat to sit in, return -1. * The given array will always have a length of at least one and contain only * ones and zeroes. * * Input: seats = [1, 0, 1, 0, 0, 0, 1] * Output: 4 */ // Runtime: O(N), N = seats length // Space: O(1) function bestSeat(seats) { let sequenceIndex; let sequenceIndexTemp; let sequenceLength = 0; let maxSequenceLength = 0; for (let index = 1; index < seats.length; index++) { let seat = seats[index]; if (seat === 0) { sequenceLength++; if (!sequenceIndexTemp) { sequenceIndexTemp = index; } } else { if (sequenceLength > maxSequenceLength) { maxSequenceLength = sequenceLength; sequenceIndex = sequenceIndexTemp; } sequenceLength = 0; sequenceIndexTemp = undefined; } } if (maxSequenceLength <= 0) { return -1; } return maxSequenceLength % 2 === 0 ? sequenceIndex + Math.floor(maxSequenceLength / 2) - 1 : sequenceIndex + Math.floor(maxSequenceLength / 2); } ================================================ FILE: coding_interviews/algoexpert/binary-search/binary-search.js ================================================ // Runtime: O(logN) // Space: O(1) function binarySearch(array, target) { let start = 0; let end = array.length - 1; let middle = Math.floor((start + end) / 2); while (start <= end) { let num = array[middle]; if (num === target) { return middle; } if (num > target) { end = middle - 1; } if (num < target) { start = middle + 1; } middle = Math.floor((start + end) / 2); } return -1; } ================================================ FILE: coding_interviews/algoexpert/branch-sums/branch-sums-without-recreating-sums.js ================================================ // Runtime: O(N), N = number of nodes // Space: list of branch sums (number of leaf nodes) is O(N) and recursive algorithm (call stack) is log(N) class BinaryTree { constructor(value) { this.value = value; this.left = null; this.right = null; } } function branchSums(root) { let sums = []; const recursiveBranchSums = (node, sum) => { if (!node) return; let newSum = sum + node.value; if (!node.left && !node.right) return sums.push(newSum); recursiveBranchSums(node.left, newSum); recursiveBranchSums(node.right, newSum); }; recursiveBranchSums(root, 0); return sums; } ================================================ FILE: coding_interviews/algoexpert/branch-sums/branch-sums.js ================================================ // Runtime: O(N), N = number of nodes // Space: list of branch sums (number of leaf nodes) is O(N) and recursive algorithm (call stack) is log(N) class BinaryTree { constructor(value) { this.value = value; this.left = null; this.right = null; } } function branchSums(root, sum = 0, sums = []) { if (!root) return sums; if (!root.left && !root.right) return [...sums, sum + root.value]; let newSum = sum + root.value; let leftBranch = branchSums(root.left, newSum, sums); let rightBranch = branchSums(root.right, newSum, sums); return [...leftBranch, ...rightBranch]; } ================================================ FILE: coding_interviews/algoexpert/bst-construction/bst-construction.js ================================================ /** BST Construction Write a BST class for a Binary Search Tree. The class should support: Inserting values with the insert method. Removing values with the remove method; this method should only remove the first instance of a given value. Searching for values with the contains method. Note that you can't remove values from a single-node tree. In other words, calling the remove method on a single-node tree should simply not do anything. Each BST node has an integer value, a left child node, and a right child node. A node is said to be a valid BST node if and only if it satisfies the BST property: its value is strictly greater than the values of every node to its left; its value is less than or equal to the values of every node to its right; and its children nodes are either valid BST nodes themselves or None / null. */ class BST { constructor(value) { this.value = value; this.left = null; this.right = null; } insert(value) { if (value < this.value) { if (this.left) this.left.insert(value); else this.left = new BST(value); } else { if (this.right) this.right.insert(value); else this.right = new BST(value); } return this; } contains(value) { if (this.value === value) { return true; } if (value < this.value) { return this.left ? this.left.contains(value) : false; } if (value >= this.value) { return this.right ? this.right.contains(value) : false; } return false; } remove(value, parent = null) { if (parent === null && this.left === null && this.right === null) return; if (value === this.value) { // when the node has children: // get the smallest node from the right subtree and replace the removed node with this one if (this.left && this.right) { let smallestNodeValue = this.right._findSmallestNodeValue(); this.right.remove(smallestNodeValue, this); this.value = smallestNodeValue; return this; } // when the node to be removed is a leaf node: just remove it if (!this.left && !this.right) { if (parent.left === this) parent.left = null; if (parent.right === this) parent.right = null; } // when the node to be removed only has one child node: point child node to the parent if (this.left) { let greatestNodeValue = this.left._findGreatestNodeValue(); this.value = greatestNodeValue; this.left.remove(greatestNodeValue, this); } // when the node to be removed only has one child node: point child node to the parent if (this.right) { let smallestNodeValue = this.right._findSmallestNodeValue(); this.value = smallestNodeValue; this.right.remove(smallestNodeValue, this); } } if (value < this.value) { if (this.left) { this.left.remove(value, this); } } if (value >= this.value) { if (this.right) { this.right.remove(value, this); } } return this; } _findSmallestNodeValue() { return this.left ? this.left._findSmallestNodeValue() : this.value; } _findGreatestNodeValue() { return this.right ? this.right._findGreatestNodeValue() : this.value; } } ================================================ FILE: coding_interviews/algoexpert/bst-traversal/bst-traversal.js ================================================ function inOrderTraverse(tree, array) { if (!tree) return; inOrderTraverse(tree.left, array); array.push(tree.value); inOrderTraverse(tree.right, array); return array; } function preOrderTraverse(tree, array) { if (!tree) return; array.push(tree.value); preOrderTraverse(tree.left, array); preOrderTraverse(tree.right, array); return array; } function postOrderTraverse(tree, array) { if (!tree) return; postOrderTraverse(tree.left, array); postOrderTraverse(tree.right, array); array.push(tree.value); return array; } ================================================ FILE: coding_interviews/algoexpert/bubble-sort/bubble-sort.js ================================================ // Runtime: O(N^2) // Space: O(1) function bubbleSort(array) { let sorted = false; while (!sorted) { sorted = true; for (let index = 0; index < array.length - 1; index++) { if (array[index] > array[index + 1]) { let aux = array[index]; array[index] = array[index + 1]; array[index + 1] = aux; sorted = false; } } } return array; } ================================================ FILE: coding_interviews/algoexpert/caesar-cipher-encryptor/caesar-cipher-encryptor.js ================================================ // Runtime: O(N), N = number of characters // Space: O(N) function getChar(char, key) { let charCode = ((char.charCodeAt() - 97 + key) % 26) + 97; return String.fromCharCode(charCode); } function caesarCipherEncryptor(string, key) { return [...string].map((char) => getChar(char, key)).join(''); } ================================================ FILE: coding_interviews/algoexpert/class-photos/class-photos.js ================================================ function classPhotos(redShirtHeights, blueShirtHeights) { redShirtHeights.sort((a, b) => a - b); blueShirtHeights.sort((a, b) => a - b); let backRow; let frontRow; if (redShirtHeights[0] < blueShirtHeights[0]) { backRow = blueShirtHeights; frontRow = redShirtHeights; } else { backRow = redShirtHeights; frontRow = blueShirtHeights; } for (let index = 0; index < backRow.length; index++) { if (frontRow[index] >= backRow[index]) return false; } return true; } ================================================ FILE: coding_interviews/algoexpert/common-characters/common-characters.js ================================================ // Runtime: (N * M), N = number of strings and M = length of biggest string // Space: (M), M = length of biggest string /** * Write a function that takes in a non-empty list of non-empty strings and returns * a list of characters that are common to all strings in the list, ignoring multiplicity. * Note that the strings are not guaranteed to only contain alphanumeric characters. * The list you return can be in any order. * * Input: * strings = ["abc", "bcd", "cbaccd"] * * Output: * ["b", "c"] // The characters could be ordered differently. */ function commonCharacters(strings) { let map = new Map(); let result = []; for (let string of strings) { let set = new Set(string); for (let char of set) { map.set(char, map.get(char) + 1 || 1); } } for (let [char, count] of map) { if (count === strings.length) { result.push(char); } } return result; } ================================================ FILE: coding_interviews/algoexpert/depth-first-search/depth-first-search-cleaner.js ================================================ // Runtime: O(V + E), V = vertices, E = edges // Space: O(V), V = vertices class Node { constructor(name) { this.name = name; this.children = []; } addChild(name) { this.children.push(new Node(name)); return this; } depthFirstSearch(array) { array.push(this.name); for (let child of this.children) { child.depthFirstSearch(array); } return array; } } ================================================ FILE: coding_interviews/algoexpert/depth-first-search/depth-first-search.js ================================================ // Runtime: O(V + E), V = vertices, E = edges // Space: O(V), V = vertices class Node { constructor(name) { this.name = name; this.children = []; } addChild(name) { this.children.push(new Node(name)); return this; } depthFirstSearch(array) { let queue = [this]; while (queue.length) { let node = queue.shift(); array.push(node.name); for (let child of node.children) { child.depthFirstSearch(array); } } return array; } } ================================================ FILE: coding_interviews/algoexpert/evaluate-expression-tree/evaluate-expression-tree-cleaner.js ================================================ function evaluateExpressionTree({value, left, right}) { if (value === -1) return evaluateExpressionTree(left) + evaluateExpressionTree(right); if (value === -2) return evaluateExpressionTree(left) - evaluateExpressionTree(right); if (value === -3) return Math.trunc(evaluateExpressionTree(left) / evaluateExpressionTree(right)); if (value === -4) return evaluateExpressionTree(left) * evaluateExpressionTree(right); return value; } ================================================ FILE: coding_interviews/algoexpert/evaluate-expression-tree/evaluate-expression-tree-with-trunc.js ================================================ function evaluateExpressionTree(tree) { if (!tree) return null; let leftValue = evaluateExpressionTree(tree.left); let rightValue = evaluateExpressionTree(tree.right); if (!leftValue && !rightValue) return tree.value; if (tree.value === -1) return leftValue + rightValue; if (tree.value === -2) return leftValue - rightValue; if (tree.value === -3) return Math.trunc(leftValue / rightValue); if (tree.value === -4) return leftValue * rightValue; } ================================================ FILE: coding_interviews/algoexpert/evaluate-expression-tree/evaluate-expression-tree.js ================================================ function evaluateExpressionTree(tree) { if (!tree) return null; let leftValue = evaluateExpressionTree(tree.left); let rightValue = evaluateExpressionTree(tree.right); if (!leftValue && !rightValue) return tree.value; if (tree.value === -1) return leftValue + rightValue; if (tree.value === -2) return leftValue - rightValue; if (tree.value === -3) { let value = leftValue / rightValue; return Math.sign(value) * Math.floor(Math.abs(value)); } if (tree.value === -4) return leftValue * rightValue; } ================================================ FILE: coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst-optimized-cleaner.js ================================================ // Runtime // - average: O(logN), where N = number of nodes in the tree // - worst case: O(N), where N = number of nodes in the tree // Space: O(1) function abs(value) { return Math.abs(value); } function findClosestValueInBst(tree, target, closest = Infinity) { if (!tree) { return closest; } if (abs(tree.value - target) < abs(closest - target)) { closest = tree.value; } if (target === tree.value) { return closest; } if (target < tree.value) { return findClosestValueInBst(tree.left, target, closest); } return findClosestValueInBst(tree.right, target, closest); } ================================================ FILE: coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst-optimized.js ================================================ // Runtime // - average: O(logN), where N = number of nodes in the tree // - worst case: O(N), where N = number of nodes in the tree // Space: O(1) function findClosestValueInBst(tree, target, closestValue = Infinity) { if (!tree) { return closestValue; } if (tree.value === target) { return target; } let currentDiff = Math.abs(tree.value - target); let diff = Math.abs(closestValue - target); let newClosestValue = currentDiff <= diff ? tree.value : closestValue; let leftValue = target < tree.value ? findClosestValueInBst(tree.left, target, newClosestValue) : newClosestValue; let rightValue = target > tree.value ? findClosestValueInBst(tree.right, target, newClosestValue) : newClosestValue; let leftDiff = Math.abs(leftValue - target); let rightDiff = Math.abs(rightValue - target); if (currentDiff <= leftDiff && currentDiff <= rightDiff) { return tree.value; } else if (leftDiff <= rightDiff) { return leftValue; } return rightValue; } ================================================ FILE: coding_interviews/algoexpert/find-closest-value-in-bst/find-closest-value-in-bst.js ================================================ // Runtime: O(N), where N = number of nodes in the tree // Space: O(1) function findClosestValueInBst(tree, target, closestValue = Infinity) { if (!tree) { return closestValue; } let currentDiff = Math.abs(tree.value - target); let diff = Math.abs(closestValue - target); let leftValue = findClosestValueInBst( tree.left, target, currentDiff <= diff ? tree.value : closestValue ); let rightValue = findClosestValueInBst( tree.right, target, currentDiff <= diff ? tree.value : closestValue ); let leftDiff = Math.abs(leftValue - target); let rightDiff = Math.abs(rightValue - target); if (currentDiff <= leftDiff && currentDiff <= rightDiff) { return tree.value; } else if (leftDiff <= rightDiff) { return leftValue; } return rightValue; } ================================================ FILE: coding_interviews/algoexpert/find-three-largest-numbers/find-three-largest-numbers.js ================================================ // Runtime: O(N), N = number of numbers in the array // Space: O(1) function findThreeLargestNumbers(array) { let first = -Infinity; let second = -Infinity; let third = -Infinity; for (let num of array) { if (num > first) { third = second; second = first; first = num; } else if (num > second) { third = second; second = num; } else if (num > third) { third = num; } } return [third, second, first]; } ================================================ FILE: coding_interviews/algoexpert/first-duplicate-value/first-duplicate-value-optimized.js ================================================ /** * Given an array of integers between 1 and n, inclusive, where n is the length of * the array, write a function that returns the first integer that appears more * than once (when the array is read from left to right). * In other words, out of all the integers that might occur more than once in the * input array, your function should return the one whose first duplicate * value has the minimum index. * If no integer appears more than once, your function should return -1. * Note that you're allowed to mutate the input array. * * Input: array = [2, 1, 5, 2, 3, 3, 4] * Output: 2 */ // Runtime: O(N), N = array length // Space: O(1) function firstDuplicateValue(array) { for (let index = 0; index < array.length; index++) { let newIndex = Math.abs(array[index]) - 1; if (array[newIndex] < 0) { return Math.abs(array[index]); } array[newIndex] = array[newIndex] * -1; } return -1; } ================================================ FILE: coding_interviews/algoexpert/first-duplicate-value/first-duplicate-value.js ================================================ /** * Given an array of integers between 1 and n, inclusive, where n is the length of * the array, write a function that returns the first integer that appears more * than once (when the array is read from left to right). * In other words, out of all the integers that might occur more than once in the * input array, your function should return the one whose first duplicate * value has the minimum index. * If no integer appears more than once, your function should return -1. * Note that you're allowed to mutate the input array. * * Input: array = [2, 1, 5, 2, 3, 3, 4] * Output: 2 */ // Runtime: O(N), N = array length // Space: O(N) function firstDuplicateValue(array) { let map = new Map(); for (let num of array) { map.set(num, map.get(num) + 1 || 1); if (map.get(num) > 1) { return num; } } return -1; } ================================================ FILE: coding_interviews/algoexpert/first-non-repeating-character/first-non-repeating-character.js ================================================ // Runtime: O(N), N = string length // Space: O(N) function firstNonRepeatingCharacter(string) { let map = new Map(); for (let char of string) { map.set(char, map.get(char) + 1 || 1); } for (let index = 0; index < string.length; index++) { if (map.get(string[index]) <= 1) return index; } return -1; } ================================================ FILE: coding_interviews/algoexpert/generate-document/generate-document.js ================================================ /** * * You're given a string of available characters and a string representing a document that you need to generate. * Write a function that determines if you can generate the document using the available characters. * If you can generate the document, your function should return true; otherwise, it should return false. * You're only able to generate the document if the frequency of unique characters in the characters string * is greater than or equal to the frequency of unique characters in the document string. * For example, if you're given characters = "abcabc" and document = "aabbccc" you cannot generate * the document because you're missing one c. * The document that you need to create may contain any characters, including special characters, * capital letters, numbers, and spaces. * Note: you can always generate the empty string (""). * * Input: * characters = "Bste!hetsi ogEAxpelrt x " * document = "AlgoExpert is the Best!" * * Output: * true */ function generateDocument(characters, document) { let map = new Map(); for (let char of characters) { map.set(char, map.get(char) + 1 || 1); } for (let char of document) { if (map.has(char) && map.get(char) > 0) { map.set(char, map.get(char) - 1); } else { return false; } } return true; } ================================================ FILE: coding_interviews/algoexpert/insertion-sort/insertion-sort.js ================================================ // Runtime: O(N^2) // Space: O(1) function swap(array, i, j) { let aux = array[i]; array[i] = array[j]; array[j] = aux; } function insertionSort(array) { for (let index = 0; index < array.length; index++) { let toSwapIndex = index; while (toSwapIndex > 0 && array[toSwapIndex] < array[toSwapIndex - 1]) { swap(array, toSwapIndex, toSwapIndex - 1); toSwapIndex -= 1; } } return array; } ================================================ FILE: coding_interviews/algoexpert/longest-peak/longest-peak.js ================================================ /** * Write a function that takes in an array of integers and returns * the length of the longest peak in the array. * A peak is defined as adjacent integers in the array that are * strictly increasing until they reach a tip (the highest value in * the peak), at which point they become strictly decreasing. * At least three integers are required to form a peak. * For example, the integers 1, 4, 10, 2 form a peak, but the * integers 4, 0, 10 don't and neither do the integers 1, 2, 2, 0. * Similarly, the integers 1, 2, 3 don't form a peak because there * aren't any strictly decreasing integers after the 3. * * Input: array = [1, 2, 3, 3, 4, 0, 10, 6, 5, -1, -3, 2, 3] * Output: 6 // 0, 10, 6, 5, -1, -3 */ // Runtime: O(N), N = array length // Space: O(1) function longestPeak(array) { let longestPeak = 0; let leftEdge; let rightEdge; for (let peakIndex = 1; peakIndex < array.length - 1; peakIndex++) { if ( array[peakIndex] > array[peakIndex - 1] && array[peakIndex] > array[peakIndex + 1] ) { for (let index = peakIndex; index > 0; index--) { if (array[index - 1] < array[index]) { leftEdge = index - 1; } else { break; } } for (let index = peakIndex; index < array.length - 1; index++) { if (array[index] > array[index + 1]) { rightEdge = index + 1; } else { break; } } longestPeak = Math.max(longestPeak, rightEdge - leftEdge + 1); } } return longestPeak; } ================================================ FILE: coding_interviews/algoexpert/majority-element/majority-element.js ================================================ // Runtime: O(N^2) // Space: O(N) function majorityElement(array) { let half = Math.floor(array.length / 2); if (array.length <= 1) return array[0]; for (let i = 0; i < array.length; i++) { let count = 1; let number = array[i]; for (let k = i + 1; k < array.length; k++) { if (array[k] === number) { count++; } if (count > half) { return number; } } } } ================================================ FILE: coding_interviews/algoexpert/merge-overlapping-intervals/merge-overlapping-intervals.js ================================================ /** * Write a function that takes in a non-empty array of arbitrary intervals, * merges any overlapping intervals, and returns the new intervals in no * particular order. * Each interval interval is an array of two integers, with interval[0] as * the start of the interval and interval[1] as the end of the interval. * Note that back-to-back intervals aren't considered to be overlapping. * For example, [1, 5] and [6, 7] aren't overlapping; however, [1, 6] and * [6, 7] are indeed overlapping. * Also note that the start of any particular interval will always be * less than or equal to the end of that interval. * * Input: intervals = [[1, 2], [3, 5], [4, 7], [6, 8], [9, 10]] * Output: [[1, 2], [3, 8], [9, 10]] */ // Runtime: O(NlogN), N = array length // Space: O(N) function mergeOverlappingIntervals(array) { if (array.length <= 1) return array; array.sort((a, b) => a[0] - b[0]); let intervals = []; let current = array[0]; for (let index = 1; index < array.length; index++) { let next = array[index]; if (current[1] >= next[0]) { current = [current[0], Math.max(current[1], next[1])]; } else { intervals.push(current); current = next; } if (index === array.length - 1) { intervals.push(current); } } return intervals; } ================================================ FILE: coding_interviews/algoexpert/middle-node/middle-node-slow-fast.js ================================================ // Runtime: O(N), N = number of nodes in the linked list // Space: O(1) function middleNode(linkedList) { let fast = linkedList; let slow = linkedList; while (fast && fast.next) { fast = fast.next.next; slow = slow.next; } return slow; } ================================================ FILE: coding_interviews/algoexpert/middle-node/middle-node.js ================================================ // Runtime: O(N), N = number of nodes in the linked list // Space: O(1) function middleNode(linkedList) { let length = 0; let node = linkedList; while (linkedList) { linkedList = linkedList.next; length++; } let middle = Math.floor(length / 2); let index = 0; while (node) { if (index === middle) { return node; } node = node.next; index++; } } ================================================ FILE: coding_interviews/algoexpert/minimum-waiting-time/minimum-waiting-time.js ================================================ function minimumWaitingTime(queries) { let waitingTime = 0; let previous = 0; queries.sort((a, b) => a - b); for (let query of queries) { waitingTime += previous; previous += query; } return waitingTime; } ================================================ FILE: coding_interviews/algoexpert/missing-numbers/missing-numbers.js ================================================ // Runtime: O(N) // Space: O(N) function missingNumbers(nums) { let numbers = []; for (let index = 0; index < nums.length + 2; index++) { numbers.push(index + 1); } for (let num of nums) { numbers[num - 1] = 0; } let result = []; for (let num of numbers) { if (num) result.push(num); } return result; } ================================================ FILE: coding_interviews/algoexpert/monotonic-array/monotonic-array-optimization-1.js ================================================ /** * Write a function that takes in an array of integers and returns a boolean * representing whether the array is monotonic. * An array is said to be monotonic if its elements, from left to right, are * entirely non-increasing or entirely non-decreasing. * Non-increasing elements aren't necessarily exclusively decreasing; they * simply don't increase. Similarly, non-decreasing elements aren't necessarily * exclusively increasing; they simply don't decrease. * Note that empty arrays and arrays of one element are monotonic. * * Input: * array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001] * * Output: * true */ // Runtime: O(N), N = array length // Space: O(1) function isMonotonic(array) { let num = array[0]; let upward; for (let index = 1; index < array.length; index++) { if (upward === undefined) { upward = array[index] !== num ? array[index] > num : undefined; } if (upward !== undefined && upward && array[index] < num) { return false; } if (upward !== undefined && !upward && array[index] > num) { return false; } num = array[index]; } return true; } ================================================ FILE: coding_interviews/algoexpert/monotonic-array/monotonic-array-optimization-2.js ================================================ /** * Write a function that takes in an array of integers and returns a boolean * representing whether the array is monotonic. * An array is said to be monotonic if its elements, from left to right, are * entirely non-increasing or entirely non-decreasing. * Non-increasing elements aren't necessarily exclusively decreasing; they * simply don't increase. Similarly, non-decreasing elements aren't necessarily * exclusively increasing; they simply don't decrease. * Note that empty arrays and arrays of one element are monotonic. * * Input: * array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001] * * Output: * true */ // Runtime: O(N), N = array length // Space: O(1) function isMonotonic(array) { let isNonDecreasing = true; let isNonIncreasing = true; for (let index = 0; index < array.length - 1; index++) { if (array[index] > array[index + 1]) isNonDecreasing = false; if (array[index] < array[index + 1]) isNonIncreasing = false; } return isNonDecreasing || isNonIncreasing; } ================================================ FILE: coding_interviews/algoexpert/monotonic-array/monotonic-array.js ================================================ /** * Write a function that takes in an array of integers and returns a boolean * representing whether the array is monotonic. * An array is said to be monotonic if its elements, from left to right, are * entirely non-increasing or entirely non-decreasing. * Non-increasing elements aren't necessarily exclusively decreasing; they * simply don't increase. Similarly, non-decreasing elements aren't necessarily * exclusively increasing; they simply don't decrease. * Note that empty arrays and arrays of one element are monotonic. * * Input: * array = [-1, -5, -10, -1100, -1100, -1101, -1102, -9001] * * Output: * true */ // Runtime: O(N), N = array length // Space: O(1) function isNonIncreasing(array) { let num = array[0]; for (let index = 1; index < array.length; index++) { if (array[index] > num) { return false; } num = array[index]; } return true; } function isNonDecreasing(array) { let num = array[0]; for (let index = 1; index < array.length; index++) { if (array[index] < num) { return false; } num = array[index]; } return true; } function isMonotonic(array) { return isNonIncreasing(array) || isNonDecreasing(array); } ================================================ FILE: coding_interviews/algoexpert/move-element-to-end/move-element-to-end.js ================================================ /** * You're given an array of integers and an integer. Write a function that * moves all instances of that integer in the array to the end of the * array and returns the array. * The function should perform this in place (i.e., it should mutate the input array) * and doesn't need to maintain the order of the other integers. * * Input: * array = [2, 1, 2, 2, 2, 3, 4, 2] * toMove = 2 * * Output: * [1, 3, 4, 2, 2, 2, 2, 2] */ // Runtime: O(2N) = O(N), where N = array length // Space: O(1) function moveElementToEnd(array, toMove) { let pointer = 0; for (let index = 0; index < array.length; index++) { if (array[index] !== toMove) { array[pointer] = array[index]; pointer++; } } for (let index = pointer; index < array.length; index++) { array[index] = toMove; } return array; } ================================================ FILE: coding_interviews/algoexpert/node-depths/node-depths.js ================================================ // Runtime: O(N), N = number of nodes // Space: O(H), H = height of the tree function nodeDepths(root, sum = 0) { if (!root) return 0; return sum + nodeDepths(root.left, sum + 1) + nodeDepths(root.right, sum + 1); } ================================================ FILE: coding_interviews/algoexpert/non-constructible-change/non-constructible-change.js ================================================ // Runtime: O(nlogn) // Space: O(1) function nonConstructibleChange(coins) { coins.sort((a, b) => a - b); let currentChangeCreated = 0; for (let coin of coins) { if (coin > currentChangeCreated + 1) { return currentChangeCreated + 1; } currentChangeCreated += coin; } return currentChangeCreated + 1; } ================================================ FILE: coding_interviews/algoexpert/nth-fibonacci/nth-fibonacci-memo-no-space.js ================================================ // Runtime: O(N) // Space: O(1) function getNthFib(n) { if (n === 1) return 0; if (n === 2) return 1; let first = 0; let second = 1; for (let num = 3; num <= n; num++) { let sum = first + second; first = second; second = sum; } return second; } ================================================ FILE: coding_interviews/algoexpert/nth-fibonacci/nth-fibonacci-memo.js ================================================ // Runtime: O(N) // Space: O(N) function getNthFib(n) { if (n === 1) return 0; if (n === 2) return 1; let memo = [0, 0, 1]; let result; for (let num = 3; num <= n; num++) { result = memo[num - 1] + memo[num - 2]; memo.push(result); } return result; } ================================================ FILE: coding_interviews/algoexpert/nth-fibonacci/nth-fibonacci.js ================================================ // Runtime: O(2^N) // Space: O(N) function getNthFib(n) { if (n === 0) return 0; if (n === 1) return 0; if (n === 2) return 1; return getNthFib(n - 1) + getNthFib(n - 2); } ================================================ FILE: coding_interviews/algoexpert/optimal-freelancing/optimal-freelancing-sorting.js ================================================ function sortJobs(jobs) { jobs.sort((job1, job2) => { if (job1.payment > job2.payment) return -1; if (job1.payment < job2.payment) return 1; return 0; }); } function optimalFreelancing(jobs) { let profit = 0; let days = [0, 0, 0, 0, 0, 0, 0]; sortJobs(jobs); for (let { deadline, payment } of jobs) { let maxTime = Math.min(deadline, 7); for (let time = maxTime; time >= 1; time--) { if (days[time - 1] === 0) { profit += payment; days[time - 1] = payment; break; } } } return profit; } ================================================ FILE: coding_interviews/algoexpert/optimal-freelancing/optimal-freelancing.js ================================================ function optimalFreelancing(jobs) { let profit = 0; let day = 7; let completedJobs = new WeakSet(); while (day > 0) { let bestJob; for (let job of jobs) { if ( job.deadline >= day && job.payment > (bestJob?.payment || 0) && !completedJobs.has(job) ) { bestJob = job; } } day--; if (bestJob) { completedJobs.add(bestJob); profit += bestJob.payment; } } return profit; } ================================================ FILE: coding_interviews/algoexpert/palindrome-check/palindrome-check.js ================================================ // Runtime: O(N), N = characters in the string // Space: O(1) function isPalindrome(string) { let start = 0; let end = string.length - 1; let middle = Math.floor((start + end) / 2); while (start <= middle && end >= middle) { if (string[start] !== string[end]) { return false; } start++; end--; } return true; } ================================================ FILE: coding_interviews/algoexpert/product-sum/product-sum-timer-later.js ================================================ // Runtime: O(N), N = all numbers including the numbers inside nested arrays // Space: O(D), D = the depth of the nested arrays function productSum(array, depth = 1) { let sum = 0; for (let num of array) { if (Array.isArray(num)) { sum += productSum(num, depth + 1); } else { sum += num; } } return sum * depth; } ================================================ FILE: coding_interviews/algoexpert/product-sum/product-sum.js ================================================ // Runtime: O(N), N = all numbers including the numbers inside nested arrays // Space: O(D), D = the depth of the nested arrays function productSum(array, product = 1) { let sum = 0; for (let num of array) { if (Array.isArray(num)) { sum += productSum(num, product + 1) * product; } else { sum += num * product; } } return sum; } ================================================ FILE: coding_interviews/algoexpert/remove-duplicates-from-linked-list/remove-duplicates-from-linked-list.js ================================================ // Runtime: O(N), N = number of nodes in the linked list // Space: O(1) function removeDuplicatesFromLinkedList(linkedList) { let head = linkedList; while (linkedList) { let next = linkedList.next; while (next && linkedList.value === next.value) { next = next.next; } linkedList.next = next; linkedList = next; } return head; } ================================================ FILE: coding_interviews/algoexpert/remove-islands/remove-islands-optimized.js ================================================ /** You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only 0s and 1s. The matrix represents a two-toned image, where each 1 represents black and each 0 represents white. An island is defined as any number of 1s that are horizontally or vertically adjacent (but not diagonally adjacent) and that don't touch the border of the image. In other words, a group of horizontally or vertically adjacent 1s isn't an island if any of those 1s are in the first row, last row, first column, or last column of the input matrix. Note that an island can twist. In other words, it doesn't have to be a straight vertical line or a straight horizontal line; it can be L-shaped, for example. You can think of islands as patches of black that don't touch the border of the two-toned image. Write a function that returns a modified version of the input matrix, where all of the islands are removed. You remove an island by replacing it with 0s. Naturally, you're allowed to mutate the input matrix. */ function markNonIsland(matrix, rowIndex, colIndex) { if ( rowIndex < 0 || rowIndex >= matrix.length || colIndex < 0 || colIndex >= matrix[rowIndex].length || [0, 2].includes(matrix[rowIndex][colIndex]) ) { return; } matrix[rowIndex][colIndex] = 2; markNonIsland(matrix, rowIndex - 1, colIndex); // top markNonIsland(matrix, rowIndex + 1, colIndex); // bottom markNonIsland(matrix, rowIndex, colIndex - 1); // left markNonIsland(matrix, rowIndex, colIndex + 1); // right } function removeIslands(matrix) { const lastRowIndex = matrix.length - 1; const lastColIndex = matrix[0].length - 1; for (let colIndex = 0; colIndex < matrix[0].length; colIndex++) { if (matrix[0][colIndex] === 1) markNonIsland(matrix, 0, colIndex); if (matrix[lastRowIndex][colIndex] === 1) markNonIsland(matrix, lastRowIndex, colIndex); } for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { if (matrix[rowIndex][0] === 1) markNonIsland(matrix, rowIndex, 0); if (matrix[rowIndex][lastColIndex] === 1) markNonIsland(matrix, rowIndex, lastColIndex); } for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { for (let colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { if (matrix[rowIndex][colIndex] === 1) { matrix[rowIndex][colIndex] = 0; } if (matrix[rowIndex][colIndex] === 2) { matrix[rowIndex][colIndex] = 1; } } } return matrix; } ================================================ FILE: coding_interviews/algoexpert/remove-islands/remove-islands.js ================================================ /** You're given a two-dimensional array (a matrix) of potentially unequal height and width containing only 0s and 1s. The matrix represents a two-toned image, where each 1 represents black and each 0 represents white. An island is defined as any number of 1s that are horizontally or vertically adjacent (but not diagonally adjacent) and that don't touch the border of the image. In other words, a group of horizontally or vertically adjacent 1s isn't an island if any of those 1s are in the first row, last row, first column, or last column of the input matrix. Note that an island can twist. In other words, it doesn't have to be a straight vertical line or a straight horizontal line; it can be L-shaped, for example. You can think of islands as patches of black that don't touch the border of the two-toned image. Write a function that returns a modified version of the input matrix, where all of the islands are removed. You remove an island by replacing it with 0s. Naturally, you're allowed to mutate the input matrix. */ function removeIsland(matrix, rowIndex, colIndex) { if ( rowIndex < 0 || rowIndex >= matrix.length || colIndex < 0 || colIndex >= matrix[rowIndex].length ) { return; } if ([0, 2].includes(matrix[rowIndex][colIndex])) { return; } matrix[rowIndex][colIndex] = 2; removeIsland(matrix, rowIndex - 1, colIndex); // top removeIsland(matrix, rowIndex + 1, colIndex); // bottom removeIsland(matrix, rowIndex, colIndex - 1); // left removeIsland(matrix, rowIndex, colIndex + 1); // right } function removeIslands(matrix) { for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { for (let colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { if ( matrix[rowIndex][colIndex] === 1 && (rowIndex === 0 || rowIndex === matrix.length - 1 || colIndex === 0 || colIndex === matrix[rowIndex].length - 1) ) { removeIsland(matrix, rowIndex, colIndex); } } } for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { for (let colIndex = 0; colIndex < matrix[rowIndex].length; colIndex++) { if (matrix[rowIndex][colIndex] === 1) { matrix[rowIndex][colIndex] = 0; } if (matrix[rowIndex][colIndex] === 2) { matrix[rowIndex][colIndex] = 1; } } } return matrix; } ================================================ FILE: coding_interviews/algoexpert/run-length-encoding/run-length-encoding copy.js ================================================ function runLengthEncoding(string) { let currentChar; let num = 1; let result = []; for (let index = 0; index < string.length; index++) { currentChar = string[index]; if (currentChar === string[index + 1] && num < 9) { num++; } else { result.push(`${num}${currentChar}`); num = 1; } } return result.join(''); } ================================================ FILE: coding_interviews/algoexpert/run-length-encoding/run-length-encoding-cleaner.js ================================================ function runLengthEncoding(string) { if (string.length === 1) { return `1${string}`; } let currentChar = string[0]; let num = 1; let result = []; for (let index = 1; index < string.length; index++) { let char = string[index]; if (char === currentChar) { if (num === 9) { result.push(num); result.push(currentChar); num = 1; } else { num++; } } else { result.push(num); result.push(currentChar); num = 1; currentChar = char; } if (index === string.length - 1) { result.push(num); result.push(currentChar); } } return result.join(''); } ================================================ FILE: coding_interviews/algoexpert/run-length-encoding/run-length-encoding.js ================================================ function runLengthEncoding(string) { if (string.length === 1) { return `1${string}`; } let currentChar = string[0]; let num = 1; let result = []; for (let index = 1; index < string.length; index++) { let char = string[index]; if (char === currentChar) { if (num === 9) { result.push(num); result.push(currentChar); num = 1; } else { num++; } } else { result.push(num); result.push(currentChar); num = 1; currentChar = char; } if (index === string.length - 1) { result.push(num); result.push(currentChar); } } return result.join(''); } ================================================ FILE: coding_interviews/algoexpert/semordnilap/semordnilap.js ================================================ /** Write a function that takes in a list of unique strings and returns a list of semordnilap pairs. A semordnilap pair is defined as a set of different strings where the reverse of one word is the same as the forward version of the other. For example the words "diaper" and "repaid" are a semordnilap pair, as are the words "palindromes" and "semordnilap". The order of the returned pairs and the order of the strings within each pair does not matter. */ // Runtime: O(N * M), N = number of words, M = length o largest word // Space: O(N) function reverse(word) { let reversedWord = []; for (let index = word.length - 1; index >= 0; index--) { reversedWord.push(word[index]); } return reversedWord.join(''); } function semordnilap(words) { let pairs = []; let map = new Map(); for (let word of words) { if (map.has(word)) { pairs.push([word, map.get(word)]); } else { map.set(reverse(word), word); } } return pairs; } ================================================ FILE: coding_interviews/algoexpert/smallest-difference/smallest-difference.js ================================================ /** * * Write a function that takes in two non-empty arrays of integers, * finds the pair of numbers (one from each array) whose absolute * difference is closest to zero, and returns an array containing * these two numbers, with the number from the first array in the first position. * Note that the absolute difference of two integers is the distance * between them on the real number line. For example, the absolute * difference of -5 and 5 is 10, and the absolute difference of -5 and -4 is 1. * You can assume that there will only be one pair of numbers with the smallest difference. * * Input: * arrayOne = [-1, 5, 10, 20, 28, 3] * arrayTwo = [26, 134, 135, 15, 17] * * Output: * [28, 26] */ // Runtime: O(NlogN + MlogM), where N = length of arrayOne and M = length of arrayTwo // Space: O(1) function smallestDifference(arrayOne, arrayTwo) { let output = []; let indexOne = 0; let indexTwo = 0; let smallestDistance = Infinity; arrayOne.sort((a, b) => a - b); arrayTwo.sort((a, b) => a - b); while (indexOne < arrayOne.length && indexTwo < arrayTwo.length) { let one = arrayOne[indexOne]; let two = arrayTwo[indexTwo]; let distance = Math.abs(one - two); if (distance < smallestDistance) { smallestDistance = distance; output = [one, two]; } if (one < two) indexOne++; else indexTwo++; } return output; } ================================================ FILE: coding_interviews/algoexpert/sorted-squared-array/sorted-squared-array-insert-position.js ================================================ // Runtime: O(n) // Space: O(n) function sortedSquaredArray(array) { let output = []; for (let num of array) { let square = num * num; let inserted = false; for (let index = 0; index < output.length; index++) { if (square <= output[index]) { output = [...output.slice(0, index), square, ...output.slice(index)]; inserted = true; break; } } if (!inserted) output.push(square); } return output; } ================================================ FILE: coding_interviews/algoexpert/sorted-squared-array/sorted-squared-array-two-pointers.js ================================================ // Runtime: O(n) // Space: O(n) function sortedSquaredArray(array) { let p1 = 0; let p2 = array.length - 1; let result = []; while (p1 <= p2) { let square1 = array[p1] * array[p1]; let square2 = array[p2] * array[p2]; if (square1 > square2) { result.unshift(square1); p1++; } else { result.unshift(square2); p2--; } } return result; } ================================================ FILE: coding_interviews/algoexpert/sorted-squared-array/sorted-squared-array.js ================================================ // Runtime: O(nlogn) // Space: O(1) function sortedSquaredArray(array) { return array.map((num) => num * num).sort((a, b) => a - b); } ================================================ FILE: coding_interviews/algoexpert/spiral-traverse/spiral-traverse.js ================================================ /** * * Write a function that takes in an n x m two-dimensional array (that can be square-shaped when n == m) * and returns a one-dimensional array of all the array's elements in spiral order. * Spiral order starts at the top left corner of the two-dimensional array, goes to the right, * and proceeds in a spiral pattern all the way until every element has been visited. * * Input: * array = [ * [1, 2, 3, 4], * [12, 13, 14, 5], * [11, 16, 15, 6], * [10, 9, 8, 7], * ] * * Output: * [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16] */ // Right: keep the row and increase the column // Bottom: keep the column and increase the row // Left: keep the row and decrease the column // Top: keep the column and decrease the row function spiralTraverse(array) { let row = 0; let col = 0; let endRow = array.length - 1; let endCol = array[0].length - 1; let output = []; let command = 'R'; while (col <= endCol && row <= endRow) { if (command === 'R') { for (let index = col; index <= endCol; index++) { output.push(array[row][index]); } row++; command = 'B'; continue; } if (command === 'B') { for (let index = row; index <= endRow; index++) { output.push(array[index][endCol]); } endCol--; command = 'L'; continue; } if (command === 'L') { for (let index = endCol; index >= col; index--) { output.push(array[endRow][index]); } endRow--; command = 'T'; continue; } if (command === 'T') { for (let index = endRow; index >= row; index--) { output.push(array[index][col]); } col++; command = 'R'; continue; } } return output; } ================================================ FILE: coding_interviews/algoexpert/tandem-bicycle/tandem-bicycle-cleaner.js ================================================ // Runtime: O(NlogN) // Space: O(1) function getTotalSpeed(redShirtSpeeds, blueShirtSpeeds) { let sum = 0; for (let index = 0; index < redShirtSpeeds.length; index++) { sum += Math.max(redShirtSpeeds[index], blueShirtSpeeds[index]); } return sum; } function tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest) { redShirtSpeeds.sort((a, b) => a - b); blueShirtSpeeds.sort((a, b) => (fastest ? b - a : a - b)); return getTotalSpeed(redShirtSpeeds, blueShirtSpeeds); } ================================================ FILE: coding_interviews/algoexpert/tandem-bicycle/tandem-bicycle.js ================================================ // Runtime: O(NlogN) // Space: O(1) function getMinimumTotalSpeed(redShirtSpeeds, blueShirtSpeeds) { let sum = 0; for (let index = 0; index < redShirtSpeeds.length; index++) { sum += Math.max(redShirtSpeeds[index], blueShirtSpeeds[index]); } return sum; } function getMaximumTotalSpeed(redShirtSpeeds, blueShirtSpeeds) { let sum = 0; for (let index = 0; index < redShirtSpeeds.length; index++) { sum += Math.max( redShirtSpeeds[index], blueShirtSpeeds[blueShirtSpeeds.length - index - 1] ); } return sum; } function tandemBicycle(redShirtSpeeds, blueShirtSpeeds, fastest) { redShirtSpeeds.sort((a, b) => a - b); blueShirtSpeeds.sort((a, b) => a - b); return fastest ? getMaximumTotalSpeed(redShirtSpeeds, blueShirtSpeeds) : getMinimumTotalSpeed(redShirtSpeeds, blueShirtSpeeds); } ================================================ FILE: coding_interviews/algoexpert/three-number-sum/three-number-sum.js ================================================ function sortKey(array) { return [...new Set(array)] .sort((a, b) => a - b) .map((num) => num.toString()) .join('*'); } function threeNumberSum(array, targetSum) { array.sort((a, b) => a - b); let map = new Map(); let triplets = []; let cache = new Map(); for (let num of array) { map.set(num, map.get(num) + 1 || 1); } for (let i = 0; i < array.length; i++) { for (let j = i + 1; j < array.length; j++) { let rest = targetSum - array[i] - array[j]; let triplet = [array[i], array[j], rest]; let sortedKey = sortKey(triplet); let allEqual = array[i] === array[j] && array[i] === rest && map.has(rest) && map.get(rest) >= 3; let isFirstEqualRest = array[i] !== array[j] && array[i] === rest && map.has(rest) && map.get(rest) >= 2; let isSecondEqualRest = array[i] !== array[j] && array[j] === rest && map.has(rest) && map.get(rest) >= 2; let hasRest = array[i] !== rest && array[j] !== rest && map.has(rest); let isEligibleTriplet = (allEqual && isFirstEqualRest && isSecondEqualRest) || hasRest; if (!cache.has(sortedKey) && isEligibleTriplet) { cache.set(sortedKey, 1); triplets.push(triplet); } } } return triplets; } ================================================ FILE: coding_interviews/algoexpert/tournament-winner/tournament-winner-optimized.js ================================================ // Runtime: O(n), n being the number of competition // Space: O(k), k being the number of teams function tournamentWinner(competitions, results) { let teams = new Map(); let maxPoints = 0; let winner; for (let index = 0; index < competitions.length; index++) { let competition = competitions[index]; let result = results[index]; let team = result === 1 ? competition[0] : competition[1]; let points = (teams.get(team) || 0) + 3; teams.set(team, points); if (points > maxPoints) { winner = team; maxPoints = points; } } return winner; } ================================================ FILE: coding_interviews/algoexpert/tournament-winner/tournament-winner.js ================================================ // Runtime: O(n), n being the number of competition // Space: O(k), k being the number of teams function tournamentWinner(competitions, results) { let teams = new Map(); let maxPoints = 0; let winner; for (let index = 0; index < competitions.length; index++) { let competition = competitions[index]; let result = results[index]; let team = result === 1 ? competition[0] : competition[1]; teams.set(team, (teams.get(team) || 0) + 3); } for (let [team, points] of teams.entries()) { if (points > maxPoints) { winner = team; maxPoints = points; } } return winner; } ================================================ FILE: coding_interviews/algoexpert/transpose-matrix/transpose-matrix.js ================================================ // Runtime: O(R * C), R = rows and C = columns // Space: O(N) function transposeMatrix(matrix) { let transposedMatrix = []; for (let col = 0; col < matrix[0].length; col++) { let newRow = []; for (let row = 0; row < matrix.length; row++) { let cell = matrix[row][col]; newRow.push(cell); } transposedMatrix.push(newRow); } return transposedMatrix; } ================================================ FILE: coding_interviews/algoexpert/two-number-sum/two-number-sum-optimized.js ================================================ // Runtime: O(n) // Space: O(n) function twoNumberSum(array, targetSum) { let hashmap = new Map(); for (let num of array) { let complement = targetSum - num; if (hashmap.has(complement)) { return [num, complement]; } hashmap.set(num, num); } return []; } ================================================ FILE: coding_interviews/algoexpert/two-number-sum/two-number-sum-two-pointers.js ================================================ // Runtime: O(nlogn) // Space: O(1) function twoNumberSum(array, targetSum) { array.sort((a, b) => a - b); let left = 0; let right = array.length - 1; while (left < right) { let leftNumber = array[left]; let rightNumber = array[right]; if (leftNumber + rightNumber === targetSum) { return [leftNumber, rightNumber]; } if (leftNumber + rightNumber > targetSum) { right--; } else { left++; } } return []; } ================================================ FILE: coding_interviews/algoexpert/two-number-sum/two-number-sum.js ================================================ // Runtime: O(n^2) // Space: O(1) function twoNumberSum(array, targetSum) { let hashmap = new Map(); for (let num of array) { hashmap.set(num, num); } for (let num of array) { let match = targetSum - num; if (match !== num && hashmap.has(match)) { return [num, match]; } } return []; } ================================================ FILE: coding_interviews/algoexpert/validate-bst/validate-bst.js ================================================ class BST { constructor(value) { this.value = value; this.left = null; this.right = null; } } function validateBst(tree) { if (!tree) return true; let greaterThanLeftChild = true; let smallerThanOrEqualToRightChild = true; if (tree.left) greaterThanLeftChild = tree.left.value < tree.value; if (tree.right) smallerThanOrEqualToRightChild = tree.right.value >= tree.value; return ( greaterThanLeftChild && smallerThanOrEqualToRightChild && validateBst(tree.left) && validateBst(tree.right) ); } ================================================ FILE: coding_interviews/algoexpert/validate-subsequence/validate-subsequence-two-pointers.js ================================================ // Runtime: O(n) // Space: O(1) function isValidSubsequence(array, sequence) { let p1 = 0; let p2 = 0; while (p1 < array.length && p2 < sequence.length) { if (array[p1] === sequence[p2]) { p1++; p2++; } else { p1++; } } return p2 === sequence.length; } ================================================ FILE: coding_interviews/algoexpert/validate-subsequence/validate-subsequence.js ================================================ // Runtime: O(n) // Space: O(1) function isValidSubsequence(array, sequence) { let p = 0; for (let index = 0; index < array.length; index++) { if (array[index] === sequence[p]) { p++; } if (p === sequence.length) { return true; } } return false; } ================================================ FILE: coding_interviews/algoexpert/zero-sum-subarray/zero-sum-subarray-optimized.js ================================================ // Runtime: O(N), N = nums length // Space: O(N) function zeroSumSubarray(nums) { let currentSum = 0; let sums = new Set(); for (let index = 0; index < nums.length; index++) { currentSum += nums[index]; if (currentSum === 0 || sums.has(currentSum)) { return true; } sums.add(currentSum); } return false; } ================================================ FILE: coding_interviews/algoexpert/zero-sum-subarray/zero-sum-subarray.js ================================================ // Runtime: O(N^2), N = nums length // Space: O(1) function zeroSumSubarray(nums) { for (let i = 0; i < nums.length; i++) { let sum = nums[i]; for (let j = i; j < nums.length; j++) { if (i !== j) { sum += nums[j]; } if (sum === 0) { return true; } } } return false; } ================================================ FILE: coding_interviews/algorithms_in_python/queue/R-6.7.py ================================================ # What values are returned during the following sequence of queue operations, # if executed on an initially empty queue? enqueue(5), enqueue(3), dequeue(), # enqueue(2), enqueue(8), dequeue(), dequeue(), enqueue(9), enqueue(1), dequeue(), # enqueue(7), enqueue(6), dequeue(), dequeue(), enqueue(4), dequeue(), dequeue(). class Emptiness(Exception): pass class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): if self.is_empty(): raise Emptiness('The Queue is empty') return self.items.pop(0) def is_empty(self): return self.size() == 0 def front(self): if self.is_empty(): raise Emptiness('The Queue is empty') return self.items[0] def back(self): if self.is_empty(): raise Emptiness('The Queue is empty') return self.items[-1] def size(self): return len(self.items) queue = Queue() queue.enqueue(5) # [5] queue.enqueue(3) # [5, 3] queue.dequeue() # [3] queue.enqueue(2) # [3, 2] queue.enqueue(8) # [3, 2, 8] queue.dequeue() # [2, 8] queue.dequeue() # [8] queue.enqueue(9) # [8, 9] queue.enqueue(1) # [8, 9, 1] queue.dequeue() # [9, 1] queue.enqueue(7) # [9, 1, 7] queue.enqueue(6) # [9, 1, 7, 6] queue.dequeue() # [1, 7, 6] queue.dequeue() # [7, 6] queue.enqueue(4) # [7, 6, 4] queue.dequeue() # [6, 4] queue.dequeue() # [4] ================================================ FILE: coding_interviews/algorithms_in_python/stack/R-6.1.py ================================================ # R-6.1 from the Algorithms in Pytho book # What values are returned during the following series of stack operations, # if executed upon an initially empty stack? # push(5), push(3), pop(), push(2), push(8), pop(), pop(), push(9), # push(1), pop(), push(7), push(6), pop(), pop(), push(4), pop(), pop(). class Emptiness(Exception): pass class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items.pop() def is_empty(self): return self.size() == 0 def top(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items[-1] def size(self): return len(self.items) stack = Stack() stack.push(5) # [5] stack.push(3) # [5, 3] stack.pop() # [5] (removed 3) stack.push(2) # [5, 2] stack.push(8) # [5, 2, 8] stack.pop() # [5, 2] (removed 8) stack.pop() # [5] (removed 2) stack.push(9) # [5, 9] stack.push(1) # [5, 9, 1] stack.pop() # [5, 9] (removed 1) stack.push(7) # [5, 9, 7] stack.push(6) # [5, 9, 7, 6] stack.pop() # [5, 9, 7] (removed 6) stack.pop() # [5, 9] (removed 7) stack.push(4) # [5, 9, 4] stack.pop() # [5, 9] (removed 4) stack.pop() # [5] (removed 9) ================================================ FILE: coding_interviews/algorithms_in_python/stack/R-6.3.py ================================================ # R-6.3 from the Algorithms in Pytho book # Implement a function with signature transfer(S, T) that transfers all elements # from stack S onto stack T, so that the element that starts at the top of S is # the first to be inserted onto T, and the element at the bottom of S ends up at the top of T. class Emptiness(Exception): pass class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items.pop() def is_empty(self): return self.size() == 0 def top(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items[-1] def size(self): return len(self.items) def transfer(S, T): while not S.is_empty(): popped_item = S.pop() T.push(popped_item) return T S = Stack() T = Stack() S.push(1) S.push(2) S.push(3) S.push(4) S.push(5) new_T = transfer(S, T) print(new_T.items) # [5, 4, 3, 2, 1] ================================================ FILE: coding_interviews/algorithms_in_python/stack/R-6.4.py ================================================ # R-6.4 from the Algorithms in Pytho book # Give a recursive method for removing all the elements from a stack. class Emptiness(Exception): pass class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items.pop() def is_empty(self): return self.size() == 0 def top(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items[-1] def size(self): return len(self.items) def remove_all(stack): if stack.is_empty(): return stack stack.pop() return remove_all(stack) stack = Stack() stack.push(1) stack.push(2) stack.push(3) stack.push(4) stack.push(5) new_stack = remove_all(stack) print(new_stack.items) # [] ================================================ FILE: coding_interviews/algorithms_in_python/stack/R-6.5.py ================================================ # R-6.5 from the Algorithms in Pytho book # Implement a function that reverses a list of elements by pushing them onto # a stack in one order, and writing them back to the list in reversed order. class Emptiness(Exception): pass class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items.pop() def is_empty(self): return self.size() == 0 def top(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items[-1] def size(self): return len(self.items) def reverse(items): stack = Stack() for item in items: stack.push(item) new_items = [] while not stack.is_empty(): popped_item = stack.pop() new_items.append(popped_item) return new_items items = [1, 2, 3, 4, 5] new_items = reverse(items) print(new_items) ================================================ FILE: coding_interviews/blind75/README.md ================================================ # Blind 75 LeetCode Questions ## Array - [x] [Two Sum](https://leetcode.com/problems/two-sum): [Solution](/coding_interviews/leetcode/easy/two-sum/two-sum.js) - [ ] [Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock) - [x] [Contains Duplicate](https://leetcode.com/problems/contains-duplicate): [Solution 1](/coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.js) & [Solution 2](/coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate-hashmap.js) - [x] [Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self): [Solution](/coding_interviews/leetcode/medium/product-of-array-except-self/product-of-array-except-self.js) - [x] [Maximum Subarray](https://leetcode.com/problems/maximum-subarray): [Solution](/coding_interviews/leetcode/easy/maximum-subarray/maximum-subarray.js) - [ ] [Maximum Product Subarray](https://leetcode.com/problems/maximum-product-subarray) - [ ] [Find Minimum in Rotated Sorted Array](https://leetcode.com/problems/find-minimum-in-rotated-sorted-array) - [ ] [Search in Rotated Sorted Array](https://leetcode.com/problems/search-in-rotated-sorted-array) - [ ] [3Sum](https://leetcode.com/problems/3sum) - [ ] [Container With Most Water](https://leetcode.com/problems/container-with-most-water) ## Binary - [ ] [Sum of Two Integers](https://leetcode.com/problems/sum-of-two-integers) - [ ] [Number of 1 Bits](https://leetcode.com/problems/number-of-1-bits) - [ ] [Counting Bits](https://leetcode.com/problems/counting-bits) - [ ] [Missing Number](https://leetcode.com/problems/missing-number) - [ ] [Reverse Bits](https://leetcode.com/problems/reverse-bits) ## Dynamic Programming - [x] [Climbing Stairs](https://leetcode.com/problems/climbing-stairs): [Solution](/coding_interviews/leetcode/easy/climbing-stairs/climbing-stairs.js) - [ ] [Coin Change](https://leetcode.com/problems/coin-change) - [ ] [Longest Increasing Subsequence](https://leetcode.com/problems/longest-increasing-subsequence) - [ ] [Longest Common Subsequence](https://leetcode.com/problems/longest-common-subsequence) - [ ] [Word Break Problem](https://leetcode.com/problems/word-break) - [ ] [Combination Sum](https://leetcode.com/problems/combination-sum-iv) - [ ] [House Robber](https://leetcode.com/problems/house-robber) - [ ] [House Robber II](https://leetcode.com/problems/house-robber-ii) - [ ] [Decode Ways](https://leetcode.com/problems/decode-ways) - [ ] [Unique Paths](https://leetcode.com/problems/unique-paths) - [ ] [Jump Game](https://leetcode.com/problems/jump-game) ## Graph - [x] [Clone Graph](https://leetcode.com/problems/clone-graph): [Solution](https://github.com/imteekay/algorithms/blob/master/coding_interviews/leetcode/medium/clone-graph/clone-graph.js) - [ ] [Course Schedule](https://leetcode.com/problems/course-schedule) - [ ] [Pacific Atlantic Water Flow](https://leetcode.com/problems/pacific-atlantic-water-flow) - [x] [Number of Islands](https://leetcode.com/problems/number-of-islands): [Solution](/coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js) - [ ] [Longest Consecutive Sequence](https://leetcode.com/problems/longest-consecutive-sequence) ## Interval - [ ] [Insert Interval](https://leetcode.com/problems/insert-interval) - [ ] [Merge Intervals](https://leetcode.com/problems/merge-intervals) - [ ] [Non-overlapping Intervals](https://leetcode.com/problems/non-overlapping-intervals) ## Linked List - [x] [Reverse a Linked List](https://leetcode.com/problems/reverse-linked-list): [Solution](/coding_interviews/leetcode/easy/reverse-linked-list/reverse-linked-list.js) - [ ] [Detect Cycle in a Linked List](https://leetcode.com/problems/linked-list-cycle) - [ ] [Merge Two Sorted Lists](https://leetcode.com/problems/merge-two-sorted-lists): [Solution](/coding_interviews/leetcode/easy/merge-two-sorted-lists/merge-two-sorted-lists.js) - [ ] [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists) - [ ] [Remove Nth Node From End Of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list): [Solution 1](/coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js) & [Solution 2](/coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list-fast-slow.js) - [ ] [Reorder List](https://leetcode.com/problems/reorder-list) ## Matrix - [x] [Set Matrix Zeroes](https://leetcode.com/problems/set-matrix-zeroes): [Solution](/coding_interviews/leetcode/medium/set-matrix-zeroes/set-matrix-zeroes.js) - [ ] [Spiral Matrix](https://leetcode.com/problems/spiral-matrix) - [x] [Rotate Image](https://leetcode.com/problems/rotate-image): [Solution](/coding_interviews/leetcode/medium/rotate-image/rotate-image.js) - [ ] [Word Search](https://leetcode.com/problems/word-search) ## String - [x] [Longest Substring Without Repeating Characters](https://leetcode.com/problems/longest-substring-without-repeating-characters): [Solution](/coding_interviews/leetcode/medium/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js) - [ ] [Longest Repeating Character Replacement](https://leetcode.com/problems/longest-repeating-character-replacement) - [ ] [Minimum Window Substring](https://leetcode.com/problems/minimum-window-substring) - [x] [Valid Anagram](https://leetcode.com/problems/valid-anagram): [Solution](/coding_interviews/leetcode/easy/valid-anagram/valid-anagram.js) - [x] [Group Anagrams](https://leetcode.com/problems/group-anagrams): [Solution](/coding_interviews/leetcode/medium/group-anagrams/group-anagrams.js) - [x] [Valid Parentheses](https://leetcode.com/problems/valid-parentheses): [Solution](/coding_interviews/leetcode/easy/valid-parentheses/valid-parentheses.js) - [x] [Valid Palindrome](https://leetcode.com/problems/valid-palindrome): [Solution](/coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome.js) - [ ] [Longest Palindromic Substring](https://leetcode.com/problems/longest-palindromic-substring) - [ ] [Palindromic Substrings](https://leetcode.com/problems/palindromic-substrings) ## Tree - [x] [Maximum Depth of Binary Tree](https://leetcode.com/problems/maximum-depth-of-binary-tree): [Solution 1](/coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js) & [Solution 2](/coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree-2.js) - [x] [Same Tree](https://leetcode.com/problems/same-tree): [Solution](/coding_interviews/leetcode/easy/same-tree/same-tree.js) - [x] [Invert/Flip Binary Tree](https://leetcode.com/problems/invert-binary-tree): [Solution](/coding_interviews/leetcode/easy/invert-binary-tree/invert-binary-tree.js) - [ ] [Binary Tree Maximum Path Sum](https://leetcode.com/problems/binary-tree-maximum-path-sum) - [x] [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal): [Solution](/coding_interviews/leetcode/medium/binary-tree-level-order-traversal/binary-tree-level-order-traversal.js) - [ ] [Serialize and Deserialize Binary Tree](https://leetcode.com/problems/serialize-and-deserialize-binary-tree) - [x] [Subtree of Another Tree](https://leetcode.com/problems/subtree-of-another-tree): [Solution](/coding_interviews/leetcode/easy/subtree-of-another-tree/subtree-of-another-tree.js) - [ ] [Construct Binary Tree from Preorder and Inorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal) - [x] [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree): [Solution 1](/coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-2.js) & [Solution 2](/coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree.js) - [x] [Kth Smallest Element in a BST](https://leetcode.com/problems/kth-smallest-element-in-a-bst): [Solution 1](/coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-1.js) & [Solution 2](/coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-2.js) - [x] [Lowest Common Ancestor of BST](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree): [Solution](/coding_interviews/leetcode/easy/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.js) - [ ] [Implement Trie (Prefix Tree)](https://leetcode.com/problems/implement-trie-prefix-tree) - [ ] [Add and Search Word](https://leetcode.com/problems/add-and-search-word-data-structure-design) - [ ] [Word Search II](https://leetcode.com/problems/word-search-ii) ## Heap - [ ] [Merge K Sorted Lists](https://leetcode.com/problems/merge-k-sorted-lists) - [ ] [Top K Frequent Elements](https://leetcode.com/problems/top-k-frequent-elements) - [ ] [Find Median from Data Stream](https://leetcode.com/problems/find-median-from-data-stream) ## Important Link: [14 Patterns to Ace Any Coding Interview Question](https://hackernoon.com/14-patterns-to-ace-any-coding-interview-question-c5bb3357f6ed) ================================================ FILE: coding_interviews/coding_interview_questions/common_elements.py ================================================ def common_elements(list1, list2): result = [] elements = {} for item in list1: elements[item] = 1 for item in list2: if item in elements: result.append(item) return result # common_elements(list_a1, list_a2) should return [1, 4, 9] (a list). list_a1 = [1, 3, 4, 6, 7, 9] list_a2 = [1, 2, 4, 5, 9, 10] print(common_elements(list_a1, list_a2)) # common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list). list_b1 = [1, 2, 9, 10, 11, 12] list_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15] print(common_elements(list_b1, list_b2)) # common_elements(list_b1, list_b2) should return [] (an empty list). list_c1 = [0, 1, 2, 3, 4, 5] list_c2 = [6, 7, 8, 9, 10, 11] print(common_elements(list_c1, list_c2)) ================================================ FILE: coding_interviews/coding_interview_questions/decode-string/decode-string.js ================================================ const isNum = (char) => !isNaN(Number(char)); export function decodeString(encodedString) { const stack = []; let index = 0; while (index < encodedString.length) { const char = encodedString[index]; if (isNum(char)) { const number = []; while (isNum(encodedString[index])) { number.push(encodedString[index]); index++; } stack.push(Number(number.join(''))); continue; } if (char === ']') { let str = ''; while (stack[stack.length - 1] !== '[') { str = stack.pop() + str; } stack.pop(); stack.push(str.repeat(stack.pop())); index++; continue; } stack.push(char); index++; } return stack.join(''); } ================================================ FILE: coding_interviews/coding_interview_questions/decode-string/tests/decode-string.test.js ================================================ import { describe, it, expect } from 'vitest'; import { decodeString } from '../decode-string'; describe('decodeString', () => { it('', () => { expect(decodeString('3[a]2[bc]')).toEqual('aaabcbc'); }); it('', () => { expect(decodeString('2[abc]3[cd]ef')).toEqual('abcabccdcdcdef'); }); it('', () => { expect(decodeString('3[a2[c]]')).toEqual('accaccacc'); }); it('', () => { expect(decodeString('100[leetcode]')).toEqual( 'leetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcode' ); }); }); ================================================ FILE: coding_interviews/coding_interview_questions/mine_swipper.py ================================================ # [[0, 0], [0, 1]], 3, 4 # => [ # [-1, -1, 1, 0], # [2, 2, 1, 0], # [0, 0, 0, 0] # ] def update_table_spot(table, row, col, num_rows, num_cols): table_with_border = table border = [] for row in range(num_rows): table_with_border[row].insert(0, 0) table_with_border[row].insert(num_cols+1, 0) for i in range(num_cols+2): border.append(0) table_with_border.insert(0, border) table_with_border.insert(num_rows+1, border) number_of_bomb_neighboors = 0 for i in range(num_rows): for j in range(num_cols): print(table[i][j], end='') print() print() if table_with_border[row-1][col-1] == -1: number_of_bomb_neighboors += 1 if table_with_border[row-1][col] == -1: number_of_bomb_neighboors += 1 if table_with_border[row-1][col+1] == -1: number_of_bomb_neighboors += 1 if table_with_border[row][col-1] == -1: number_of_bomb_neighboors += 1 if table_with_border[row][col+1] == -1: number_of_bomb_neighboors += 1 if table_with_border[row+1][col-1] == -1: number_of_bomb_neighboors += 1 if table_with_border[row+1][col] == -1: number_of_bomb_neighboors += 1 if table_with_border[row+1][col+1] == -1: number_of_bomb_neighboors += 1 table[row][col] = number_of_bomb_neighboors return table def mine_swipper(bombs, num_rows, num_cols): table = [] for row in range(num_rows): filled_row = [] for col in range(num_cols): filled_row.append(0) table.append(filled_row) for bomb in bombs: table[bomb[0]][bomb[1]] = -1 for row in range(num_rows): for col in range(num_cols): if table[row][col] == 0: table = update_table_spot(table, row, col, num_rows, num_cols) for i in range(num_rows): for j in range(num_cols): print(table[i][j], end='') print() mine_swipper([[0, 0], [0, 1]], 3, 4) ================================================ FILE: coding_interviews/coding_interview_questions/most_frequently_occurring.py ================================================ def most_frequent(given_list): max_item = 0 result = 0 if not given_list: return None frequencies = {} for item in given_list: if item in frequencies: frequencies[item] += 1 else: frequencies[item] = 1 if frequencies[item] > max_item: result = item max_item = frequencies[item] return result # most_frequent(list1) should return 1 list1 = [1, 3, 1, 3, 2, 1] print(most_frequent(list1)) # most_frequent(list2) should return 3 list2 = [3, 3, 1, 3, 2, 1] print(most_frequent(list2)) # most_frequent(list3) should return None list3 = [] print(most_frequent(list3)) # most_frequent(list4) should return 0 list4 = [0] print(most_frequent(list4)) # most_frequent(list5) should return -1 list5 = [0, -1, 10, 10, -1, 10, -1, -1, -1, 1] print(most_frequent(list5)) ================================================ FILE: coding_interviews/coding_interview_questions/non_repeating.py ================================================ # 'aabcb' --> 'c' # 'xxyz' --> 'y' # '' --> None # 'aabb' --> None # 'abcab' --> 'c' # 'abab' --> None # 'aabbbc' --> 'c' # 'aabbdbc' --> 'd' def non_repeating(string): counter_mapping = {} for char in string: if char in counter_mapping: counter_mapping[char] += 1 else: counter_mapping[char] = 1 for char, counter in counter_mapping.items(): if counter == 1: return char return None print(non_repeating('aabcb')) print(non_repeating('xxyz')) print(non_repeating('')) print(non_repeating('aabb')) print(non_repeating("abcab")) print(non_repeating("abab")) print(non_repeating("aabbbc")) print(non_repeating("aabbdbc")) ================================================ FILE: coding_interviews/coding_interview_questions/nth_element_from_the_end.py ================================================ # Use this class to create linked lists. class Node: def __init__(self, value, next=None): self.value = value self.next = next def __str__(self): return str(self.value) def nth_from_last(head, n): if head is None or n < 0: return elements = [] current_node = head while current_node: elements.append(current_node.value) current_node = current_node.next if n > len(elements): return None else: return elements[len(elements) - n] # Testing Linked List function def linked_list_to_string(head): current = head str_list = [] while current: str_list.append(str(current.value)) current = current.next return ' -> '.join(str_list.append('(None)')) current = Node(1) for i in range(2, 8): current = Node(i, current) head = current # head = 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> (None) current2 = Node(4) for i in range(3, 0, -1): current2 = Node(i, current2) head2 = current2 # head2 = 1 -> 2 -> 3 -> 4 -> (None) print('nth_from_last(head, 1) should return 1.') print(nth_from_last(head, 1)) print('nth_from_last(head, 5) should return 5.') print(nth_from_last(head, 5)) print('nth_from_last(head2, 2) should return 3.') print(nth_from_last(head2, 2)) print('nth_from_last(head2, 4) should return 1.') print(nth_from_last(head2, 4)) print('nth_from_last(head2, 5) should return None.') print(nth_from_last(head2, 5)) print('nth_from_last(None, 1) should return None.') print(nth_from_last(None, 1)) ================================================ FILE: coding_interviews/coding_interview_questions/one_away_strings.py ================================================ # 'abcde' # 'abfde' # => True # 'abcde' # 'abde' # => True # 'abde' # 'abfde' # => True def handle_different_sized_strings(s1, s2): indice1, indice2, number_of_differences = 0, 0, 0 while indice2 < len(s2): if number_of_differences > 1: return False if s1[indice1] != s2[indice2]: number_of_differences += 1 indice1 += 1 indice1 += 1 indice2 += 1 return True def handle_same_sized_strings(s1, s2): number_of_differences = 0 for indice in range(len(s1)): if s1[indice] != s2[indice]: number_of_differences += 1 return number_of_differences == 1 def is_one_away(s1, s2): if len(s1) - len(s2) > 1 or len(s2) - len(s1) > 1: return False if s1 == s2: return True if len(s1) > len(s2): return handle_different_sized_strings(s1, s2) if len(s2) > len(s1): return handle_different_sized_strings(s2, s1) if len(s1) == len(s2): return handle_same_sized_strings(s1, s2) print(is_one_away('abcde', 'abfde')) print(is_one_away('abcde', 'abde')) print(is_one_away('abde', 'abfde')) print(is_one_away('', '')) print(is_one_away('', 'a')) print(is_one_away('a', '')) print(is_one_away('aabb', 'aacc')) print() print(is_one_away("abcde", "abcd")) # should return True print(is_one_away("abde", "abcde")) # should return True print(is_one_away("a", "a")) # should return True print(is_one_away("abcdef", "abqdef")) # should return True print(is_one_away("abcdef", "abccef")) # should return True print(is_one_away("abcdef", "abcde")) # should return True print(is_one_away("aaa", "abc")) # should return False print(is_one_away("abcde", "abc")) # should return False print(is_one_away("abc", "abcde")) # should return False print(is_one_away("abc", "bcc")) # should return False ================================================ FILE: coding_interviews/coding_interview_questions/optimized_common_elements.py ================================================ def common_elements(list1, list2): result = [] point1 = 0 point2 = 0 while point1 < len(list1) and point2 < len(list2): if list1[point1] == list2[point2]: result.append(list1[point1]) point1 += 1 point2 += 1 elif list1[point1] > list2[point2]: point2 += 1 else: point1 += 1 return result # common_elements(list_a1, list_a2) should return [1, 4, 9] (a list). list_a1 = [1, 3, 4, 6, 7, 9] list_a2 = [1, 2, 4, 5, 9, 10] print(common_elements(list_a1, list_a2)) # common_elements(list_b1, list_b2) should return [1, 2, 9, 10, 12] (a list). list_b1 = [1, 2, 9, 10, 11, 12] list_b2 = [0, 1, 2, 3, 4, 5, 8, 9, 10, 12, 14, 15] print(common_elements(list_b1, list_b2)) # common_elements(list_b1, list_b2) should return [] (an empty list). list_c1 = [0, 1, 2, 3, 4, 5] list_c2 = [6, 7, 8, 9, 10, 11] print(common_elements(list_c1, list_c2)) ================================================ FILE: coding_interviews/coding_interview_questions/rotation_array.py ================================================ # both arrays are the same size? => true # is A and B is equal, is A a rotation of B? => false # is both array is empty, one is a rotation of another? => true # [1, 2, 3, 4, 5, 6, 7] # [4, 5, 6, 7, 1, 2, 3] # True # [1, 2, 3, 4, 5, 6, 7] # [4, 3, 6, 7, 1, 2, 3] # False # [] # [] # True def is_rotation(a, b): if a == b: return True if len(a) != len(b): return False for index in range(1, len(b)): if b[index:len(b)] + b[0:index] == a: return True return False a = [1, 2, 3, 4, 5, 6, 7] b = [4, 5, 6, 7, 1, 2, 3] print(is_rotation(a, b)) a = [1, 2, 3, 4, 5, 6, 7] b = [4, 3, 6, 7, 1, 2, 3] print(is_rotation(a, b)) a = [] b = [] print(is_rotation(a, b)) ================================================ FILE: coding_interviews/coding_interview_questions/two-crystal-balls/index.js ================================================ export function twoCrystalBalls(breaks) { let jumpAmount = Math.floor(Math.sqrt(breaks.length)); let index = jumpAmount; for (; index < breaks.length; index += jumpAmount) { if (breaks[index]) break; } index -= jumpAmount; for (let j = 0; j < jumpAmount && index < breaks.length; index++, j++) { if (breaks[index]) return index; } return -1; } ================================================ FILE: coding_interviews/coding_interview_questions/two-crystal-balls/tests/index.test.js ================================================ import { describe, expect, it } from 'vitest'; import { twoCrystalBalls } from '..'; describe('twoCrystalBalls', () => { it('', () => { const idx = Math.floor(Math.random() * 10000); const data = new Array(10000).fill(false); for (let i = idx; i < 10000; ++i) { data[i] = true; } expect(twoCrystalBalls(data)).toEqual(idx); expect(twoCrystalBalls(new Array(821).fill(false))).toEqual(-1); }); }); ================================================ FILE: coding_interviews/cracking-the-coding-interview/README.md ================================================ # Cracking the Coding Interview ## Chapter 001: Arrays and Strings - [1.1 Is Unique](./chapter-001/is-unique) - [1.2 Check Permutation](./chapter-001/check-permutation) - [1.3 URLlify](./chapter-001/urlify) - [1.4 Palindrome Permutation](./chapter-001/palindrome-permutation) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/aditional1.py ================================================ def product(a, b): sum = 0 for i in range(b): sum += a return sum print(product(2, 4)) # Complexity: O(b) | O(N) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/aditional2.py ================================================ def power(a, b): if b < 0: return 0 elif b == 0: return 1 else: return a * power(a, b - 1) print(power(2, 2)) print(power(2, 10)) print(power(3, 2)) # Complexity: O(B) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/aditional3.py ================================================ def mod(a, b): if b > a: return a return mod(a - b, b) print(mod(10, 2)) print(mod(10, 3)) print(mod(10, 4)) print(mod(10, 5)) print(mod(10, 6)) # Complexity: O(a / b) def mod(a, b): if b <= 0: return -1 div = a / b return a - div * b # Complexity: O(1) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/aditional4.py ================================================ def div(a, b): count = 0 sum = b while sum <= a: sum += b count += 1 return count print(div(10, 5)) print(div(10, 2)) print(div(10, 3)) print(div(10, 11)) # Complexity: O(a / b) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/aditional5.py ================================================ def sqrt(n): return sqrt_helper(n, 1, n) def sqrt_helper(n, min, max): if min > max: return -1 guess = (min + max) / 2 if guess * guess > n: return sqrt_helper(n, min, guess - 1) elif guess * guess < n: return sqrt_helper(n, guess + 1, max) else: return guess print(sqrt(100)) print(sqrt(9)) print(sqrt(25)) print(sqrt(3)) # Complexity: O(log N) --> It is a binary search algorithm ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/aditional6.py ================================================ from math import sqrt def square_root(n): for guess in range(int(sqrt(n))+1): if guess * guess == n: return guess return -1 print(square_root(100)) print(square_root(9)) print(square_root(25)) print(square_root(3)) # Complexity: O(log N) --> It is a binary search algorithm ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example1.py ================================================ def foo(array): sum = 0 product = 1 for element in array: sum += element for element in array: product *= element print("%d, %d" %(sum, product)) foo([1, 2, 3, 4, 5]) # The complexity of the foo function is: O(N) # Initializing sum and product = 1 + 1 = 2 # We iterate through the array two times = 2 * length(array) = 2 * N # Printing sum and product = 1 # Conclusion: O(2N + 3) = O(N) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example10.py ================================================ from math import sqrt def is_prime(num): if num < 2: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(sqrt(num)) + 1, 2): if num % i == 0: return False return True print(is_prime(1)) # False print(is_prime(2)) # True print(is_prime(9)) # False print(is_prime(17)) # True print(is_prime(24)) # False # is prime function has complexity of O(sqrt(N)) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example11.py ================================================ def factorial(n): if n < 0: return -1 if n == 0: return 1 return n * factorial(n - 1) # factorial function has a complexity of O(N) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example12.py ================================================ def permutation(str): handle_permutation(str, "") def handle_permutation(str, prefix): if len(str) == 0: print(prefix) else: for i in range(len(str)): rem = str[0:i] + str[i+1:] handle_permutation(rem, prefix + str[i]) permutation('abc') ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example13.py ================================================ def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2) print(fib(1)) print(fib(4)) print(fib(5)) print(fib(10)) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example14.py ================================================ def all_fib(n): for i in range(n): print(fib(i)) def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2) all_fib(10) # Complexity: O(2 ^ (n+1)) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example15.py ================================================ def all_fib(n): memo = [] memo.append(0) memo.append(1) for i in range(n): print("%d: %d" %(i, fib(i, memo))) def fib(n, memo): if n <= len(memo) - 1: return memo[n] memo.append(fib(n - 1, memo) + fib(n - 2, memo)) return memo[n] all_fib(7) # Complexity: O(N) # All previous actions are already computed ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example16.py ================================================ def powers_of_2(n): if n <= 0: return 0 if n == 1: print(1) return 1 previous = powers_of_2(n / 2) current = previous * 2 print(current) return current powers_of_2(4) # Complexity: O(log N) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example2.py ================================================ def print_pairs(array): for i in array: for j in array: print("%d, %d" %(i, j)) print_pairs([1, 2, 3, 4, 5]) # The complexity of the print_pairs function is: O(N^2) # We do a nested loop = length(array) ^ 2 = N * 2 # There are O(N^2) pairs # Conclusion: O(N^2) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example3.py ================================================ def print_unordered_pairs(array): for i in range(len(array)): for j in range(i+1, len(array)): print("%d, %d" %(array[i], array[j])) print_unordered_pairs([1, 2, 3, 4, 5]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array) * (length(array) - 1) / 2 = (length(array) * 2 - length(array)) / 2 = (N^2 - N) / 2 # There are O((N^2 - N) / 2) pairs # Conclusion: O(N^2) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example4.py ================================================ def print_unordered_pairs(array_a, array_b): for a in array_a: for b in array_b: if a < b: print('%d, %d' %(a, b)) print_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array_a) * length(array_b) = N^2 # There are O(N^2) pairs # Conclusion: O(N^2) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example5.py ================================================ def print_unordered_pairs(array_a, array_b): for a in array_a: for b in array_b: for i in range(1000000): print('%d, %d' %(a, b)) print_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array_a) * length(array_b) * 1000000 = N^2 * 1000000 # There are O(N^2 * 1000000) pairs # Conclusion: O(N^2) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example6.py ================================================ def reverse(array): for i in range(len(array) / 2): index = len(array) - i - 1 temporary_num = array[index] array[index] = array[i] array[i] = temporary_num return array new_array = reverse(list(range(1, 6)) for i in new_array: print(i) # The complexity of the reverse function is: O(N) # Even though we iterate only through half of the array (O(N/2)), we still consider this a O(N) complexity # Conclusion: O(N) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example7.py ================================================ # O(N + P), if P < N / 2 --> O(N) # O(2N) --> O(N) # O(N + logN) --> O(N) # O(N + M), if N > M then O(N), otherwise O(M) ================================================ FILE: coding_interviews/cracking-the-coding-interview/big_o/example9.py ================================================ def sum(node): if node is None: return 0 return sum(node.left) + node.value + sum(node.right) # If we have N nodes in our tree, this will be O(N) complexity ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/check-permutation/check-permutation.js ================================================ // Given two strings, write a method to decide if one is a permutation of the other // If they have different lengths, they are not permutations // Build a hashmap of characters of one of the strings // Iterate through the other string and check if the characters are in the hashmap // If there's no match in the hashmap, they are not permutations // If it passes the loop, they are permutations. // Runtime Complexity: O(N), where N = the length of the string // Space Complexity: O(N), where N = the length of the string function buildCharsMap(string) { const charsMap = new Map(); for (let char of string) { if (charsMap.has(char)) charsMap.set(char, charsMap.get(char) + 1); else charsMap.set(char, 1); } return charsMap; } export function checkPermutation(s1, s2) { if (s1.length !== s2.length) return false; const charsMap = buildCharsMap(s1); for (let char of s2) { if (!charsMap.has(char)) { return false; } if (charsMap.get(char) === 0) { return false; } charsMap.set(char, charsMap.get(char) - 1); } return true; } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/check-permutation/check-permutation.test.js ================================================ import { describe, expect, it } from 'vitest'; import { checkPermutation } from './check-permutation'; describe('checkPermutation', () => { it('returns the correct results', () => { expect(checkPermutation('aba', 'aab')).toBeTruthy(); }); it('returns the correct results', () => { expect(checkPermutation('aba', 'aaba')).toBeFalsy(); }); it('returns the correct results', () => { expect(checkPermutation('aba', 'aa')).toBeFalsy(); }); }); ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/cpp/remove_specified_character.cpp ================================================ #include #include using namespace std; int main() { string word, characteres, result = ""; getline(cin, word); cin >> characteres; for (int i = 0; i < word.size(); i++) { int belongs_to = 0; for (int j = 0; j < characteres.size(); j++) { if (word[i] == characteres[j]) { belongs_to = 1; break; } } if (!belongs_to) result += word[i]; } cout << result << endl; return 0; } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/is-unique/is-unique.js ================================================ // Is Unique: Implement an algorithm to determine if a string has all unique characters. // Using a hashmap to count the number of characters in the string // if there's already a character, it should return false as a result // if it passes the entire string, it means it's a string with unique characters // Time Complexity: O(N), N = number of charactes in the string // Space Complexity: O(N), N = number of charactes in the string stored in the `charMap` hashmap export function isUnique(string) { const charMap = new Map(); for (let char of string) { if (charMap.has(char)) return false; charMap.set(char, 1); } return true; } // Using a set to store all unique characters of the string // if the size of the set is equal to the string, the string has unique characters // Time Complexity: O(N), N = number of charactes in the string // Space Complexity: O(N), N = number of charactes in the string stored in the `uniqueChars` set export function isUniqueWithSet(string) { const uniqueChars = new Set(); for (let char of string) { uniqueChars.add(char); } return uniqueChars.size === string.length; } // Using a set to store all unique characters of the string // A simplified version using the Set constructor // Time Complexity: O(N), N = number of charactes in the string // Space Complexity: O(N), N = number of charactes in the string stored in the `uniqueChars` set export function isUniqueWithSetSimplified(string) { return string.length === new Set(string).size; } // --- What if you cannot use additional data structures? --- // Comparing each character with all the other characters // Runtime Complexity: O(N^2) // Space Complexity: O(1) export function isUniqueNSquare(string) { for (let i = 0; i < string.length; i++) { for (let j = i + 1; j < string.length; j++) { if (string[i] === string[j]) return false; } } return true; } // Sorting and comparing adjacent characters // Runtime Complexity: O(NlogN) because of the sorting runtime complexity // Space Complexity: O(N) because of the newly created array export function isUniqueWithoutDS(string) { let sortedString = [...string].sort( (a, b) => a.charCodeAt() - b.charCodeAt() ); for (let index = 0; index < sortedString.length - 1; index++) { if (sortedString[index] === sortedString[index + 1]) return false; } return true; } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/is-unique/is-unique.test.js ================================================ import { describe, expect, it } from 'vitest'; import { isUnique, isUniqueNSquare, isUniqueWithSet, isUniqueWithSetSimplified, isUniqueWithoutDS, } from './is-unique'; const unique = 'asdfghjkl'; const nonUnique = 'asdfghjkla'; describe('isUnique', () => { it('returns correct result', () => { expect(isUnique(unique)).toBeTruthy(); }); it('returns false for non-unique characters', () => { expect(isUnique(nonUnique)).toBeFalsy(); }); }); describe('isUniqueWithSet', () => { it('returns true for unique characters', () => { expect(isUniqueWithSet(unique)).toBeTruthy(); }); it('returns false for non-unique characters', () => { expect(isUniqueWithSet(nonUnique)).toBeFalsy(); }); }); describe('isUniqueWithSetSimplified', () => { it('returns true for unique characters', () => { expect(isUniqueWithSetSimplified(unique)).toBeTruthy(); }); it('returns false for non-unique characters', () => { expect(isUniqueWithSetSimplified(nonUnique)).toBeFalsy(); }); }); describe('isUniqueNSquare', () => { it('returns true for unique characters', () => { expect(isUniqueNSquare(unique)).toBeTruthy(); }); it('returns false for non-unique characters', () => { expect(isUniqueNSquare(nonUnique)).toBeFalsy(); }); }); describe('isUniqueWithoutDS', () => { it('returns true for unique characters', () => { expect(isUniqueWithoutDS(unique)).toBeTruthy(); }); it('returns false for non-unique characters', () => { expect(isUniqueWithoutDS(nonUnique)).toBeFalsy(); }); }); ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/one-away/one-away.js ================================================ // One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. // Given two strings, write a function to check if they are one edit (or zero edits) away // Examples // pale, ple -> true // pales, pale -> true // pale, bale -> true // pale, bake -> false /** * pale => {p: 1, a: 1, l: 1, e: 1} * ple => {p: 1, l: 1, e: 1} * bake => {b: 1, a: 1, k: 1, e: 1} */ function buildCharsCount(string) { let charsCount = new Map(); for (let char of string) { if (charsCount.has(char)) charsCount.set(char, charsCount.get(char) + 1); else charsCount.set(char, 1); } return charsCount; } export function oneAway(s1, s2) { if (s1.length - s2.length >= 2) return false; if (s2.length - s1.length >= 2) return false; let charsCount1 = buildCharsCount(s1); let charsCount2 = buildCharsCount(s2); let string = charsCount1.size >= charsCount2.size ? s1 : s2; let [map1, map2] = charsCount1.size >= charsCount2.size ? [charsCount1, charsCount2] : [charsCount2, charsCount1]; let numberOfEdits = 0; for (let char of string) { let count1 = map1.get(char) || 0; let count2 = map2.get(char) || 0; numberOfEdits += count1 - count2; } return [0, 1].includes(numberOfEdits); } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/one-away/one-away.test.js ================================================ import { describe, expect, it } from 'vitest'; import { oneAway } from './one-away'; describe('oneAway', () => { it('', () => { expect(oneAway('pale', 'ple')).toEqual(true); expect(oneAway('pale', 'pale')).toEqual(true); expect(oneAway('pales', 'pale')).toEqual(true); expect(oneAway('pale', 'bale')).toEqual(true); expect(oneAway('paalle', 'paklle')).toEqual(true); expect(oneAway('paalle', 'paklle')).toEqual(true); expect(oneAway('1203', '1213')).toEqual(true); expect(oneAway('pale', 'bake')).toEqual(false); expect(oneAway('palee', 'ple')).toEqual(false); }); }); ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/palindrome-permutation/palindrome-permutation.js ================================================ // Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. // A palindrome is a word or phrase that is the same forwards and backwards. // A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. // You can ignore casing and non-letter characters. // Example: // Tact Coa // - taco cat // - atco cta // Runtime Complexity: O(N), where N = the true length of the string // Space Complexity: O(N), where N = the true length of the string in the hashmap function isAlpha(char) { return /[_a-zA-Z]/.test(char); } function buildMapOsChars(string) { const charsMap = new Map(); const downcasedString = string.toLowerCase(); for (let char of downcasedString) { if (!isAlpha(char)) continue; if (charsMap.has(char)) charsMap.set(char, charsMap.get(char) + 1); else charsMap.set(char, 1); } return charsMap; } export function palindromePermutation(string) { let charsMap = buildMapOsChars(string); let numberOfCharsWithOneCount = 0; for (let [_, count] of charsMap.entries()) { numberOfCharsWithOneCount += count % 2; } return numberOfCharsWithOneCount <= 1; } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/palindrome-permutation/palindrome-permutation.test.js ================================================ import { describe, expect, it } from 'vitest'; import { palindromePermutation } from './palindrome-permutation'; describe('palindromePermutation', () => { it('', () => { expect(palindromePermutation('Tact Coa')).toEqual(true); }); it('', () => { expect(palindromePermutation('tat')).toEqual(true); }); it('', () => { expect(palindromePermutation('abcd')).toEqual(false); }); it('', () => { expect(palindromePermutation('tactfcoa')).toEqual(false); }); it('', () => { expect(palindromePermutation('tactfffcoa')).toEqual(false); }); }); ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.01.py ================================================ ''' Is Unique: Implement an algorithm to determine if a string has all unique characters. What if you cannot use additional data structures? - Examples: abc => True aaa => False abcdefghij => True abcdefghia => False Some questions: - Could the string be an empty string? - What's the memory constraints? ''' # First approach using Hash Map def all_unique_characters(string): characters_counter = {} for char in string: if char in characters_counter: characters_counter[char] += 1 else: characters_counter[char] = 1 for char, counter in characters_counter.items(): if counter > 1: return False return True print(all_unique_characters('abc')) print(all_unique_characters('aaa')) print(all_unique_characters('abcdefghij')) print(all_unique_characters('abcdefghia')) # Second approach using Set def all_unique_characters(string): unique_chars = set() for char in string: unique_chars.add(char) return len(unique_chars) == len(string) print(all_unique_characters('abc')) print(all_unique_characters('aaa')) print(all_unique_characters('abcdefghij')) print(all_unique_characters('abcdefghia')) ''' Both approaches are: - Space: O(N) - Time: O(N) ''' ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.02.py ================================================ ''' Check Permutation: Given two strings, write a method to decide if one is a permutation of the other. - Examples: "abc" "bca" => True "abc" "bca" => True "abc" "aab" => False "abc" "baca" => False Questions: - Do the strings have the same length? ''' def permutation(str1, str2): if len(str1) != len(str2): return False return sorted(str1) == sorted(str2) print(permutation("abc", "bca")) print(permutation("abc", "bca")) print(permutation("abc", "aab")) print(permutation("abc", "baca")) ''' This is: - Space: O(1) (no new storage of the string) - Time: O(NlogN) (because of the sorting) ''' def permutation(str1, str2): if len(str1) != len(str2): return False first_set = set() second_set = set() for char in str1: first_set.add(char) for char in str2: second_set.add(char) return first_set == second_set print(permutation("abc", "bca")) print(permutation("abc", "bca")) print(permutation("abc", "aab")) print(permutation("abc", "baca")) ''' This is: - Space: O(N) (for each string we have a new set with N places - N is equal to the string length) - Time: O(N) (just the str1 and str2 iteration) ''' def permutation(str1, str2): if len(str1) != len(str2): return False characters = {} for char in str1: if char in characters: characters[char] += 1 else: characters[char] = 1 for char in str2: if char not in characters or characters[char] == 0: return False characters[char] -= 1 return True print(permutation("abc", "bca")) print(permutation("abc", "bca")) print(permutation("abc", "aab")) print(permutation("abc", "baca")) ''' This is: - Space: O(N) (new dictionary for the first string with N places - N is equal to the string length) - Time: O(N) (just the str1 and str2 iteration) ''' ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.03.py ================================================ ''' URLify: Write a method to replace all spaces in a string with '%20'. You may assume that the string has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string. Example: Input: "Mr John Smith ", 13 Output: "Mr%20John%20Smith" ''' def urlify(string, length): original_string = string[0:length] chars = [] for char in original_string: if char is " ": chars.append("%20") else: chars.append(char) return "".join(chars) result = urlify("Mr John Smith ", 13) # => "Mr%20John%20Smith" print(result) result = urlify("Mr John Smith ", 14) # => "Mr%20John%20Smith%20" print(result) ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.04.py ================================================ ''' Palindrome Permutation: Given a string, write a function to check if it is a permutation of a palindrome. A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters. The palindrome does not need to be limited to just dictionary words. Example Input: Tact Coa Output: True (permutations: "taco cat", "atco eta", etc.) ''' def is_even(number): return number % 2 == 0 def is_even_length(string): return is_even(len(string)) def is_palindrome_permutation(string): string = string.lower() string = "".join(string.split()) even = is_even_length(string) char_counter = {} odd = 0 for char in string: if char in char_counter: char_counter[char] += 1 else: char_counter[char] = 1 for char, counter in char_counter.items(): if not is_even(counter): odd += 1 return (even and odd == 0) or (not even and not is_even(odd)) result = is_palindrome_permutation('Tact Coa') print(result) # True result = is_palindrome_permutation('Tac Coa') print(result) # False result = is_palindrome_permutation('Tac Tac') print(result) # True data = [ ('Tact Coa', True), ('Tac Coa', False), ('Tac Tac', True) ] for [string, expected] in data: actual = is_palindrome_permutation(string) print(actual == expected) ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.05.py ================================================ ''' One Away: There are three types of edits that can be performed on strings: insert a character, remove a character, or replace a character. Given two strings, write a function to check if they are one edit (or zero edits) away. Example: pale, ple -> true pales, pale -> true pale, bale -> true pale, bake -> false bla, bleble -> false ''' def is_two_chars_away(str1, str2): return (len(str1) - len(str2) >= 2) or (len(str2) - len(str1) >= 2) def number_of_needed_changes(bigger_str, smaller_str): str_counter = {} for char in bigger_str: if char in str_counter: str_counter[char] += 1 else: str_counter[char] = 1 for char in smaller_str: if char in str_counter: str_counter[char] -= 1 needed_changes = 0 for char, counter in str_counter.items(): needed_changes += counter return needed_changes def one_away(str1, str2): if is_two_chars_away(str1, str2): return False needed_changes = 0 if len(str1) >= len(str2): needed_changes = number_of_needed_changes(str1, str2) else: needed_changes = number_of_needed_changes(str2, str1) return needed_changes <= 1 data = [ ('pale', 'ple', True), ('pales', 'pale', True), ('pale', 'bale', True), ('paleabc', 'pleabc', True), ('pale', 'ble', False), ('a', 'b', True), ('', 'd', True), ('d', 'de', True), ('pale', 'pale', True), ('pale', 'ple', True), ('ple', 'pale', True), ('pale', 'bale', True), ('pale', 'bake', False), ('pale', 'pse', False), ('ples', 'pales', True), ('pale', 'pas', False), ('pas', 'pale', False), ('pale', 'pkle', True), ('pkle', 'pable', False), ('pal', 'palks', False), ('palks', 'pal', False), ('bla', 'bleble', False) ] for [test_s1, test_s2, expected] in data: actual = one_away(test_s1, test_s2) print(actual == expected) ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.06.py ================================================ ''' String Compression: Implement a method to perform basic string compression using the counts of repeated characters. For example, the string aabcccccaaa would become a2b1c5a3. If the "compressed" string would not become smaller than the original string, our method should return the original string. You can assume the string has only uppercase and lowercase letters (a - z). ''' def string_compression(string): if string is '': return '' counter = 1 current_char = string[0] compressed_string = [] for char in string[1:]: if char == current_char: counter += 1 else: compressed_string.append(current_char) compressed_string.append(str(counter)) current_char = char counter = 1 compressed_string.append(current_char) compressed_string.append(str(counter)) return ''.join(compressed_string) test_cases = [ ('Aa', 'A1a1'), ('aabcccccaaa', 'a2b1c5a3'), ('', ''), ('abcdef', 'a1b1c1d1e1f1') ] for [string, expected] in test_cases: actual = string_compression(string) print(actual == expected) ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/001.07.py ================================================ ''' Rotate Matrix: Given an image represented by an NxN matrix, where each pixel in the image is 4 bytes, write a method to rotate the image by 90 degrees. Can you do this in place? ''' ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/bottlenecks.py ================================================ ''' Example: Given an array of distinct integer values, count the number of pairs of integers that have difference k. For example, given the array { 1, 7, 5, 9, 2, 12, 3 } and the difference k = 2,there are four pairs with difference2: (1, 3), (3, 5), (5, 7), (7, 9). ''' def pairs_of_difference(array, diff): hash_table = {} for num in array: hash_table[num] = num count = 0 for num in array: if num + diff in hash_table: count += 1 if num - diff in hash_table: count += 1 return count // 2 print(pairs_of_difference([1, 7, 5, 9, 2, 12, 3], 2)) ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/python/is_unique.py ================================================ import time import unittest from collections import defaultdict def is_unique_chars_using_dictionary(text): char_counter = {} for char in text: if char in char_counter: return False else: char_counter[char] = 1 return True class Test(unittest.TestCase): test_cases = [ ("abcd", True), ("s4fad", True), ("", True), ("23ds2", False), ("hb 627jh=j ()", False), ("".join([chr(val) for val in range(128)]), True), # unique 128 chars ("".join([chr(val // 2) for val in range(129)]), False), # non-unique 129 chars ] test_functions = [ is_unique_chars_using_dictionary, # is_unique_chars_sorting, ] def test_is_unique_chars(self): num_runs = 1000 function_runtimes = defaultdict(float) for _ in range(num_runs): for text, expected in self.test_cases: for is_unique_chars in self.test_functions: start = time.perf_counter() assert ( is_unique_chars(text) == expected ), f"{is_unique_chars.__name__} failed for value: {text}" function_runtimes[is_unique_chars.__name__] += ( time.perf_counter() - start ) * 1000 print(f"\n{num_runs} runs") for function_name, runtime in function_runtimes.items(): print(f"{function_name}: {runtime:.1f}ms") if __name__ == "__main__": unittest.main() ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/string-compression/string-compression.js ================================================ // String Compression: Implement a method to perform basic string compression using the counts of repeated characters. // For example, the string `aabcccccaaa` would become `a2b1c5a3`. // If the "compressed" string would not become smaller than the original string, your method should return the original string. // You can assume the string has only uppercase and lowercase letters (a-z) function compress(chars) { let index = 0, p1 = 0; while (p1 < chars.length) { let p2 = p1; while (p2 < chars.length && chars[p1] === chars[p2]) { p2++; } let count = p2 - p1; chars[index++] = chars[p1]; if (count > 1) { let countString = count.toString(); for (let char of countString) { chars[index++] = char; } } p1 = p2; } return chars; } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/urlify/urlify.js ================================================ // URLlify: Write a method to replace all spaces in a string with '%20'. // You may assume that the string has sufficient space at the end to hold the additional characters, // and that you are given the "true" length of the string // Runtime Complexity: O(N), where N = the true length of the string // Space Complexity: O(N), where N = the true length of the string in the new array export function urlify(string, length, placeholder = '%20') { let output = []; let lastChar = ''; let space = ' '; for (let index = 0; index < length; index++) { let char = string[index]; if (char !== space) { output.push(char); } if (char === space && lastChar !== space) { output.push(placeholder); } lastChar = char; } return output.join(''); } // Runtime Complexity: O(N), where N = the true length of the string // Space Complexity: O(N), where N = the true length of the string in the new array export function urlifyForward(string, length, placeholder = '%20') { let output = []; let index = 0; let space = ' '; const moveForward = () => { while (string[index] === space) { index++; } }; while (index < length) { if (string[index] === space) { output.push(placeholder); moveForward(); } else { output.push(string[index]); index++; } } return output.join(''); } ================================================ FILE: coding_interviews/cracking-the-coding-interview/chapter-001/urlify/urlify.test.js ================================================ import { describe, expect, it } from 'vitest'; import { urlify, urlifyForward } from './urlify'; describe('urlify', () => { it('', () => { expect(urlify('Mr John Smith ', 13)).toEqual('Mr%20John%20Smith'); }); }); describe('urlifyForward', () => { it('', () => { expect(urlifyForward('Mr John Smith ', 13)).toEqual( 'Mr%20John%20Smith' ); }); }); ================================================ FILE: coding_interviews/daily_code_problems/001.py ================================================ """ Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. """ def found_sum_of_two_numbers_brute_force(k, numbers): for index_1 in range(len(numbers)): for index_2 in range(index_1, len(numbers)): if numbers[index_1] + numbers[index_2] == k: return True return False def found_sum_of_two_numbers(k, numbers): start = 0 end = len(numbers) - 1 sorted_numbers = sorted(numbers) while start < end: if sorted_numbers[start] + sorted_numbers[end] == k: return True elif sorted_numbers[start] + sorted_numbers[end] > k: end -= 1 else: start += 1 return False def test_algorithm(k, numbers): print('Brute force:', found_sum_of_two_numbers_brute_force(k, numbers)) print('Optmized:', found_sum_of_two_numbers(k, numbers)) print() test_algorithm(17, [10, 15, 3, 7]) test_algorithm(17, [15, 10, 3, 7]) test_algorithm(17, [15, 10, 3, 8]) ================================================ FILE: coding_interviews/daily_code_problems/002.py ================================================ """ Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]. """ from functools import reduce def product_with_exception(integers): product_of_all = reduce((lambda product, item: product * item), integers) return list(map(lambda item: product_of_all / item, integers)) def test_product_with_exception(integers, result): print(product_with_exception(integers) == result) test_product_with_exception([1, 2, 3, 4, 5], [120, 60, 40, 30, 24]) test_product_with_exception([3, 2, 1], [2, 3, 6]) test_product_with_exception( [-20, 20, 50, 10], [10000, -10000, -4000, -20000]) ================================================ FILE: coding_interviews/daily_code_problems/003.py ================================================ ''' Given the root to a binary tree, implement serialize(root), which serializes the tree into a string, and deserialize(s), which deserializes the string back into the tree. For example, given the following Node class class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right The following test should pass: node = Node('root', Node('left', Node('left.left')), Node('right')) assert deserialize(serialize(node)).left.left.val == 'left.left' serialize --> 'root' 'left' 'left.left' 'right' deserialize --> Node('root', Node('left', Node('left.left')), Node('right')) ''' from queue import Queue class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def serialize(node): if node is None: return 'X ' return node.val + ' ' + serialize(node.left) + serialize(node.right) def deserialize_node(nodes): value = nodes.get() if value == 'X': return None node = Node(value) node.left = deserialize_node(nodes) node.right = deserialize_node(nodes) return node def create_nodes_queue(string): nodes = string.split(' ') queue = Queue() for node in nodes: queue.put(node) return queue def deserialize(string): string = string.strip() nodes = create_nodes_queue(string) return deserialize_node(nodes) def pre_order(tree): if tree is None: return print(tree.val) pre_order(tree.left) pre_order(tree.right) node = Node('root', Node('left', Node('left.left')), Node('right')) serialized_node = serialize(node) print(serialized_node) tree = deserialize(serialized_node) print(pre_order(tree)) ================================================ FILE: coding_interviews/daily_code_problems/004.py ================================================ ''' Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. ''' # using a hash table: linear time and linear space def get_lowest(lowest, present_numbers): while lowest in present_numbers: lowest += 1 return lowest def lowest_positive_integer(numbers): present_numbers = {} lowest = 1 for number in numbers: present_numbers[number] = True return get_lowest(lowest, present_numbers) result = lowest_positive_integer([3, 4, -1, 1]) print(result) result = lowest_positive_integer([3, 4, 2, -1, 1]) print(result) result = lowest_positive_integer([5, 4, 2, -1, 1]) print(result) ================================================ FILE: coding_interviews/daily_code_problems/005.py ================================================ ''' cons(a, b) constructs a pair, and car(pair) and cdr(pair) returns the first and last element of that pair. For example, car(cons(3, 4)) returns 3, and cdr(cons(3, 4)) returns 4. Given this implementation of cons: def cons(a, b): def pair(f): return f(a, b) return pair Implement car and cdr. ''' def cons(a, b): def pair(f): return f(a, b) return pair def list_pair(a, b): return [a, b] def car(pair): [a, _] = pair(list_pair) return a def cdr(pair): [_, b] = pair(list_pair) return b a = 1 b = 2 result = car(cons(a, b)) print(result) result = cdr(cons(a, b)) print(result) ================================================ FILE: coding_interviews/daily_code_problems/006.py ================================================ ''' An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. ''' ================================================ FILE: coding_interviews/daily_code_problems/007.py ================================================ ''' Given the mapping a = 1, b = 2, ... z = 26, and an encoded message, count the number of ways it can be decoded. For example, the message '111' would give 3, since it could be decoded as 'aaa', 'ka', and 'ak'. You can assume that the messages are decodable. For example, '001' is not allowed. ''' def count_decoded_possibilities(encoded_message): pass count = count_decoded_possibilities('111') print(count) # 3 - 'aaa', 'ka', and 'ak' count = count_decoded_possibilities('121') print(count) # 3 - 'aba', 'la', 'au' ================================================ FILE: coding_interviews/daily_code_problems/README.md ================================================ # Daily Code Problem - [001](001.py) - [002](002.py) - [003](003.py) - [004](004.py) - [005](005.py) - [006](006.py) - [007](007.py) Problems: https://www.dailycodingproblem.com ================================================ FILE: coding_interviews/elements_of_programming_interview/array.py ================================================ # Your input is an array of # integers, and you have to reorder its entries # so that the even entries appear first. def even_before_odd(numbers): next_even, next_odd = 0, len(numbers) while next_even < next_odd: if numbers[next_even] % 2 == 0: next_even += 1 else: numbers[next_even], numbers[next_odd] = numbers[next_odd], numbers[next_even] next_odd -= 1 ## With this solution, we have a O(1) space complexity and O(N) time complexity ================================================ FILE: coding_interviews/elements_of_programming_interview/base_conversion.py ================================================ ''' "615" "5" --> 5 --> 5 * (7 ** 0) "1" --> 1 --> 1 * (7 ** 1) "6" --> 6 --> 6 * (7 ** 2) => 306 306 % 13 = 7 306 / 13 = 23 23 % 13 = 10 23 / 13 = 1 1 % 13 = 1 ''' num_representation = { 10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F', } def to_num_representation(num): if num < 10: return str(num) return num_representation[num] def base_conversion(string_num, base1, base2): decimal = 0 reversed_string_num = string_num[::-1] for index in range(len(reversed_string_num)): char_num = reversed_string_num[index] decimal += int(char_num) * (base1 ** index) digits = [] while decimal: modulo = decimal % base2 decimal = decimal // base2 digits.append(to_num_representation(modulo)) return ''.join(digits)[::-1] print(base_conversion("615", 7, 13)) ================================================ FILE: coding_interviews/elements_of_programming_interview/buy_and_sell_stock_once.py ================================================ # Buy and Sell stoks once def buy_and_sell_stock_once(prices): if not prices: return 0 min_price, max_profit = float('inf'), 0.0 for price in prices: profit_if_sell_today = price - min_price max_profit = max(max_profit, profit_if_sell_today) min_price = min(min_price, price) return max_profit prices = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250] print(buy_and_sell_stock_once(prices)) print(buy_and_sell_stock_once([])) ================================================ FILE: coding_interviews/elements_of_programming_interview/can_reach_end.py ================================================ """ In a particular board game, a player has to try to advance through a sequence of positions. Each position has a nonnegative integer associated with it, representing the maximum you can advance from that position in one move. You begin in the first position and win by getting to the last position. For example, let A = (3,3,1,0,2,0,1) represent the board game, i.e., the lth entry in A is the maximum we can advance from L Then the game can be won by the following sequence of advances through A: take 1 step from A[0] to A[1], then 3 steps from A[1] to A[4], then 2 steps from A[4] to A[6], which is the last position. Note that A[0] = 3 >= 1, A[1] =3 >= 3, and A[4] = 2 >= 2, so all moves are valid. If A instead was (3,2,0,0,2,0,1), it would not be possible to advance past position 3, so the game cannot be won. Write a program that takes an array of n integers, where A[i] denotes the maximum you can advance from the index i, and returns whether it is possible to advance to the last index starting from the beginning of the array. """ def can_reach_end(board_game): furthest_reach_so_far, last_index = 0, len(board_game) - 1 current_index = 0 while current_index <= furthest_reach_so_far and furthest_reach_so_far < last_index: furthest_reach_so_far = max(furthest_reach_so_far, board_game[current_index] + current_index) current_index += 1 return furthest_reach_so_far >= last_index print(can_reach_end([3, 3, 7, 0, 2, 0, 1])) print(can_reach_end([2, 4, 1, 1, 0, 2, 3])) print(can_reach_end([3, 2, 0, 0, 2, 0, 1])) ================================================ FILE: coding_interviews/elements_of_programming_interview/delete_duplicates_from_a_sorted_array.py ================================================ # input: [2,3,5,5,7,11,11,11,13] # output: [2,3,5,7,11,13,0,0,0] # input: [-2,-2,1] # output: [-2,1,0] # input: [0,0,1,1] # output: [0,1,0,0] ''' result = [] counter = {} loop input is not in the counter counter[number] << True result << number n = len(input) - len(result) loop n result << 0 return result Space: O(2N) = O(N) Runtime: O(N) ''' def delete_duplicates(numbers): if not numbers: return [[], 0] result = [] counter_mapper = {} counter = 0 for number in numbers: if number not in counter_mapper: counter_mapper[number] = True result.append(number) counter += 1 difference_of_lengths = len(numbers) - len(result) for _ in range(difference_of_lengths): result.append(0) return [result, counter] def test(input, expect): print(delete_duplicates(input) == expect) test([2,3,5,5,7,11,11,11,13], [[2,3,5,7,11,13,0,0,0],6]) test([-2,-2,1], [[-2,1,0],2]) test([0,0,1,1], [[0,1,0,0],2]) test([], [[],0]) def delete_duplicates_2(numbers): counter = 1 if not numbers: return [[], 0] for index in range(1, len(numbers)): if numbers[index - 1] != numbers[index]: numbers[counter] = numbers[index] counter += 1 difference_of_lengths = len(numbers) - counter for index in range(difference_of_lengths): numbers[len(numbers) - index - 1] = 0 return [numbers, counter] def test_2(input, expect): print(delete_duplicates(input) == expect) test_2([2,3,5,5,7,11,11,11,13], [[2,3,5,7,11,13,0,0,0],6]) test_2([-2,-2,1], [[-2,1,0],2]) test_2([0,0,1,1], [[0,1,0,0],2]) test_2([], [[],0]) ================================================ FILE: coding_interviews/elements_of_programming_interview/interconvert_string_and_integer.py ================================================ # Interconvert String and Integer ''' "123" => 123 "-123" => -123 ''' def to_int(string): sign = 1 if string[0] == '-': sign = -1 string = string[1:] integer = 0 reversed_string = string[::-1] for index in range(len(string)): int_char = reversed_string[index] digit = ord(int_char) - 48 integer += (digit * 10 ** index) return integer * sign print(to_int('123')) print(to_int('-123')) ''' 123 => "123" -123 => "-123" ''' def to_string(integer): sign = '' if integer < 0: sign = '-' abs_integer = abs(integer) digits = [] while abs_integer > 0: digits.append(chr(ord('0') + abs_integer % 10)) abs_integer = abs_integer // 10 return sign + ''.join(digits[::-1]) print(to_string(123)) print(to_string(-123)) ================================================ FILE: coding_interviews/elements_of_programming_interview/longest_subarray_length_with_same_integers.py ================================================ ''' Write a program that takes an array of integers and finds the length of a longest subarray all of whose entries are equal. ''' def longest_subarray_length_with_same_integers(numbers): if not numbers: return 0 longest_subarray_length, counter, current_comparator = 0, 0, numbers[0] for number in numbers: if number == current_comparator: counter += 1 else: counter = 1 current_comparator = number longest_subarray_length = max(longest_subarray_length, counter) return longest_subarray_length numbers = [260, 290, 290, 250, 250, 250] prices = [310, 315, 275, 295, 260, 270, 290, 230, 255, 250] print(longest_subarray_length_with_same_integers(numbers)) print(longest_subarray_length_with_same_integers(prices)) print(longest_subarray_length_with_same_integers([])) ================================================ FILE: coding_interviews/elements_of_programming_interview/multiply_two_arbitrary_precision_integers.py ================================================ # Write a program that takes two arrays representing integers, # and retums an integer representing their product """ 1234 4321 result1 = 1 x 4 + 1 x 3 x 10 + 1 x 2 x 100 + 1 x 1 x 1000 result2 = ... result3 = ... result4 = ... result = result1 + result2 + result3 + result4 """ def multiply_two_arbitrary_precision_integers(int1, int2): result = 0 for integer in int1: for index in range(len(int2)): result += integer * int2[len(int2) - 1 - index] * pow(10, index) return result print(multiply_two_arbitrary_precision_integers([1,9,3,7,0,7,7,2,1], [-7,6,1,8,3,8,2,5,7,2,8,7])) ================================================ FILE: coding_interviews/elements_of_programming_interview/spreadsheet_column_encoding.py ================================================ encoding_mapper = { 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10, 'K': 11, 'L': 12, 'M': 13, 'N': 14, 'O': 15, 'P': 16, 'Q': 17, 'R': 18, 'S': 19, 'T': 20, 'U': 21, 'V': 22, 'W': 23, 'X': 24, 'Y': 25, 'Z': 26, } def spreadcheet_column_encoding(encoding): number, reversed_encoding = 0, encoding[::-1] for index in range(len(reversed_encoding)): number += (26 ** index) * (encoding_mapper[reversed_encoding[index]]) return number ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/hash_tables/count_triplets.py ================================================ # https://www.hackerrank.com/challenges/count-triplets-1/problem?h_l=interview&h_r=next-challenge&h_r%5B%5D%5B%5D%5B%5D=next-challenge&h_r%5B%5D%5B%5D%5B%5D=next-challenge&h_v=zen&h_v%5B%5D%5B%5D%5B%5D=zen&h_v%5B%5D%5B%5D%5B%5D=zen&isFullScreen=true&playlist_slugs%5B%5D%5B%5D%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D%5B%5D%5B%5D=dictionaries-hashmaps #!/bin/python3 import math import os import random import re import sys from collections import Counter def count_triplets(arr, r): number_counter = Counter(arr) prev_counter = Counter() triplets = 0 for number in arr: prev = number // r next_num = number * r number_counter[number] -= 1 if prev_counter[prev] and number_counter[next_num] and number % r == 0: triplets += prev_counter[prev] * number_counter[next_num] prev_counter[number] += 1 return triplets if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') nr = input().rstrip().split() n = int(nr[0]) r = int(nr[1]) arr = list(map(int, input().rstrip().split())) ans = count_triplets(arr, r) fptr.write(str(ans) + '\n') fptr.close() ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/hash_tables/ransom_note.py ================================================ # https://www.hackerrank.com/challenges/ctci-ransom-note/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps #!/bin/python3 import math import os import random import re import sys def build_word_counter(magazine): word_counter = {} for word in magazine: if word in word_counter: word_counter[word] += 1 else: word_counter[word] = 1 return word_counter def check_notes_on_magazine(word_counter, note): for word in note: if word in word_counter and word_counter[word] > 0: word_counter[word] -= 1 else: print('No') return print('Yes') def check_magazine(magazine, note): word_counter = build_word_counter(magazine) check_notes_on_magazine(word_counter, note) if __name__ == '__main__': first_multiple_input = input().rstrip().split() m = int(first_multiple_input[0]) n = int(first_multiple_input[1]) magazine = input().rstrip().split() note = input().rstrip().split() check_magazine(magazine, note) ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/hash_tables/sherlock_and_anagrams.py ================================================ # https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem?h_l=interview&h_r%5B%5D=next-challenge&h_r%5B%5D=next-challenge&h_v%5B%5D=zen&h_v%5B%5D=zen&playlist_slugs%5B%5D%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D%5B%5D=dictionaries-hashmaps&isFullScreen=true def sherlock_and_anagrams(s): substrings = {} for i in range(0, len(s) - 1): for index in range(0, len(s) - i): sorted_substring = ''.join(sorted(s[index:index+i+1])) if sorted_substring in substrings: substrings[sorted_substring] += 1 else: substrings[sorted_substring] = 1 count_anagrams = 0 for _, count in substrings.items(): if count > 0: count_anagrams += (count * (count - 1) // 2) return count_anagrams print(sherlock_and_anagrams('abba')) print(sherlock_and_anagrams('ifailuhkqq')) print(sherlock_and_anagrams('kkkk')) print(sherlock_and_anagrams('ifailuhkqqhucpoltgtyovarjsnrbfpvmupwjjjfiwwhrlkpekxxnebfrwibylcvkfealgonjkzwlyfhhkefuvgndgdnbelgruel')) ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/hash_tables/two_strings.py ================================================ # https://www.hackerrank.com/challenges/two-strings/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=dictionaries-hashmaps&h_r=next-challenge&h_v=zen #!/bin/python3 import math import os import random import re import sys def two_strings(s1, s2): chars_presence = {} for char in s1: if char not in chars_presence: chars_presence[char] = True for char in s2: if char in chars_presence: return 'YES' return 'NO' if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') q = int(input().strip()) for q_itr in range(q): s1 = input() s2 = input() result = two_strings(s1, s2) fptr.write(result + '\n') fptr.close() ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/warmup/counting_valleys.py ================================================ # https://www.hackerrank.com/challenges/counting-valleys/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen #!/bin/python3 import math import os import random import re import sys def counting_valleys(steps, path): valleys_count, level = 0, 0 for step in path: if step == 'U': level += 1 if level == 0: valleys_count += 1 else: level -= 1 return valleys_count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') steps = int(input().strip()) path = input() result = counting_valleys(steps, path) fptr.write(str(result) + '\n') fptr.close() ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/warmup/jumping_on_the_clouds.py ================================================ # https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen #!/bin/python3 import math import os import random import re import sys def won_the_game(current, end_game): return current == end_game def is_cumulus(cloud): return cloud == 0 def jumping_on_clouds(c): current, jumps, end_game = 0, 0, len(c) - 1 while not won_the_game(current, end_game): if current + 2 <= end_game and is_cumulus(c[current + 2]): current += 2 else: current += 1 jumps += 1 return jumps if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) c = list(map(int, input().rstrip().split())) result = jumping_on_clouds(c) fptr.write(str(result) + '\n') fptr.close() ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/warmup/repeated_string.py ================================================ # https://www.hackerrank.com/challenges/repeated-string/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen&h_r=next-challenge&h_v=zen #!/bin/python3 import math import os import random import re import sys # # aba => 2 # n = 10 # abaabaabaa => 7 # 10 / len(s) => 3 # 10 % len(s) => 1 # 2 * 3 + 1 def repeatedString(s, n): count_as = 0 for char in s: if char == 'a': count_as += 1 times = n // len(s) remaining = n % len(s) count_as = count_as * times for index in range(0, remaining): if s[index] == 'a': count_as += 1 return count_as if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') s = input() n = int(input().strip()) result = repeatedString(s, n) fptr.write(str(result) + '\n') fptr.close() ================================================ FILE: coding_interviews/hackerrank_interview_prep_kit/warmup/sales_by_match.py ================================================ # https://www.hackerrank.com/challenges/sock-merchant/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=warmup #!/bin/python3 import math import os import random import re import sys def sock_merchant(n, ar): counter = {} for num in ar: if num in counter: counter[num] += 1 else: counter[num] = 1 count = 0 for _, num_count in counter.items(): count += num_count // 2 return count if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') n = int(input().strip()) ar = list(map(int, input().rstrip().split())) result = sock_merchant(n, ar) fptr.write(str(result) + '\n') fptr.close() ================================================ FILE: coding_interviews/interviews/fair/decrementBinaryNumber.js ================================================ function countOnes(number) { let counter = 0; number.split('').forEach((char) => { if (char === '1') counter++; }); return counter; } function toBinary(number) { return number.toString(2); } function toDecimal(number) { return parseInt(number, 2); } function decrementBinary(number) { return toBinary(toDecimal(number) - 1); } function decrementBinaryNumber(number, requests) { const answer = []; requests.forEach((request) => { if (request === '?') { answer.push(countOnes(number)); } else { number = decrementBinary(number); } }); return answer; } ================================================ FILE: coding_interviews/interviews/fair/diceTotalScore.js ================================================ function diceTotalScore(a, b, c) { if (a === b && b === c) { return 1000 * a; } if (a === b) { return 500 * a; } if (a === c) { return 500 * a; } if (b === c) { return 500 * b; } return 100 * Math.min(a, b, c); } ================================================ FILE: coding_interviews/interviews/fair/isSubmatrixFull.js ================================================ function isSubmatrixFull(numbers) { const answer = []; for (let i = 0; i < numbers[0].length - 2; i++) { const subMatrixNumbers = new Set(); for (let row = 0; row < 3; row++) { for (let col = i; col < i + 3; col++) { subMatrixNumbers.add(numbers[row][col]); } } answer.push(subMatrixNumbers.size === 9); } return answer; } ================================================ FILE: coding_interviews/interviews/fair/sortChessSubsquares.js ================================================ function sortChessSubsquares(numbers, queries) { queries.forEach(([x, y, w]) => { const blacks = []; const whites = []; for (let row = x; row < x + w; row++) { for (let col = y; col < y + w; col++) { if ((row + col) % 2 === 0) { blacks.push(numbers[row][col]); } else { whites.push(numbers[row][col]); } } } whites.sort((a, b) => a - b); blacks.sort((a, b) => a - b); let whiteCounter = 0; let blackCounter = 0; for (let row = x; row < x + w; row++) { for (let col = y; col < y + w; col++) { if ((row + col) % 2 === 0) { numbers[row][col] = blacks[blackCounter]; blackCounter++; } else { numbers[row][col] = whites[whiteCounter]; whiteCounter++; } } } }); return numbers; } ================================================ FILE: coding_interviews/interviews/google/printSequence/printSequence.js ================================================ /* number of rows: 4 number of columns: 5 Print this: 1 8 9 16 17 2 7 10 15 18 3 6 11 14 19 4 5 12 13 20 */ function printSequence(rows, columns) { const matrix = []; for (let row = 0; row < rows; row++) { const matrixRow = []; for (let col = 0; col < columns; col++) { if (col % 2 === 0) { matrixRow.push(col * rows + 1 + row); } else { matrixRow.push((col + 1) * rows - row); } } matrix.push(matrixRow); } return matrix; } console.log(printSequence(4, 5)); console.log(printSequence(6, 6)); ================================================ FILE: coding_interviews/interviews/mercari/cumulativeSum.js ================================================ const cumulativeSum = (arr, sum = 0) => arr.map((number) => { sum += number; return sum; }); cumulativeSum([1, 3, 5, 7]); ================================================ FILE: coding_interviews/interviews/mercari/findMaxMin.js ================================================ const arr = [1, 2, 3, 4, 100]; const findMaxMin = (arr = []) => { let min = Infinity; let max = -Infinity; arr.forEach((number) => { if (number < min) min = number; if (number > max) max = number; }); return { min, max, }; }; findMaxMin(arr); ================================================ FILE: coding_interviews/interviews/mercari/findSumPairs.js ================================================ let arr = [1, 5, 6, 1, 0, 1]; const findSumPairs = (arr, value) => { const lookup = {}; const pairs = []; arr.forEach((number) => { const target = value - number; if (lookup[target]) { pairs.push([number, target]); } lookup[number] = true; }); return pairs; }; findSumPairs(arr, 6); ================================================ FILE: coding_interviews/interviews/mercari/multipleDupesArray.js ================================================ const arr = [1, 1, 2, 3, 4, 5, 6, 7, 8, 6, 6, 7, 7, 7, 10, 10]; const multipleDupesArray = (arr) => { const counter = {}; const duplicates = []; arr.forEach((number) => { if (number in counter) counter[number]++; else counter[number] = 1; }); Object.entries(counter).forEach(([number, count]) => { if (count > 1) duplicates.push(number); }); return duplicates; }; multipleDupesArray(arr); ================================================ FILE: coding_interviews/interviews/mercari/products.js ================================================ // Given the sample response: // data: { // items: [ // { // id: 1, // name: "Nike Shoes", // price: 1000, // status: "on_sale", // photos: [{ large: 'xxx', thumbnail: 'yyy'}, { large: 'xxx', thumbnail: 'yyy'}] // verified: true, // .. // }, // ... // ], // } // get/items // 1. Construct a query which includes name, price, photos, & status // 2. Using the query, bring the data in to RecommendedItems component // 3. Render the UI for the recommended items list // 4. Handle loading and error states within the component import React from 'react'; import useQuery from 'react-query'; const fallBackImg = 'https/....'; const getThumbail = ({ photos }) => (photos[0] && photos[0].thumbail) || fallBackImg; const useItems = (limit) => { const { data } = useQuery(['items'], fetch(`/items?limit=${limit}`)); return data.map((item) => ({ ...item, thumbnail: getThumbail(item), })); }; // items styles // toCurrency() function Item({ name, price, thumbnail }) { return ( <> {name}

{name}

{toCurrency(price)}

); } const WithLoadingErrorAndData = ({ isLoading, isError, children }) => { if (isLoading) return ; if (isError) return ; return children; }; // Component function RecommendedItems({ limit, component }) { const { data, isLoading, isError } = useItems(limit); return ( {data.items.map((item) => ( ))} ); } ================================================ FILE: coding_interviews/interviews/mercari/removeDupes.js ================================================ const arr = [1, 1, 1, 1, 1, 1, 1]; const removeDupes = (arr) => [...new Set(arr)]; removeDupes(arr); ================================================ FILE: coding_interviews/interviews/mercari/retries.js ================================================ /* Implement a retryAsync function that will call an asynchronous function and then * recall it again on failure until a max number of retries has been reached. * The function receives the asynchronous function and the maximum number of retries * The function should return the result of the async function and throw an error * after the maximum number of retries */ // Update the following function const retryAsync = async (asyncFunc, maxRetries) => { try { return await asyncFunc(); } catch (error) { if (maxRetries > 0) { return await retryAsync(asyncFunc, maxRetries - 1); } else { throw new Error('error'); } } }; // Usage Example - DO NOT MODIFY const main = async () => { const myPromise = () => new Promise((resolve, reject) => { setTimeout(() => { reject('Promise Failed'); }, 3000); }); const res = await retryAsync(myPromise, 3); return res; }; main(); ================================================ FILE: coding_interviews/interviews/meta/compareLettersInArray/compareLettersInArray.js ================================================ function hasSameLength(words, letters) { return words.length !== letters.length; } function isArray(arr) { return Array.isArray(arr); } function bothArrays(words, letters) { return isArray(words) && isArray(letters); } function compareLettersInArray(words, letters) { if (hasSameLength(words, letters) || !bothArrays(words, letters)) { return false; } let firstLetterMatches = true; for (let i = 0; i < words.length; i++) { if (words[i][0] !== letters[i]) { firstLetterMatches = false; break; } } return firstLetterMatches; } const words = ['ant', 'bear', 'vulture', 'viper', 'deer']; const letters = ['a', 'b', 'c', 'd', 'e']; console.log('answer', compareLettersInArray(words, letters)); console.log('answer', compareLettersInArray(words, ['a', 'b', 'v', 'v', 'd'])); ================================================ FILE: coding_interviews/interviews/meta/flatten/flatten.js ================================================ // [1, [2, [ [3, 4], 5], 6]] => [1, 2, 3, 4, 5, 6] function flatten(arr) { const flatArray = []; arr.forEach((element) => { if (Number.isInteger(element)) { flatArray.push(element); } else { flatArray.push(...flatten(element)); } }); return flatArray; } const flatArray = flatten([1, [2, [[3, 4], 5], 6]]); console.log(flatArray, [1, 2, 3, 4, 5, 6]); ================================================ FILE: coding_interviews/interviews/meta/flatten/flatten2.js ================================================ // [1, [2, null, true, [ [3, 'NaN', 4, undefined], 5], false, 6, '7']] => [1, 2, 3, 4, 5, 6] function isString(str) { return typeof str === 'string' || str instanceof String; } function flatten(arr) { const flatArray = []; arr.forEach((element) => { if (Number.isInteger(element)) { flatArray.push(element); } if (element instanceof Array) { flatArray.push(...flatten(element)); } if (isString(element)) { const numberValue = Number(element); if (Number.isInteger(numberValue)) { flatArray.push(numberValue); } } }); return flatArray; } const flatArray = flatten([ 1, [2, null, true, [[3, 'NaN', 4, undefined], 5], false, 6, '7'], ]); console.log(flatArray, [1, 2, 3, 4, 5, 6, 7]); ================================================ FILE: coding_interviews/interviews/quintoandar/quinto1.py ================================================ def group_by(parsed_phone, number): numbers_of_characters = len(parsed_phone) result_list = [] for i in range(0, numbers_of_characters, number): result_list.append(parsed_phone[i:i+number]) return result_list S = "00-44 48 5555 8361" parsed_phone = S.strip().replace("-", "").replace(" ", "") numbers_of_characters = len(parsed_phone) if numbers_of_characters % 3 == 0 || numbers_of_characters % 3 == 2: return '-'.join(group_by(parsed_phone, 3)) else: grouped_by_three = group_by(parsed_phone[0:numbers_of_characters-4], 3) grouped_by_two = group_by(parsed_phone[numbers_of_characters-4:], 2) return '-'.join(grouped_by_three + grouped_by_two) ================================================ FILE: coding_interviews/interviews/quintoandar/quinto2.py ================================================ A = [0,3,3,7,5,3,11,1] tuple_a = [(index, el) for index, el in enumerate(A)] sorted_tuple = sorted(tuple_a, key=lambda x: x[1]) dual = [] for index, el in enumerate(range(len(sorted_tuple) - 1)): result = (sorted_tuple[index], sorted_tuple[index+1]) dual.append(result) smaller_distance = 1000000000 for d in dual: indice1, indice2 = d[0][0], d[1][0] value1, value2 = d[0][1], d[1][1] if indice1 < indice2: if abs(value1 - value2) < smaller_distance: smaller_distance = abs(value1 - value2) else: if abs(value2 - value1) < smaller_distance: smaller_distance = abs(value2 - value1) if smaller_distance == 1000000000: print(-1) else: print(smaller_distance) ================================================ FILE: coding_interviews/interviews/quintoandar/quinto3.py ================================================ T = [80, 80, 1000000000, 80, 80, 80, 80, 80, 80, 123456789] number_of_shares = int(len(T) / 2) number_of_different_types = len(set(T)) if number_of_different_types < number_of_shares: return number_of_different_types else: return number_of_shares ================================================ FILE: coding_interviews/interviews/quintoandar/regions.js ================================================ // Regions Map // We want to represent our operational area in memory and store it in a database. // The regions will be used in many different ways. We want to be able to manage them and perform different operations on top of them. // They will have a label that needs to be unique // The top-level hierarchy is pre-defined as Country > State > City, // but after City the regions represented could have many different levels: Zones ("Zona Sul"), Neighborhoods ("Moema") or even parts of a Neighborhood. // brasil // ├─ rj // │ ├─ buzios // │ ├─ marica // │ └─ rio-de-janeiro // └─ sp // ├─ ... // ├─ osasco // |- centro // └─ sao-paulo // _- santana // ├─ central // ├─ north // │ ├─ santana // │ └─ tucuruvi // ├─ south // │ ├─ moema // │ └─ vila-mariana // └─ west // ├─ butanta // |- vila indiana // └─ pinheiros area1 = buzios; area2 = rio - de - janeiro; const isDiff = (area1, area2); const isEqual = (area1, area2) => { if (Object.keys(area1).length !== Object.keys(area2).length) { return false; } let result; for (const [key, value] of Object.entries(area1)) { const isObj1 = typeof value === 'object'; const isObj2 = typeof area2[key] === 'object'; if (isObj1 && isObj2) { result = result && isEqual(value, area2[key]); } if (isObj1 && !isObj2) { result = false; break; } if (isObj2 && !isObj1) { result = false; break; } // strings if (value !== area2[key]) { result = false; break; } } return result; }; interface Region { [index: string]: string | Region; } interface City { [index: string]: Region; } interface Country { [index: string]: City; } interface Area { [index: string]: Country; } /** * { * brazil: { * [state]: { * [city]: { * [neighborhood]: string | Map * } * } * } * } **/ ================================================ FILE: coding_interviews/interviews/smartnews/countries.js ================================================ function solution(A) { let countries = buildCountriesMapper(A); let countriesCount = 0; for (let row = 0; row < A.length; row++) { for (let col = 0; col < A[row].length; col++) { const country = A[row][col]; if (!countries[row][col]) countriesCount++; verifyCountry(A, country, row, col, countries); } } return countriesCount; } function buildCountriesMapper(A) { const mapper = []; for (let row = 0; row < A.length; row++) { const line = []; for (let col = 0; col < A[row].length; col++) { line.push(false); } mapper.push(line); } return mapper; } function verifyCountry(A, country, row, col, countries) { if ( row < 0 || col < 0 || row >= A.length || col >= A[row].length || countries[row][col] || country !== A[row][col] ) return; countries[row][col] = true; country = A[row][col]; verifyCountry(A, country, row, col - 1, countries); verifyCountry(A, country, row, col + 1, countries); verifyCountry(A, country, row + 1, col, countries); } ================================================ FILE: coding_interviews/interviews/smartnews/emiter.js ================================================ /* Event Emiter 1. `on` & `emit` 2. `off` 3. `once` */ class EventEmiter { events = {}; on(eventName, fn) { if (!this.events[eventName]) { this.events[eventName] = [{ subscriber: 'on', fn }]; } else { this.events[eventName].push({ subscriber: 'on', fn }); } } emit(eventName, ...args) { if (this.events[eventName]) { for (let i = 0; i < this.events[eventName].length; i++) { this.events[eventName][i].fn(...args); if (this.events[eventName][i].subscriber === 'once') { this.off(eventName, this.events[eventName][i].fn); } } } } off(eventName, fn) { if (this.events[eventName]) { this.events[eventName] = this.events[eventName].filter( (event) => event.fn !== fn ); } } once(eventName, fn) { if (!this.events[eventName]) { this.events[eventName] = [{ subscriber: 'once', fn }]; } else { this.events[eventName].push({ subscriber: 'once', fn }); } } } const eventEmitet = new EventEmiter(); const fn1 = (param1, param2) => console.log('test 1', param1, param2); eventEmitet.once('test', fn1); eventEmitet.emit('test', 'param1', 'param2'); // log param1, param2 eventEmitet.emit('test', 'param1', 'param2'); // log nothing ================================================ FILE: coding_interviews/interviews/smartnews/getTriplets.js ================================================ // /** // * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. // * // * Note: // * The solution set must not contain duplicate triplets. // * // * Example: // * Given array nums = [-1, 0, 1, 2, -1, -4], // * // * A solution set is: // * [ // * [-1, 0, 1], // * [-1, -1, 2] // * ] // */ const getTriplets = (nums) => { const triplets = []; const tripletMapper = {}; const allNumbers = {}; nums.forEach((num) => (allNumbers[num] = true)); for (let i = 0; i < nums.length - 2; i++) { for (let j = i + 1; j < nums.length - 1; j++) { const firstTwoSum = nums[i] + nums[j]; const targetNumber = 0 - firstTwoSum; if (allNumbers[targetNumber]) { const mapperKey = stringify([nums[i], nums[j], targetNumber]); if (!tripletMapper[mapperKey]) { tripletMapper[mapperKey] = true; triplets.push([nums[i], nums[j], targetNumber]); } } } } return triplets; }; const stringify = (nums) => nums[0] + '.' + nums[1] + '.' + nums[2]; console.log(getTriplets([0, 0, 0])); console.log(getTriplets([-1, 0, 1, 2, -1, -4])); console.log(getTriplets([0, -1, 2])); console.log(getTriplets([0, -1, Infinity])); ================================================ FILE: coding_interviews/interviews/uber/longest-words.js ================================================ // console.log('Hello world'); // I would like you to write a function which takes two arguments: a list of words, each separated by comma, and a list of letters. The function should output the longest words from which can be made using the letters in the list. // --------- // Inputs // --------- // Words: aab,cab,abba,abacus,scabs,scab,bacca,ab // Letters: aabbscb // aab, cab, abba // ---------------------- // Expected Output // ---------------------- // abba, scab // Algorithm Analysis // O(L + W * CW) => O(W * CW) // L = letters // W = words // CW = chars of word function buildCounter(letters) { let lettersCounter = {}; for (let char of letters) { if (lettersCounter[char]) { lettersCounter[char]++; } else { lettersCounter[char] = 1; } } return lettersCounter; } function getLongestWords(words, letters) { let lettersCounter = buildCounter(letters); let longestLength = 0; let allValidWords = {}; for (let word of words) { let lettersCounterCopy = { ...lettersCounter }; // O(L) let isValid = true; for (let char of word) { if ( lettersCounterCopy[char] == undefined || lettersCounterCopy[char] === 0 ) { isValid = false; break; } lettersCounterCopy[char] -= 1; } if (isValid) { if (allValidWords[word.length]) { allValidWords[word.length].push(word); } else { allValidWords[word.length] = [word]; } longestLength = Math.max(longestLength, word.length); } } return allValidWords[longestLength] || []; } console.log( getLongestWords( ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'], 'aabbscb' ) ); console.log( getLongestWords( ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'], '' ) ); console.log( getLongestWords( ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'], 'aabbscbsu' ) ); console.log( getLongestWords( ['aab', 'cab', 'abba', 'abacus', 'scabs', 'scab', 'bacca', 'ab'], 'aabbscbs' ) ); console.log(getLongestWords([''], 'batata')); console.log(getLongestWords(['batata'], 'batata')); console.log(getLongestWords(['aaaaaaaaaaaaaa'], 'aaaaaaaaaaaaaa')); ================================================ FILE: coding_interviews/interviews/uber/maxFrequency.js ================================================ export function maxFrequency(numbers) { let maxFrequencyNumber = -1; let result = -1; let numberToFrequencyMap = {}; for (let num of numbers) { if (numberToFrequencyMap[num]) { numberToFrequencyMap[num]++; } else { numberToFrequencyMap[num] = 1; } } Object.entries(numberToFrequencyMap).forEach(([num, frequency]) => { if (frequency > maxFrequencyNumber) { maxFrequencyNumber = frequency; result = Number(num); } }); return result; } ================================================ FILE: coding_interviews/interviews/uber/permutations.js ================================================ /* Input [2,3] Output: ["AD", "BD", "CD", "AE", "BE", "CE", "AF", "BF", "CF"], 9 Input [] Output: [], 0 Input [1,2] Output: ["A", "B", "C"], 3 Input [0,2] Output: ["+A", "+B", "+C"], 3 Input [2,3,4] Output: ["ADG", "ADH", "ADI", "AEG", ...] */ let numberToValues = { 0: '+', 1: ' ', 2: 'ABC', 3: 'DEF', 4: 'GHI', 5: 'JKL', 6: 'MNO', 7: 'PQRS', 8: 'TUV', 9: 'WXYZ', }; function combine(permutations, chars) { let combination = []; for (let permutation of permutations) { for (let char of chars) { combination.push(permutation + char); } } return combination; } function permutations(numbers) { if (numbers.length === 0) { return []; } let allPermutations = []; let num = numbers[0]; let chars = numberToValues[num]; for (let char of chars) { allPermutations.push(char); } for (let index = 1; index < numbers.length; index++) { let num = numbers[index]; let chars = numberToValues[num]; allPermutations = combine(allPermutations, chars); } return allPermutations; } console.log(permutations([2, 3])); console.log(permutations([2, 3, 4])); console.log(permutations([1, 2, 3, 4])); console.log(permutations([0, 1, 2, 3, 4])); ================================================ FILE: coding_interviews/interviews/uber/tests/maxFrequency.test.js ================================================ import { describe, expect, it } from 'vitest'; import { maxFrequency } from '../maxFrequency'; describe('maxFrequency', () => { it('', () => { expect(maxFrequency([2, 2, 2, 3, 3, 1])).toEqual(2); }); it('', () => { expect(maxFrequency([1, 1, 2, 2, 3, 3])).toEqual(1); }); it('', () => { expect(maxFrequency([])).toEqual(-1); }); }); ================================================ FILE: coding_interviews/javascript/array/binary-search.js ================================================ function getMiddle(start, end) { return Math.floor((start + end) / 2); } function binarySearch(numbers, target) { let start = 0; let end = numbers.length - 1; let middle = getMiddle(start, end); let found = false; while (start <= end && !found) { middle = getMiddle(start, end); const middleNumber = numbers[middle]; if (middleNumber === target) found = true; if (middleNumber > target) end = middle - 1; if (middleNumber < target) start = middle + 1; } return found; } function logResult(list, target) { console.log(binarySearch(list, target)); } logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5); // true logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 11); // false logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], -1); // false logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0); // false logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 9); // true logResult([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 1); // true ================================================ FILE: coding_interviews/javascript/array/slice.js ================================================ const list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; list.slice(0); // all elements: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] list.slice(0, 3); // first 3 elements: [1, 2, 3] list.slice(1, 4); // from 2 to 4: [2, 3, 4] ================================================ FILE: coding_interviews/javascript/array/subarrays.js ================================================ function generateSubarrays(arr, start, end, result) { if (end == arr.length) return; else if (start > end) generateSubarrays(arr, 0, end + 1, result); else { result.push(arr.slice(start, end + 1)); generateSubarrays(arr, start + 1, end, result); } } let arr = [1, 2, 3]; let result = []; generateSubarrays(arr, 0, 0, result); console.log(result); ================================================ FILE: coding_interviews/javascript/hashmap/iteration.js ================================================ let hashmap = {}; let numbers = [1, 2, 3, 4, 5, 1, 6, 1, 7, 0, 8, 9, 10, 0, 1]; for (let number of numbers) { if (hashmap[number]) { hashmap[number]++; } else { hashmap[number] = 1; } } // if I need keys and values Object.entries(hashmap).forEach(([key, value]) => { console.log(`${key} -> ${value}`); }); // if I need keys only Object.keys(hashmap).forEach((key) => { console.log(key); }); // if I need values only Object.values(hashmap).forEach((value) => { console.log(value); }); ================================================ FILE: coding_interviews/javascript/hashmap/object.js ================================================ // building a hashmap to count numbers let hashmap = {}; let numbers = [1, 2, 3, 4, 5, 1, 6, 1, 7, 0, 8, 9, 10, 0, 1]; for (let number of numbers) { if (hashmap[number]) { hashmap[number]++; } else { hashmap[number] = 1; } } console.log(hashmap); ================================================ FILE: coding_interviews/javascript/queue/queue.js ================================================ let queue = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function push(queue, value) { queue.push(value); } function pop(queue) { return queue.shift(); } function front(queue) { return queue[0]; } function isEmpty(queue) { return queue.length === 0; } console.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] push(queue, 0); console.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 0] pop(queue); // 1 console.log(queue); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] front(queue); // 2 isEmpty(queue); // false while (!isEmpty(queue)) { queue.pop(); } isEmpty(queue); // true console.log(queue); ================================================ FILE: coding_interviews/javascript/stack/stack.js ================================================ let stack = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; function push(stack, value) { stack.push(value); } function pop(stack) { return stack.pop(); } function top(stack) { return stack[stack.length - 1]; } function isEmpty(stack) { return stack.length === 0; } console.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] push(stack, 11); console.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] pop(stack); // 11 console.log(stack); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] top(stack); // 10 isEmpty(stack); // false while (!isEmpty(stack)) { stack.pop(); } isEmpty(stack); // true console.log(stack); ================================================ FILE: coding_interviews/javascript/string/alphabet.js ================================================ // index to alphabet char const alphabet = 'abcdefghijklmnopqrstuvwxyz'; alphabet[0]; // a alphabet[1]; // b // -------------------- // -------------------- // alphabet char to index function getIndexFromChar(char) { return char.charCodeAt() - 97; } getIndexFromChar('a'); // 0 getIndexFromChar('b'); // 1 ================================================ FILE: coding_interviews/javascript/string/charCode.js ================================================ 'a'.charCodeAt() - 96; // 1 'b'.charCodeAt() - 96; // 2 ================================================ FILE: coding_interviews/javascript/string/isString.js ================================================ function isString(str) { return typeof str === 'string' || str instanceof String; } ================================================ FILE: coding_interviews/javascript/string/methods.js ================================================ const string = 'nihongo'; string.replace('n', 'N'); // 'Nihongo' string.replaceAll('n', 'N'); // 'NihoNgo' string.slice(2, 4); // 'ho' string.toUpperCase(); // 'NIHONGO' string.toUpperCase().toLowerCase(); // 'nihongo' ' nihongo '.trim(); // 'nihongo' ================================================ FILE: coding_interviews/javascript/string/sort.js ================================================ function sort(string) { return [...string].sort((c1, c2) => c1.localeCompare(c2)).join(''); } ================================================ FILE: coding_interviews/javascript/tree/inorder.js ================================================ /* TreeNode { value: int left: TreeNode | null right: TreeNode | null } */ function inorder(node) { if (!node) return; inorder(node.left); node.value; inorder(node.right); } ================================================ FILE: coding_interviews/javascript/tree/postorder.js ================================================ /* TreeNode { value: int left: TreeNode | null right: TreeNode | null } */ function postorder(node) { if (!node) return; postorder(node.left); postorder(node.right); node.value; } ================================================ FILE: coding_interviews/javascript/tree/preorder.js ================================================ /* TreeNode { value: int left: TreeNode | null right: TreeNode | null } */ function preorder(node) { if (!node) return; node.value; preorder(node.left); preorder(node.right); } ================================================ FILE: coding_interviews/leetcode/easy/a-number-after-a-double-reversal/a-number-after-a-double-reversal.js ================================================ function reverse(numString) { const stringArray = []; for (let i = numString.length - 1; i >= 0; i--) { stringArray.push(numString[i]); } return stringArray.join(''); } function removeLeadingZeros(numString) { const numStringWithoutLeadingZeros = []; let foundFirstNonLeadingZero = false; for (let i = 0; i < numString.length; i++) { const digitChar = numString[i]; if ( (!foundFirstNonLeadingZero && digitChar !== '0') || foundFirstNonLeadingZero ) { foundFirstNonLeadingZero = true; numStringWithoutLeadingZeros.push(digitChar); } } return numStringWithoutLeadingZeros.join(''); } export function isSameAfterReversals(num) { const numString = num.toString(); if (numString.length === 1) { return true; } const reversedNumString = removeLeadingZeros(reverse(numString)); return numString === reverse(reversedNumString); } ================================================ FILE: coding_interviews/leetcode/easy/a-number-after-a-double-reversal/tests/a-number-after-a-double-reversal.test.js ================================================ import { describe, it, expect } from 'vitest'; import { isSameAfterReversals } from '../a-number-after-a-double-reversal'; describe('isSameAfterReversals', () => { it('', () => { expect(isSameAfterReversals(526)).toBeTruthy(); }); it('', () => { expect(isSameAfterReversals(1800)).toBeFalsy(); }); it('', () => { expect(isSameAfterReversals(0)).toBeTruthy(); }); it('', () => { expect(isSameAfterReversals(609576)).toBeTruthy(); }); }); ================================================ FILE: coding_interviews/leetcode/easy/add-digits/add-digits.js ================================================ /* Given an integer num, repeatedly add all its digits until the result has only one digit, and return it. Input: num = 38 Output: 2 Explanation: The process is 38 --> 3 + 8 --> 11 11 --> 1 + 1 --> 2 Since 2 has only one digit, return it. Input: num = 0 Output: 0 */ function isSingleDigit(number) { return Math.floor(number / 10) === 0; } function addDigits(number) { let result = number; let sumOfDigits = 0; while (!isSingleDigit(result)) { while (result) { digit = result % 10; result = Math.floor(result / 10); sumOfDigits += digit; } result = sumOfDigits; sumOfDigits = 0; } return result; } console.log('addDigits', addDigits(38)); console.log('addDigits', addDigits(0)); ================================================ FILE: coding_interviews/leetcode/easy/add-two-integers/index.js ================================================ const sum = (num1, num2) => num1 + num2; ================================================ FILE: coding_interviews/leetcode/easy/alternating-digit-sum/alternating-digit-sum.js ================================================ function isEvent(num) { return num % 2 === 0; } function alternateDigitSum(n) { let output = 0; let nString = n.toString(); for (let index = 0; index < nString.length; index++) { if (isEvent(index)) output += Number(nString[index]); else output += Number(nString[index]) * -1; } return output; } ================================================ FILE: coding_interviews/leetcode/easy/apply-operations-to-an-array/apply-operations-to-an-array.js ================================================ function applyOperations(nums) { for (let index = 0; index < nums.length - 1; index++) { if (nums[index] === nums[index + 1]) { nums[index] *= 2; nums[index + 1] = 0; } } let zeros = 0; for (let num of nums) { if (num === 0) zeros++; } let result = []; for (let num of nums) { if (num !== 0) { result.push(num); } } for (let index = 1; index <= zeros; index++) { result.push(0); } return result; } ================================================ FILE: coding_interviews/leetcode/easy/arithmetic_progression/arithmetic_progression.py ================================================ # https://leetcode.com/problems/can-make-arithmetic-progression-from-sequence def can_make_arithmetic_progression(arr): sorted_arr, diff = sorted(arr), '-Inf' for index in range(len(sorted_arr) - 1): if diff == '-Inf': diff = sorted_arr[index + 1] - sorted_arr[index] if sorted_arr[index + 1] - sorted_arr[index] != diff: return False return True ================================================ FILE: coding_interviews/leetcode/easy/array_partition.py ================================================ ''' https://leetcode.com/problems/array-partition-i/description/ Input: [1,4,3,2] Output: 4 ''' def array_pair_sum(nums): return sum(sorted(nums)[::2]) print(array_pair_sum([1, 4, 3, 2])) ================================================ FILE: coding_interviews/leetcode/easy/average-of-levels-in-binary-tree/average-of-levels-in-binary-tree.js ================================================ function averageOfLevels(root) { const queue = []; const averageOfLevels = []; queue.push(root); while (queue.length) { let sumOfLevelNodes = 0; let levelNumberOfNodes = queue.length; for (let node of queue) { sumOfLevelNodes += node.val; } averageOfLevels.push(sumOfLevelNodes / queue.length); for (let index = 0; index < levelNumberOfNodes; index++) { const node = queue.shift(); node.left && queue.push(node.left); node.right && queue.push(node.right); } } return averageOfLevels; } ================================================ FILE: coding_interviews/leetcode/easy/average-salary-excluding-the-minimum-and-maximum-salary/average-salary-excluding-the-minimum-and-maximum-salary.js ================================================ function average(salaries) { let min = Infinity; let max = -Infinity; let sum = 0; for (let salary of salaries) { min = Math.min(min, salary); max = Math.max(max, salary); sum += salary; } sum -= min + max; return sum / (salaries.length - 2); } ================================================ FILE: coding_interviews/leetcode/easy/average-value-of-even-numbers-that-are-divisible-by-three/average-value-of-even-numbers-that-are-divisible-by-three.js ================================================ // https://leetcode.com/problems/average-value-of-even-numbers-that-are-divisible-by-three function isEven(num) { return num % 2 === 0; } function isDividedBy3(num) { return num % 3 === 0; } function averageValue(nums) { let n = 0; let sum = 0; for (let num of nums) { if (isEven(num) && isDividedBy3(num)) { n++; sum += num; } } return n ? Math.floor(sum / n) : 0; } ================================================ FILE: coding_interviews/leetcode/easy/backspace-string-compare/index.js ================================================ function buildStack(string) { const stack = []; for (let index = 0; index < string.length; index++) { if (string[index] === '#') { stack.pop(); } else { stack.push(string[index]); } } return stack; } function isEqual(stack1, stack2) { if (stack1.length !== stack2.length) { return false; } for (let index = 0; index < stack1.length; index++) { if (stack1[index] !== stack2[index]) { return false; } } return true; } export function backspaceCompare(s, t) { const sStack = buildStack(s); const tStack = buildStack(t); return isEqual(sStack, tStack); } ================================================ FILE: coding_interviews/leetcode/easy/backspace-string-compare/tests/index.test.js ================================================ import { describe, expect, it } from 'vitest'; import { backspaceCompare } from '../'; describe('backspaceCompare', () => { it('', () => { expect(backspaceCompare('ab#c', 'ad#c')).toBeTruthy(); }); it('', () => { expect(backspaceCompare('ab##', 'c#d#')).toBeTruthy(); }); it('', () => { expect(backspaceCompare('a#c', 'b')).toBeFalsy(); }); }); ================================================ FILE: coding_interviews/leetcode/easy/baseball-game/baseball-game.js ================================================ function calPoints(ops) { const record = []; for (let op of ops) { if (op === 'C') { record.pop(); } else if (op === 'D') { const lastOp = record[record.length - 1]; record.push(lastOp * 2); } else if (op === '+') { const lastOp = record[record.length - 1]; const penultimateOp = record[record.length - 2]; record.push(lastOp + penultimateOp); } else { record.push(Number(op)); } } return record.reduce((recordItem, sum) => sum + recordItem, 0); } ================================================ FILE: coding_interviews/leetcode/easy/best-poker-hand/best-poker-hand.js ================================================ // https://leetcode.com/problems/best-poker-hand function buildMap(list) { let map = new Map(); for (let item of list) { if (map.has(item)) map.set(item, map.get(item) + 1); else map.set(item, 1); } return map; } function bestHand(ranks, suits) { let suitsMap = buildMap(suits); for (let [_, count] of suitsMap.entries()) { if (count >= 5) return 'Flush'; } let ranksMap = buildMap(ranks); let hasPair = false; for (let [_, count] of ranksMap.entries()) { if (count >= 3) return 'Three of a Kind'; if (count >= 2) hasPair = true; } return hasPair ? 'Pair' : 'High Card'; } ================================================ FILE: coding_interviews/leetcode/easy/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock-tle.js ================================================ function maxProfit(prices) { let max = 0; for (let index = 0; index < prices.length; index++) { for ( let compareIndex = index + 1; compareIndex < prices.length; compareIndex++ ) { max = Math.max(max, prices[compareIndex] - prices[index]); } } return max; } ================================================ FILE: coding_interviews/leetcode/easy/best-time-to-buy-and-sell-stock/best-time-to-buy-and-sell-stock.js ================================================ function maxProfit(prices) { let max = 0; let buy = 0; let sell = 1; while (sell < prices.length) { if (prices[buy] < prices[sell]) { let profit = prices[sell] - prices[buy]; max = Math.max(max, profit); } else { buy = sell; } sell++; } return max; } ================================================ FILE: coding_interviews/leetcode/easy/binary-number-with-alternating-bits/binary-number-with-alternating-bits.js ================================================ function toBinary(n) { let binary = []; while (n) { binary.push((n % 2).toString()); n = Math.floor(n / 2); } return binary.join(''); } function isAlternating(binary) { let previous = binary[0]; for (let index = 1; index < binary.length; index++) { let current = binary[index]; if (previous === current) return false; previous = current; } return true; } function hasAlternatingBits(n) { return isAlternating(toBinary(n)); } ================================================ FILE: coding_interviews/leetcode/easy/binary-search/binary-search.js ================================================ function search(nums, target) { let start = 0; let end = nums.length - 1; let middle = Math.floor((end + start) / 2); let index = -1; let found = false; while (start <= end && !found) { if (target > nums[middle]) { start = middle + 1; middle = Math.floor((end + start) / 2); } else if (target < nums[middle]) { end = middle - 1; middle = Math.floor((end + start) / 2); } else { index = middle; found = true; } } return index; } ================================================ FILE: coding_interviews/leetcode/easy/binary-tree-inorder-traversal/binary-tree-inorder-traversal.js ================================================ function inorderTraversal(root) { if (!root) { return []; } return [ ...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right), ]; } ================================================ FILE: coding_interviews/leetcode/easy/binary-tree-paths/binary-tree-paths.js ================================================ function traversal(node, paths, path) { if (!node.left && !node.right) { paths.push(path.join('->')); } if (node.left) { traversal(node.left, paths, [...path, node.left.val]); } if (node.right) { traversal(node.right, paths, [...path, node.right.val]); } } function binaryTreePaths(root) { let paths = []; traversal(root, paths, [root.val]); return paths; } ================================================ FILE: coding_interviews/leetcode/easy/binary-tree-postorder-traversal/binary-tree-postorder-traversal.js ================================================ function postorderTraversal(root) { if (!root) { return []; } return [ ...postorderTraversal(root.left), ...postorderTraversal(root.right), root.val, ]; } ================================================ FILE: coding_interviews/leetcode/easy/binary-tree-preorder-traversal/binary-tree-preorder-traversal.js ================================================ function preorderTraversal(root) { if (!root) { return []; } return [ root.val, ...preorderTraversal(root.left), ...preorderTraversal(root.right), ]; } ================================================ FILE: coding_interviews/leetcode/easy/binary-tree-tilt/binary-tree-tilt-optimized.js ================================================ // https://leetcode.com/problems/binary-tree-tilt /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ let sum; function sumNodes(node) { if (!node) return 0; let leftSum = sumNodes(node.left); let rightSum = sumNodes(node.right); sum += Math.abs(leftSum - rightSum); return node.val + leftSum + rightSum; } function findTilt(root) { sum = 0; sumNodes(root); return sum; } ================================================ FILE: coding_interviews/leetcode/easy/binary-tree-tilt/binary-tree-tilt.js ================================================ // https://leetcode.com/problems/binary-tree-tilt /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ function sumNodes(node) { if (!node) return 0; return node.val + sumNodes(node.left) + sumNodes(node.right); } function findTilt(root) { if (!root) return 0; return ( Math.abs(sumNodes(root.left) - sumNodes(root.right)) + findTilt(root.left) + findTilt(root.right) ); } ================================================ FILE: coding_interviews/leetcode/easy/binary_in_linked_list/binary_in_linked_list.py ================================================ def get_decimal_value(head): numbers = [head.val] while head.next: head = head.next numbers.append(head.val) decimal_number = 0 base = 1 for index in range(len(numbers)): decimal_number += base * numbers[len(numbers) - index - 1] base *= 2 return decimal_number ================================================ FILE: coding_interviews/leetcode/easy/build_an_array_with_stack_operations/build_an_array_with_stack_operations.py ================================================ # https://leetcode.com/problems/build-an-array-with-stack-operations def build_array(target, n): hash = {} for num in target: hash[num] = True result = [] for num in range(1, n + 1): if len(hash) == 0: break result.append('Push') if num in hash: del hash[num] else: result.append('Pop') return result def build_array(target, n): s = set(target) result = [] for index in range(1, target[-1] + 1): result.append('Push') if index not in s: result.append('Pop') return result ================================================ FILE: coding_interviews/leetcode/easy/build_array_from_permutation/build_array_from_permutation.js ================================================ // https://leetcode.com/problems/build-array-from-permutation const buildArray = function (nums) { return nums.map((num) => nums[num]); }; ================================================ FILE: coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates-on.js ================================================ // https://leetcode.com/problems/buy-two-chocolates function buyChoco(prices, money) { let min1 = Infinity; let min2 = Infinity; for (let num of prices) { if (num < min1) { min2 = min1; min1 = num; } else if (num <= min2) { min2 = num; } } return money - min1 - min2 >= 0 ? money - min1 - min2 : money; } ================================================ FILE: coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates-sort.js ================================================ // https://leetcode.com/problems/buy-two-chocolates function buyChoco(prices, money) { prices.sort((a, b) => a - b); const first = prices[0]; const second = prices[1]; const diff = money - first - second; return diff >= 0 ? diff : money; } ================================================ FILE: coding_interviews/leetcode/easy/buy-two-chocolates/buy-two-chocolates.js ================================================ // https://leetcode.com/problems/buy-two-chocolates function buyChocolate(prices, money) { let price = Infinity; let priceIndex = 0; for (let index = 0; index < prices.length; index++) { if (prices[index] <= money && prices[index] < price) { price = prices[index]; priceIndex = index; } } prices[priceIndex] = Infinity; return money - price; } function buyChoco(prices, money) { let restMoney = buyChocolate(prices, buyChocolate(prices, money)); return restMoney >= 0 ? restMoney : money; } ================================================ FILE: coding_interviews/leetcode/easy/calculate-amount-paid-in-taxes/calculate-amount-paid-in-taxes.js ================================================ // https://leetcode.com/problems/calculate-amount-paid-in-taxes function calculateTax(brackets, income) { let taxes = 0; let appliedIncome = 0; let moneyToApplyTax; let tax; for (let index = 0; index < brackets.length && income > 0; index++) { moneyToApplyTax = Math.min(income, brackets[index][0] - appliedIncome); appliedIncome += moneyToApplyTax; tax = moneyToApplyTax * (brackets[index][1] / 100); taxes += tax; income -= moneyToApplyTax; } return taxes; } ================================================ FILE: coding_interviews/leetcode/easy/calculate-delayed-arrival-time/calculate-delayed-arrival-time.js ================================================ // https://leetcode.com/problems/calculate-delayed-arrival-time function findDelayedArrivalTime(arrivalTime, delayedTime) { return (arrivalTime + delayedTime) % 24; } ================================================ FILE: coding_interviews/leetcode/easy/calculate-digit-sum-of-a-string/calculate-digit-sum-of-a-string.js ================================================ function buildSubsets(s, k) { const subsets = []; for (let index = 0; index < s.length; index += k) { subsets.push(s.substring(index, index + k)); } return subsets; } function sumDigits(digits) { let sumOfDigits = 0; for (let digit of digits) { sumOfDigits += Number(digit); } return sumOfDigits; } function sumDigitsOfSubsets(subsets) { return subsets.map(sumDigits); } function digitSum(s, k) { if (s.length <= k) return s; const subsets = buildSubsets(s, k); const sumOfDigitsOfSubsets = sumDigitsOfSubsets(subsets); const newString = sumOfDigitsOfSubsets.join(''); return digitSum(newString, k); } ================================================ FILE: coding_interviews/leetcode/easy/calculate-money-in-leetcode-bank/calculate-money-in-leetcode-bank.js ================================================ function totalMoney(n) { let monday = 0; let previousDay = monday; let counter = monday; for (let index = 0; index < n; index++) { if (index % 7 === 0) { monday++; counter += monday; previousDay = monday; } else { previousDay++; counter += previousDay; } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/can-place-flowers/can-place-flowers.js ================================================ function canPlaceFlowers(flowerbed, n) { let counter = 0; for (let index = 0; index < flowerbed.length; index++) { if (flowerbed[index] === 0) { let isLeftPlotEmpty = index === 0 || flowerbed[index - 1] === 0; let isRightPlotEmpty = index === flowerbed.length - 1 || flowerbed[index + 1] === 0; if (isLeftPlotEmpty && isRightPlotEmpty) { flowerbed[index] = 1; counter++; } } } return counter >= n; } ================================================ FILE: coding_interviews/leetcode/easy/capitalize-the-title/capitalize-the-title.js ================================================ function isUppercase(char) { return char.charCodeAt() >= 65 && char.charCodeAt() <= 90; } function isLowercase(char) { return char.charCodeAt() >= 97 && char.charCodeAt() <= 122; } function capitalizeChar(char) { return isUppercase(char) ? char : String.fromCharCode(char.charCodeAt() - 32); } function lowercaseChar(char) { return isLowercase(char) ? char : String.fromCharCode(char.charCodeAt() + 32); } function capitalize(string) { return capitalizeChar(string[0]) + lowercase(string.slice(1)); } function lowercase(string) { return string.split('').map(lowercaseChar).join(''); } function parse(string) { return string.length <= 2 ? lowercase(string) : capitalize(string); } function capitalizeTitle(title) { return title.split(' ').map(parse).join(' '); } ================================================ FILE: coding_interviews/leetcode/easy/cells-in-a-range-on-an-excel-sheet/cells-in-a-range-on-an-excel-sheet.js ================================================ const alphabet = ' ABCDEFGHIJKLMNOPQRSTUVWXYZ'; export function cellsInRange(s) { const result = []; for ( let alpha = alphabet.indexOf(s[0]); alpha <= alphabet.indexOf(s[3]); alpha++ ) { for (let i = Number(s[1]); i <= Number(s[4]); i++) { result.push(alphabet[alpha] + i.toString()); } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/cells-in-a-range-on-an-excel-sheet/tests/cells-in-a-range-on-an-excel-sheet.test.js ================================================ import { describe, it, expect } from 'vitest'; import { cellsInRange } from '../cells-in-a-range-on-an-excel-sheet'; describe('cellsInRange', () => { it('', () => { expect(cellsInRange('U7:X9')).toEqual([ 'U7', 'U8', 'U9', 'V7', 'V8', 'V9', 'W7', 'W8', 'W9', 'X7', 'X8', 'X9', ]); }); it('', () => { expect(cellsInRange('P7:Z7')).toEqual([ 'P7', 'Q7', 'R7', 'S7', 'T7', 'U7', 'V7', 'W7', 'X7', 'Y7', 'Z7', ]); }); it('', () => { expect(cellsInRange('K1:L2')).toEqual(['K1', 'K2', 'L1', 'L2']); }); it('', () => { expect(cellsInRange('A1:F1')).toEqual(['A1', 'B1', 'C1', 'D1', 'E1', 'F1']); }); it('', () => { expect(cellsInRange('K2:L3')).toEqual(['K2', 'K3', 'L2', 'L3']); }); }); ================================================ FILE: coding_interviews/leetcode/easy/check-array-formation-through-concatenation/check-array-formation-through-concatenation.js ================================================ function buildMap(pieces) { let hashmap = new Map(); for (let piece of pieces) { hashmap.set(piece[0], piece); } return hashmap; } function canFormArray(arr, pieces) { let index = 0; let hashmap = buildMap(pieces); let output = []; while (index < arr.length) { let num = arr[index]; if (!hashmap.has(num)) return false; output = [...output, ...hashmap.get(num)]; index += hashmap.get(num).length; } if (arr.length !== output.length) return false; for (let index = 0; index < arr.length; index++) { if (arr[index] !== output[index]) return false; } return true; } ================================================ FILE: coding_interviews/leetcode/easy/check-distances-between-same-letters/check-distances-between-same-letters.js ================================================ function getDistanceIndex(char) { return char.charCodeAt() - 97; } function checkDistances(string, distance) { const hashmap = new Map(); for (let index = 0; index < string.length; index++) { const char = string[index]; if (hashmap.has(char)) { const distanceIndex = getDistanceIndex(char); const charDistance = distance[distanceIndex]; const previousIndex = hashmap.get(char); if (index - previousIndex - 1 !== charDistance) return false; } else { hashmap.set(char, index); } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/check-if-a-string-is-an-acronym-of-words/check-if-a-string-is-an-acronym-of-words.js ================================================ // https://leetcode.com/problems/check-if-a-string-is-an-acronym-of-words function isAcronym(words, s) { if (words.length !== s.length) return false; for (let index = 0; index < s.length; index++) { if (words[index][0] !== s[index]) { return false; } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence.js ================================================ function hasPrefix(word, searchWord) { if (searchWord.length > word.length) return false; for (let index = 0; index < searchWord.length; index++) { if (searchWord[index] !== word[index]) return false; } return true; } function isPrefixOfWord(sentence, searchWord) { const words = sentence.split(' '); for (let index = 0; index < words.length; index++) { if (hasPrefix(words[index], searchWord)) return index + 1; } return -1; } ================================================ FILE: coding_interviews/leetcode/easy/check-if-all-as-appears-before-all-bs/check-if-all-as-appears-before-all-bs.js ================================================ function checkString(s) { let gotFirstB = false; for (let char of s) { if (char === 'b' && !gotFirstB) { gotFirstB = true; } if (char === 'a' && gotFirstB) { return false; } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/check-if-matrix-is-x-matrix/check-if-matrix-is-x-matrix.js ================================================ function isInGrid(grid, row, col) { return row >= 0 && col >= 0 && row < grid.length && col < grid.length; } const DIAGONAL = -1; function getDiagonalFromLeftToRight(grid) { let row = 0; let col = 0; let values = []; while (isInGrid(grid, row, col)) { values.push(grid[row][col]); grid[row][col] = DIAGONAL; row++; col++; } return values; } function getDiagonalFromRightToLeft(grid) { let row = 0; let col = grid.length - 1; let values = []; while (isInGrid(grid, row, col)) { if (grid[row][col] !== DIAGONAL) { values.push(grid[row][col]); grid[row][col] = DIAGONAL; } row++; col--; } return values; } function isDiagonalNonZero(diagonal) { return diagonal.filter((value) => value === 0).length === 0; } function isOtherZero(grid) { for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid.length; col++) { if (grid[row][col] !== DIAGONAL && grid[row][col] !== 0) { return false; } } } return true; } function checkXMatrix(grid) { const fromLeftToRightDiagonalValues = getDiagonalFromLeftToRight(grid); const fromRightToLeftDiagonalValues = getDiagonalFromRightToLeft(grid); const isFromLeftToRightNonZero = isDiagonalNonZero( fromLeftToRightDiagonalValues ); const isFromRightToLeftNonZero = isDiagonalNonZero( fromRightToLeftDiagonalValues ); const isOtherElementsZero = isOtherZero(grid); return ( isFromLeftToRightNonZero && isFromRightToLeftNonZero && isOtherElementsZero ); } function checkXMatrix(grid) { const n = grid.length; for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[0].length; j++) { if (i == j || i + j + 1 == n) { if (grid[i][j] == 0) return false; } else { if (grid[i][j] != 0) return false; } } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/check-if-number-has-equal-digit-count-and-digit-value/check-if-number-has-equal-digit-count-and-digit-value.js ================================================ function digitCount(num) { let counter = new Map(); for (let digit of num) { if (counter.has(digit)) { counter.set(digit, counter.get(digit) + 1); } else { counter.set(digit, 1); } } for (let index = 0; index < num.length; index++) { let digit = num[index]; let indexString = index.toString(); if ( counter.has(indexString) && counter.get(indexString) !== Number(digit) ) { return false; } if (!counter.has(indexString) && digit !== '0') { return false; } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/check-if-numbers-are-ascending-in-a-sentence/check-if-numbers-are-ascending-in-a-sentence.js ================================================ function getNumbers(string) { const tokens = string.split(' '); const numbersStrings = tokens.filter((token) => !Number.isNaN(Number(token))); return numbersStrings.map((numberString) => Number(numberString)); } function isIncreasing(numbers) { for (let index = 0; index < numbers.length - 1; index++) { if (numbers[index + 1] <= numbers[index]) return false; } return true; } function areNumbersAscending(string) { const numbers = getNumbers(string); return isIncreasing(numbers); } ================================================ FILE: coding_interviews/leetcode/easy/check-if-the-sentence-is-pangram/check-if-the-sentence-is-pangram.py ================================================ # https://leetcode.com/problems/check-if-the-sentence-is-pangram def check_if_pangram(sentence): if len(sentence) < 26: return False unique_chars = set() for char in sentence: unique_chars.add(char) return len(unique_chars) == 26 def check_if_pangram(sentence): return len(set(sentence)) == 26 ================================================ FILE: coding_interviews/leetcode/easy/check-whether-two-strings-are-almost-equivalent/check-whether-two-strings-are-almost-equivalent.js ================================================ function createCounter(word) { const counter = new Map(); for (let char of word) { if (counter.has(char)) counter.set(char, counter.get(char) + 1); else counter.set(char, 1); } return counter; } function isSimilar(word, counter1, counter2) { for (let char of word) { const count1 = counter1.get(char); const count2 = (counter2.has(char) && counter2.get(char)) || 0; if (Math.abs(count1 - count2) > 3) return false; } return true; } function checkAlmostEquivalent(word1, word2) { const word1Counter = createCounter(word1); const word2Counter = createCounter(word2); return ( isSimilar(word1, word1Counter, word2Counter) && isSimilar(word2, word2Counter, word1Counter) ); } ================================================ FILE: coding_interviews/leetcode/easy/check_if_all_characters_have_equal_number_of_occurrences/check_if_all_characters_have_equal_number_of_occurrences.js ================================================ // https://leetcode.com/problems/check-if-all-characters-have-equal-number-of-occurrences const areOccurrencesEqual = function (s) { const counter = {}; for (let i = 0; i < s.length; i++) { if (s[i] in counter) counter[s[i]]++; else counter[s[i]] = 1; } return new Set(Object.values(counter)).size === 1; }; ================================================ FILE: coding_interviews/leetcode/easy/check_if_two_string_arrays_are_equivalent/check_if_two_string_arrays_are_equivalent.py ================================================ # https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent def array_strings_are_equal(word1, word2): return ''.join(word1) == ''.join(word2) ================================================ FILE: coding_interviews/leetcode/easy/circular-sentence/circular-sentence.js ================================================ function isCircularSentence(sentence) { const words = sentence.split(' '); const lastWord = words[words.length - 1]; const lastCharEqualFirstChar = lastWord[lastWord.length - 1] === words[0][0]; if (!lastCharEqualFirstChar) return false; for (let index = 0; index < words.length - 1; index++) { const firstWord = words[index]; const nextWord = words[index + 1]; if (firstWord[firstWord.length - 1] !== nextWord[0]) return false; } return true; } ================================================ FILE: coding_interviews/leetcode/easy/climbing-stairs/climbing-stairs.js ================================================ function climbStairs(n) { let memo = [0, 1, 2, 3]; for (let i = 4; i <= n; i++) { memo.push(memo[i - 1] + memo[i - 2]); } return memo[n]; } ================================================ FILE: coding_interviews/leetcode/easy/climbing_stairs.py ================================================ # https://leetcode.com/problems/climbing-stairs/description/ def climb_stairs(n): memo = [0, 1, 2, 3] for i in range(4, n + 1): memo.append(memo[i - 1] + memo[i - 2]) return memo[n] print climb_stairs(1) print climb_stairs(2) print climb_stairs(3) print climb_stairs(4) print climb_stairs(5) print climb_stairs(6) ================================================ FILE: coding_interviews/leetcode/easy/concatenation_of_array/concatenation_of_array.js ================================================ const getConcatenation = function (nums) { nums.forEach((num) => nums.push(num)); return nums; }; const getConcatenation = function (nums) { return [...nums, ...nums]; }; ================================================ FILE: coding_interviews/leetcode/easy/consecutive-characters/consecutive-characters.js ================================================ function maxPower(string) { let power = 1; let max = 1; let currentChar = string[0]; for (let index = 1; index < string.length; index++) { let char = string[index]; if (char === currentChar) max++; if (char !== currentChar || index === string.length - 1) { currentChar = char; power = Math.max(max, power); max = 1; } } return power; } ================================================ FILE: coding_interviews/leetcode/easy/construct-string-from-binary-tree/construct-string-from-binary-tree.js ================================================ // https://leetcode.com/problems/construct-string-from-binary-tree /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ // Time complexity : O(n). The preorder traversal is done over the n nodes of the given Binary Tree. // Space complexity : O(n). The depth of the recursion tree can go upto n in case of a skewed tree. function tree2str(root) { if (!root) return ''; let left = tree2str(root.left); let right = tree2str(root.right); if (right) { return `${root.val}(${left})(${right})`; } if (left) { return `${root.val}(${left})`; } return root.val.toString(); } ================================================ FILE: coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate-hashmap.js ================================================ /* nums = [1,2,3,4,4] numToCounter = { 1: 1, 2: 1, 3: 1, 4: 2 } */ function containsDuplicate(nums) { let numToCounter = {}; let appearsAtLeastTwice = false; for (let num of nums) { if (numToCounter[num]) { numToCounter[num]++; } else { numToCounter[num] = 1; } } Object.values(numToCounter).forEach((num) => { if (num >= 2) { appearsAtLeastTwice = true; } }); return appearsAtLeastTwice; } ================================================ FILE: coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.js ================================================ function containsDuplicate(nums) { return !(nums.length === new Set(nums).size); } ================================================ FILE: coding_interviews/leetcode/easy/contains-duplicate/contains-duplicate.py ================================================ # https://leetcode.com/problems/contains-duplicate-ii def contains_nearby_duplicate(nums, k): for index in range(len(nums)): for comp_index in range(len(nums)): if index != comp_index and nums[index] == nums[comp_index] and abs(comp_index - index) <= k: return True return False def contains_nearby_duplicate(nums, k): index_mapper = {} for index, num in enumerate(nums): if num in index_mapper and index - index_mapper[num] <= k: return True index_mapper[num] = index return False ================================================ FILE: coding_interviews/leetcode/easy/convert-sorted-array-to-binary-search-tree/convert-sorted-array-to-binary-search-tree.js ================================================ function sortedArrayToBST(nums) { if (nums.length === 0) return null; const middle = Math.floor(nums.length / 2); const num = nums[middle]; const node = new TreeNode(num); node.left = sortedArrayToBST(nums.slice(0, middle)); node.right = sortedArrayToBST(nums.slice(middle + 1, nums.length)); return node; } ================================================ FILE: coding_interviews/leetcode/easy/convert-the-temperature/convert-the-temperature.js ================================================ function convertTemperature(celsius) { return [celsius + 273.15, celsius * 1.8 + 32.0]; } ================================================ FILE: coding_interviews/leetcode/easy/count-asterisks/count-asterisks.js ================================================ function toggleCanCount(canCount) { return !canCount; } function countAsterisks(s) { let asteristics = 0; let canCount = true; for (let char of s) { if (canCount && char === '*') { asteristics++; } if (char === '|') { canCount = toggleCanCount(canCount); } } return asteristics; } ================================================ FILE: coding_interviews/leetcode/easy/count-common-words-with-one-occurrence/count-common-words-with-one-occurrence.js ================================================ function buildHashmap(words) { let hashmap = new Map(); for (let word of words) { if (hashmap.has(word)) { hashmap.set(word, hashmap.get(word) + 1); } else { hashmap.set(word, 1); } } return hashmap; } function countWords(words1, words2) { let words1Counter = buildHashmap(words1); let words2Counter = buildHashmap(words2); let words = 0; for (let [word, counter] of words1Counter) { if ( counter === 1 && words2Counter.has(word) && words2Counter.get(word) === 1 ) { words++; } } return words; } ================================================ FILE: coding_interviews/leetcode/easy/count-complete-tree-nodes/count-complete-tree-nodes.js ================================================ // https://leetcode.com/problems/count-complete-tree-nodes /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ function countNodes(node) { return node ? 1 + countNodes(node.left) + countNodes(node.right) : 0; } ================================================ FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/count-equal-and-divisible-pairs-in-an-array-2.js ================================================ /* list = [3, 1, 2, 2, 2, 1, 3] data structure { 3: [0, 6], 1: [1, 5], 2: [2, 3, 4] } worst case scenario { x: [0, 1, 2, 3, ..., 100] } */ export function countPairs(numbers, k) { let counter = 0; for (let i = 0; i < numbers.length - 1; i++) { for (let j = i + 1; j < numbers.length; j++) { if (numbers[i] === numbers[j] && (i * j) % k === 0) { counter++; } } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/count-equal-and-divisible-pairs-in-an-array.js ================================================ /* list = [3, 1, 2, 2, 2, 1, 3] data structure { 3: [0, 6], 1: [1, 5], 2: [2, 3, 4] } worst case scenario { x: [0, 1, 2, 3, ..., 100] } */ export function countPairs(numbers, k) { const numberToIndices = {}; numbers.forEach((number, index) => { if (number in numberToIndices) { numberToIndices[number].push(index); } else { numberToIndices[number] = [index]; } }); let counter = 0; Object.values(numberToIndices).forEach((indices) => { for (let i = 0; i < indices.length - 1; i++) { for (let j = i + 1; j < indices.length; j++) { if ((indices[i] * indices[j]) % k === 0) { counter++; } } } }); return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/tests/count-equal-and-divisible-pairs-in-an-array-2.test.js ================================================ import { describe, expect, it } from 'vitest'; import { countPairs } from '../count-equal-and-divisible-pairs-in-an-array-2'; describe('countPairs', () => { it('', () => { expect(countPairs([3, 1, 2, 2, 2, 1, 3], 2)).toEqual(4); }); it('', () => { expect(countPairs([1, 2, 3, 4], 1)).toEqual(0); }); }); ================================================ FILE: coding_interviews/leetcode/easy/count-equal-and-divisible-pairs-in-an-array/tests/count-equal-and-divisible-pairs-in-an-array.test.js ================================================ import { describe, expect, it } from 'vitest'; import { countPairs } from '../count-equal-and-divisible-pairs-in-an-array'; describe('countPairs', () => { it('', () => { expect(countPairs([3, 1, 2, 2, 2, 1, 3], 2)).toEqual(4); }); it('', () => { expect(countPairs([1, 2, 3, 4], 1)).toEqual(0); }); }); ================================================ FILE: coding_interviews/leetcode/easy/count-good-triplets/count-good-triplets.py ================================================ # https://leetcode.com/problems/count-good-triplets ''' Time Complexity: O(N^3) Space Complexity: O(1) - no extra space rather than the input ''' def count_good_triplets(arr, a, b, c): counter = 0 for i in range(len(arr)): for j in range(i+1, len(arr)): for k in range(j+1, len(arr)): if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/count-integers-with-even-digit-sum/count-integers-with-even-digit-sum.js ================================================ function sumDigits(numString) { let sum = 0; for (let digit of numString) { sum += Number(digit); } return sum; } function isEven(num) { return num % 2 === 0; } function countEven(num) { let counter = 0; for (let number = 1; number <= num; number++) { let numString = number.toString(); let digitSum = sumDigits(numString); if (isEven(digitSum)) counter++; } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-k-difference/count-k-difference.js ================================================ /* Given an integer array nums and an integer k, return the number of pairs (i, j) where i < j such that |nums[i] - nums[j]| == k. The value of |x| is defined as: x if x >= 0. -x if x < 0. Example 1: Input: nums = [1,2,2,1], k = 1 Output: 4 Explanation: The pairs with an absolute difference of 1 are: - [1,2,2,1] - [1,2,2,1] - [1,2,2,1] - [1,2,2,1] Example 2: Input: nums = [1,3], k = 3 Output: 0 Explanation: There are no pairs with an absolute difference of 3. Example 3: Input: nums = [3,2,1,5,4], k = 2 Output: 3 Explanation: The pairs with an absolute difference of 2 are: - [3,2,1,5,4] - [3,2,1,5,4] - [3,2,1,5,4] */ function countKDifference(nums, k) { const numsMap = {}; nums.forEach((num) => { if (num in numsMap) numsMap[num] += 1; else numsMap[num] = 1; }); let count = 0; nums.forEach((num) => { const rest = num + k; if (rest in numsMap) { count += numsMap[rest]; } }); return count; } console.log(countKDifference([1, 2, 2, 1], 1), 4); console.log(countKDifference([1, 3], 3), 0); console.log(countKDifference([3, 2, 1, 5, 4], 2), 3); console.log(countKDifference([7, 10, 10, 6, 10, 1, 9, 10, 4, 9], 7), 0); console.log(countKDifference([2, 3, 2, 10, 3, 9, 4, 9, 5, 8], 1), 11); ================================================ FILE: coding_interviews/leetcode/easy/count-largest-group/count-largest-group.js ================================================ // https://leetcode.com/problems/count-largest-group function sumDigits(num) { let numString = num.toString(); let sum = 0; for (let digit of numString) { sum += Number(digit); } return sum; } function countLargestGroup(n) { let hashmap = new Map(); for (let num = 1; num <= n; num++) { let sum = sumDigits(num); if (hashmap.has(sum)) hashmap.set(sum, [...hashmap.get(sum), num]); else hashmap.set(sum, [num]); } let largest = -Infinity; for (let [_, values] of hashmap.entries()) { largest = Math.max(largest, values.length); } let size = 0; for (let [_, values] of hashmap.entries()) { if (values.length === largest) size++; } return size; } ================================================ FILE: coding_interviews/leetcode/easy/count-operations-to-obtain-zero/count-operations-to-obtain-zero.js ================================================ export function countOperations(num1, num2) { let counter = 0; while (num1 > 0 && num2 > 0) { if (num1 >= num2) { num1 -= num2; } else { num2 -= num1; } counter++; } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-operations-to-obtain-zero/tests/count-operations-to-obtain-zero.test.js ================================================ import { describe, expect, it } from 'vitest'; import { countOperations } from '../count-operations-to-obtain-zero'; describe('countOperations', () => { it('', () => { expect(countOperations(2, 3)).toEqual(3); }); it('', () => { expect(countOperations(10, 10)).toEqual(1); }); }); ================================================ FILE: coding_interviews/leetcode/easy/count-pairs-of-similar-strings/count-pairs-of-similar-strings.js ================================================ function buildCharsMap(word) { const map = new Map(); for (let char of word) { if (map.has(char)) map.set(char, map.get(char) + 1); else map.set(char, 1); } return map; } function hasAllChars(word, charsMap) { for (let char of word) { if (!charsMap.has(char)) return false; } return true; } function isSimilar(word1, word2) { const word1CharsMap = buildCharsMap(word1); const word2CharsMap = buildCharsMap(word2); return hasAllChars(word1, word2CharsMap) && hasAllChars(word2, word1CharsMap); } function similarPairs(words) { let count = 0; for (let i = 0; i < words.length - 1; i++) { for (let j = i + 1; j < words.length; j++) { if (isSimilar(words[i], words[j])) count++; } } return count; } ================================================ FILE: coding_interviews/leetcode/easy/count-pairs-whose-sum-is-less-than-target/count-pairs-whose-sum-is-less-than-target-two-pointers.js ================================================ // https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target function countPairs(nums, target) { nums.sort((num1, num2) => num1 - num2); let counter = 0; let start = 0; let end = nums.length - 1; while (start < end) { if (nums[start] + nums[end] < target) { counter += end - start; start++; } else { end--; } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-pairs-whose-sum-is-less-than-target/count-pairs-whose-sum-is-less-than-target.js ================================================ // https://leetcode.com/problems/count-pairs-whose-sum-is-less-than-target function countPairs(nums, target) { let counter = 0; for (let i = 0; i < nums.length; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] < target) counter++; } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-prefixes-of-a-given-string/count-prefixes-of-a-given-string.js ================================================ function hasPrefix(word, s) { for (let index = 0; index < word.length; index++) { if (word[index] !== s[index]) { return false; } } return true; } function countPrefixes(words, s) { let counter = 0; for (let word of words) { if (word.length <= s.length && hasPrefix(word, s)) { counter++; } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-square-sum-triples/count-square-sum-triples.js ================================================ function countTriples(n) { let hashmap = new Map(); let counter = 0; for (let num = 1; num <= n; num++) { hashmap.set(num * num, num); } for (let a = 1; a <= n; a++) { for (let b = 1; b <= n; b++) { const c = a * a + b * b; if (hashmap.has(c)) { counter++; } } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/count-symmetric-integers/count-symmetric-integers.js ================================================ // https://leetcode.com/problems/count-symmetric-integers function isSymmetricIntegers(num) { let numString = num.toString(); if (numString.length % 2 !== 0) return false; let firstHalfSum = 0; let lastHalfSum = 0; for (let index = 0; index < numString.length; index++) { let digit = numString[index]; if (index < numString.length / 2) firstHalfSum += Number(digit); else lastHalfSum += Number(digit); } return firstHalfSum === lastHalfSum; } function countSymmetricIntegers(low, high) { let count = 0; for (let num = low; num <= high; num++) { if (isSymmetricIntegers(num)) { count++; } } return count; } ================================================ FILE: coding_interviews/leetcode/easy/count-the-digits-that-divide-a-number/count-the-digits-that-divide-a-number.js ================================================ function countDigits(num) { let digitsCount = 0; let numString = num.toString(); for (let numChar of numString) { if (num % Number(numChar) === 0) digitsCount++; } return digitsCount; } ================================================ FILE: coding_interviews/leetcode/easy/count-the-number-of-vowel-strings-in-range/count-the-number-of-vowel-strings-in-range.js ================================================ const VOWELS = ['a', 'e', 'i', 'o', 'u']; function isVowelString(string) { return ( VOWELS.includes(string[0]) && VOWELS.includes(string[string.length - 1]) ); } function vowelStrings(words, left, right) { let vowelsStrings = 0; for (let index = left; index <= right; index++) { if (isVowelString(words[index])) { vowelsStrings++; } } return vowelsStrings; } ================================================ FILE: coding_interviews/leetcode/easy/count-vowel-substrings-of-a-string/count-vowel-substrings-of-a-string.js ================================================ const VOWELS = ['a', 'e', 'i', 'o', 'u']; function isVowel(char) { return VOWELS.includes(char); } function hasAllVowels(foundVowels) { return ( foundVowels.has('a') && foundVowels.has('e') && foundVowels.has('i') && foundVowels.has('o') && foundVowels.has('u') ); } function countVowelSubstrings(word) { let vowelSubstringCount = 0; for (let i = 0; i < word.length - 4; i++) { if (!isVowel(word[i])) continue; const foundVowels = new Map(); foundVowels.set(word[i], 1); for (let index = i + 1; index < word.length; index++) { const char = word[index]; if (!isVowel(char)) break; if (foundVowels.has(char)) foundVowels.set(char, foundVowels.get(char) + 1); else foundVowels.set(char, 1); if (hasAllVowels(foundVowels)) vowelSubstringCount++; } } return vowelSubstringCount; } ================================================ FILE: coding_interviews/leetcode/easy/count_good_rectangles/count_good_rectangles.py ================================================ # https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square ''' Time Complexity: O(N) Space Complexity: O(N) ''' def count_good_rectangles(rectangles): max_len, all_max_lens = 0, [] for rec in rectangles: square_len = min(rec[0], rec[1]) max_len = max(max_len, square_len) all_max_lens.append(square_len) counter = 0 for length in all_max_lens: if length == max_len: counter += 1 return counter def count_good_rectangles_optimized(rectangles): max_len, counter = 0, 0 for rec in rectangles: square_len = min(rec[0], rec[1]) if square_len > max_len: max_len = square_len counter = 0 if square_len == max_len: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/count_matches/count_matches.py ================================================ # https://leetcode.com/problems/count-items-matching-a-rule def count_matches(items, ruleKey, ruleValue): counter = 0 for item in items: if ruleKey == 'type' and item[0] == ruleValue: counter += 1 if ruleKey == 'color' and item[1] == ruleValue: counter += 1 if ruleKey == 'name' and item[2] == ruleValue: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/count_of_matches_in_tournament/count_of_matches_in_tournament.py ================================================ # https://leetcode.com/problems/count-of-matches-in-tournament ''' Runtime: O(N) Space: O(1) ''' def number_of_matches(n): if n <= 0: return 0 number_of_games = 0 while n > 1: games = n // 2 number_of_games += games if n % 2 == 0: n = games else: n = games + 1 return number_of_games ================================================ FILE: coding_interviews/leetcode/easy/count_students/count_students.py ================================================ # https://leetcode.com/problems/number-of-students-unable-to-eat-lunch def is_empty(arr): return len(arr) == 0 def count_students(students, sandwiches): preferred_circles = 0 preferred_squares = 0 for student in students: if student: preferred_squares += 1 else: preferred_circles += 1 while not is_empty(students) and not is_empty(sandwiches): if students[0] == sandwiches[0]: if students[0]: preferred_squares -= 1 else: preferred_circles -= 1 del students[0] del sandwiches[0] else: students.append(students[0]) del students[0] if not is_empty(sandwiches) and (sandwiches[0] and preferred_squares == 0 or sandwiches[0] == 0 and preferred_circles == 0): break return len(students) def count_students(students, sandwiches): preferences = [0, 0] for student in students: preferences[student] += 1 index = 0 while index < len(students): if preferences[sandwiches[index]] > 0: preferences[sandwiches[index]] -= 1 else: break index += 1 return len(students) - index ================================================ FILE: coding_interviews/leetcode/easy/count_the_number_of_consistent_strings/count_the_number_of_consistent_strings.py ================================================ # https://leetcode.com/problems/count-the-number-of-consistent-strings ''' Time complexity: O(WN), where W = number of words and N = number of character of the longest string Space complexity: O(N) ''' def count_consistent_strings(allowed, words): allowed_mapper = {} for char in allowed: allowed_mapper[char] = True counter = 0 for word in words: all_chars_allowed = True for char in word: if char not in allowed_mapper: all_chars_allowed = False break if all_chars_allowed: counter += 1 return counter ''' Time complexity: O(WNA), where W = number of words and N = number of character of the longest string, and A = length of the allowed string Space complexity: O(1) ''' def count_consistent_strings(allowed, words): counter = 0 for word in words: counter += 1 for char in word: if char not in allowed: counter -= 1 break return counter ================================================ FILE: coding_interviews/leetcode/easy/counting-bits/counting-bits.js ================================================ function countOnesInBinaryTransformation(number) { let counter = 0; while (number) { let remainder = number % 2; if (remainder) counter++; number = Math.floor(number / 2); } return counter; } function countBits(n) { let answer = []; for (let num = 0; num <= n; num++) { answer.push(countOnesInBinaryTransformation(num)); } return answer; } ================================================ FILE: coding_interviews/leetcode/easy/counting-words-with-a-given-prefix/counting-words-with-a-given-prefix.js ================================================ function hasPrefix(word, pref) { if (pref.length > word.length) { return false; } let matchesPrefix = true; for (let i = 0; i < pref.length; i++) { if (word[i] !== pref[i]) { matchesPrefix = false; break; } } return matchesPrefix; } export function prefixCount(words, pref) { let count = 0; words.forEach((word) => { if (hasPrefix(word, pref)) { count++; } }); return count; } ================================================ FILE: coding_interviews/leetcode/easy/counting-words-with-a-given-prefix/tests/counting-words-with-a-given-prefix.test.js ================================================ import { describe, it, expect } from 'vitest'; import { prefixCount } from '../counting-words-with-a-given-prefix'; describe('prefixCount', () => { it('matches 2 words', () => { expect( prefixCount(['pay', 'attention', 'practice', 'attend'], 'at') ).toEqual(2); }); it('matches 3 words', () => { expect( prefixCount(['pay', 'attention', 'practice', 'attend', 'at'], 'at') ).toEqual(3); }); it('matches no word', () => { expect( prefixCount(['leetcode', 'win', 'loops', 'success'], 'code') ).toEqual(0); }); }); ================================================ FILE: coding_interviews/leetcode/easy/crawler-log-folder/crawler-log-folder.js ================================================ function minOperations(logs) { let fileLevel = 0; for (let log of logs) { if (log === '../' && fileLevel) fileLevel--; else if (log === '../') { } else if (log === './') { } else fileLevel++; } return Math.abs(fileLevel); } ================================================ FILE: coding_interviews/leetcode/easy/create_target_array/create_target_array.py ================================================ # https://leetcode.com/problems/create-target-array-in-the-given-order/ def createTargetArray(nums, index): target = [] for i in range(len(nums)): target.insert(index[i], nums[i]) return target ================================================ FILE: coding_interviews/leetcode/easy/decode-the-message/decode-the-message.js ================================================ export function decodeMessage(key, message) { let hashmap = new Map(); let alphabet = 'abcdefghijklmnopqrstuvwxyz'; let counter = 0; hashmap.set(' ', ' '); for (let char of key) { if (!hashmap.has(char)) { hashmap.set(char, alphabet[counter]); counter++; } } let result = []; for (let char of message) { result.push(hashmap.get(char)); } return result.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/decode-the-message/tests/decode-the-message.test.js ================================================ import { describe, expect, it } from 'vitest'; import { decodeMessage } from '../decode-the-message'; describe('decodeMessage', () => { it('', () => { expect( decodeMessage( 'eljuxhpwnyrdgtqkviszcfmabo', 'zwx hnfx lqantp mnoeius ycgk vcnjrdb' ) ).toEqual('the five boxing wizards jump quickly'); }); it('', () => { expect( decodeMessage( 'the quick brown fox jumps over the lazy dog', 'vkbs bs t suepuv' ) ).toEqual('this is a secret'); }); }); ================================================ FILE: coding_interviews/leetcode/easy/decode_xored_array/decode_xored_array.py ================================================ # https://leetcode.com/problems/decode-xored-array def decode(encoded, first): original = [first] for num in encoded: original.append(original[-1] ^ num) return original ================================================ FILE: coding_interviews/leetcode/easy/decompressed_encoded_list/decompressed_encoded_list.py ================================================ # https://leetcode.com/problems/decompress-run-length-encoded-list ''' We are given a list nums of integers representing a list compressed with run-length encoding. Consider each adjacent pair of elements [freq, val] = [nums[2*i], nums[2*i+1]] (with i >= 0). For each such pair, there are freq elements with value val concatenated in a sublist. Concatenate all the sublists from left to right to generate the decompressed list. Return the decompressed list. Input: nums = [1,2,3,4] Output: [2,4,4,4] Input: nums = [1,1,2,3] Output: [1,3,3] ''' def build_frequencies(frequency, num): return [num for i in range(frequency)] def decompress_list(nums): result_list = [] for index in range(0, len(nums), 2): result_list += build_frequencies(nums[index], nums[index+1]) return result_list data_tests = [ ([1, 2, 3, 4], [2, 4, 4, 4]), ([1, 1, 2, 3], [1, 3, 3]) ] for nums, expected in data_tests: result = decompress_list(nums) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/decrypt_string/decrypt_string.py ================================================ # https://leetcode.com/problems/decrypt-string-from-alphabet-to-integer-mapping def alpha(num): return chr(int(num) + ord('a') - 1) def freqAlphabets(s): result, index, s_length = [], 0, len(s) while index < s_length: if index + 2 < len(s) and s[index + 2] == '#': result.append(alpha(s[index:index+2])) index += 3 else: result.append(alpha(s[index])) index += 1 return ''.join(result) ================================================ FILE: coding_interviews/leetcode/easy/defanging_an_ip_address/defanging_an_ip_address.py ================================================ # https://leetcode.com/problems/defanging-an-ip-address/ ''' "1.1.1.1" "1[.]1[.]1[.]1" "255.100.50.0" "255[.]100[.]50[.]0" ''' def defang_ip_address(address): address_chars_list = [] for char in address: if char == '.': address_chars_list.append('[.]') else: address_chars_list.append(char) return ''.join(address_chars_list) data_tests = [ ("1.1.1.1", "1[.]1[.]1[.]1"), ("255.100.50.0", "255[.]100[.]50[.]0") ] for address, expected in data_tests: result = defang_ip_address(address) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/defuse-the-bomb/defuse-the-bomb.js ================================================ function sumNextK(code, from, k) { let sum = 0; for (let index = from + 1; index <= from + k; index++) { sum += code[index]; } return sum; } function decryptNext(code, k) { let newCode = [...code, ...code]; let sum = sumNextK(newCode, 0, k); let nextSum = [sum]; for (let index = 1; index < code.length; index++) { sum = sum - newCode[index] + newCode[index + k]; nextSum.push(sum); } return nextSum; } function sumPreviousK(code, from, k) { let sum = 0; for (let index = from - 1; index >= from - k; index--) { sum += code[index]; } return sum; } function decryptPrevious(code, k) { let newCode = [...code, ...code]; let sum = sumPreviousK(code, code.length - 1, k); let previousSum = [sum]; for (let index = newCode.length - 2; index >= code.length; index--) { sum = sum - newCode[index] + newCode[index - k]; previousSum.push(sum); } return previousSum.reverse(); } function decryptWithZeros(code) { return code.map((_) => 0); } function decrypt(code, k) { if (k > 0) return decryptNext(code, k); if (k < 0) return decryptPrevious(code, k * -1); return decryptWithZeros(code); } ================================================ FILE: coding_interviews/leetcode/easy/delete-greatest-value-in-each-row/delete-greatest-value-in-each-row.js ================================================ function isEmpty(grid) { let lastRow = grid[grid.length - 1]; for (let col = 0; col < grid[0].length; col++) { if (lastRow[col] !== 0) return false; } return true; } function deleteGreatestValue(grid) { let result = 0; while (!isEmpty(grid)) { let max = -Infinity; for (let row = 0; row < grid.length; row++) { let maxCell = -Infinity; let maxCol = -Infinity; for (let col = 0; col < grid[row].length; col++) { const cell = grid[row][col]; if (cell > maxCell) { maxCell = Math.max(cell, maxCell); maxCol = col; } } max = Math.max(maxCell, max); grid[row][maxCol] = 0; } result += max; } return result; } ================================================ FILE: coding_interviews/leetcode/easy/delete_columns_to_make_sorted/delete_columns_to_make_sorted.py ================================================ # https://leetcode.com/problems/delete-columns-to-make-sorted def min_deletion_size(strs): counter = 0 for col in range(len(strs[0])): column = [] for row in range(len(strs)): column.append(strs[row][col]) if column != sorted(column): counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/design-an-ordered-stream/design-an-ordered-stream.js ================================================ const OrderedStream = function (n) { this.n = n; this.key = 1; this.hashmap = new Map(); }; OrderedStream.prototype.insert = function (idKey, value) { this.hashmap.set(idKey, value); if (this.key === idKey) { const chunk = []; for (let index = this.key; index <= this.n + 1; index++) { if (this.hashmap.has(index)) { const value = this.hashmap.get(index); chunk.push(value); this.hashmap.delete(index); this.key++; } else { return chunk; } } } return []; }; ================================================ FILE: coding_interviews/leetcode/easy/design-hashmap/design-hashmap.js ================================================ const MyHashMap = function () { this.map = []; }; MyHashMap.prototype.put = function (key, value) { let found = false; this.map.forEach(([k], index) => { if (key === k) { this.map[index] = [key, value]; found = true; } }); if (!found) this.map.push([key, value]); }; MyHashMap.prototype.get = function (key) { let value = -1; this.map.forEach(([k, v]) => { if (key === k) { value = v; } }); return value; }; MyHashMap.prototype.remove = function (key) { this.map.forEach(([k], index) => { if (key === k) { this.map = [...this.map.slice(0, index), ...this.map.slice(index + 1)]; } }); }; ================================================ FILE: coding_interviews/leetcode/easy/design-hashset/design-hashset.js ================================================ const MyHashSet = function () { this.hashmap = new Map(); }; MyHashSet.prototype.add = function (key) { this.hashmap.set(key, true); }; MyHashSet.prototype.remove = function (key) { this.hashmap.delete(key); }; MyHashSet.prototype.contains = function (key) { return this.hashmap.has(key); }; ================================================ FILE: coding_interviews/leetcode/easy/design_parking_system/design_parking_system.py ================================================ # https://leetcode.com/problems/design-parking-system class ParkingSystem: def __init__(self, big, medium, small): self.big = big self.medium = medium self.small = small def add_car(self, car_type): if car_type == 1: if self.big >= 1: self.big -= 1 return True else: return False if car_type == 2: if self.medium >= 1: self.medium -= 1 return True else: return False if car_type == 3: if self.small >= 1: self.small -= 1 return True else: return False ================================================ FILE: coding_interviews/leetcode/easy/destination_city/destination_city.py ================================================ def dest_city(paths): all_origins = [] all_destinations = [] for [city1, city2] in paths: all_origins.append(city1) all_destinations.append(city2) return [d for d in all_destinations if d not in all_origins][0] def dest_city(paths): all_origins = set() all_destinations = set() for [city1, city2] in paths: all_origins.add(city1) all_destinations.add(city2) return (all_destinations - all_origins).pop() ================================================ FILE: coding_interviews/leetcode/easy/detect-capital/detect-capital.js ================================================ function allCapitals(word) { return word === word.toUpperCase(); } function allNotCapitals(word) { return word === word.toLowerCase(); } function firstCapital(word) { return allCapitals(word[0]) && allNotCapitals(word.slice(1)); } function detectCapitalUse(word) { return allCapitals(word) || allNotCapitals(word) || firstCapital(word); } ================================================ FILE: coding_interviews/leetcode/easy/determine-if-string-halves-are-alike/determine-if-string-halves-are-alike.js ================================================ const VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']; function getVowelsCount(string) { let count = 0; for (let char of string) { if (VOWELS.includes(char)) count++; } return count; } function halvesAreAlike(s) { let halfIndex = s.length / 2; let firstHalf = s.slice(0, halfIndex); let secondHalf = s.slice(halfIndex); let firstHalfVowelsCount = getVowelsCount(firstHalf); let secondHalfVowelsCount = getVowelsCount(secondHalf); return firstHalfVowelsCount === secondHalfVowelsCount; } ================================================ FILE: coding_interviews/leetcode/easy/determine_color_of_a_chessboard_square/determine_color_of_a_chessboard_square.py ================================================ # https://leetcode.com/problems/determine-color-of-a-chessboard-square/ mapper = { 'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8 } def is_even(num): return num % 2 == 0 def square_is_white(coordinates): x, y = mapper[coordinates[0]], int(coordinates[1]) if x == y or (is_even(x - y)): return False return True def square_is_white(coordinates): x, y = mapper[coordinates[0]], int(coordinates[1]) return not (x == y or (is_even(x - y))) def square_is_white(coordinates): return ord(coordinates[0]) % 2 != int(coordinates[1]) % 2 ================================================ FILE: coding_interviews/leetcode/easy/di_string_match/di_string_match.py ================================================ # https://leetcode.com/problems/di-string-match def di_string_match(S): permutation, top, bottom = [], len(S), 0 for char in S: if char == 'I': permutation.append(bottom) bottom += 1 else: permutation.append(top) top -= 1 permutation.append(top) return permutation ================================================ FILE: coding_interviews/leetcode/easy/difference-between-element-sum-and-digit-sum-of-an-array/difference-between-element-sum-and-digit-sum-of-an-array.js ================================================ function getDigitsSum(num) { let digits = 0; let numString = num.toString(); for (let numChar of numString) { digits += Number(numChar); } return digits; } function differenceOfSum(nums) { let elementSum = 0; let digitSum = 0; for (let num of nums) { elementSum += num; digitSum += getDigitsSum(num); } return Math.abs(elementSum - digitSum); } ================================================ FILE: coding_interviews/leetcode/easy/discount_price/discount_price.py ================================================ def finalPrices(prices): result = [] for index, price in enumerate(prices): discount = get_discount(prices, index, price) result.append(price - discount) return result def get_discount(prices, index, price): for other_price in prices[index + 1:]: if other_price <= price: return other_price return 0 ================================================ FILE: coding_interviews/leetcode/easy/distribute-candies-among-children-i/distribute-candies-among-children-i.js ================================================ // https://leetcode.com/problems/distribute-candies-among-children-i function distributeCandies(n, limit) { let count = 0; for (let i = limit; i >= 0; i--) { for (let j = limit; j >= 0; j--) { for (let k = limit; k >= 0; k--) { if (i + j + k === n) { count++; } } } } return count; } ================================================ FILE: coding_interviews/leetcode/easy/distribute-candies-among-children-i/distribute-candies-among-children-ii.js ================================================ // https://leetcode.com/problems/distribute-candies-among-children-i function distributeCandies(n, limit) { let count = 0; for (let i = limit; i >= 0; i--) { for (let j = limit; j >= 0; j--) { let k = n - i - j; if (k >= 0 && k <= limit) { count++; } } } return count; } ================================================ FILE: coding_interviews/leetcode/easy/distribute-candies-to-people/distribute-candies-to-people.js ================================================ function initPeopleCandies(numPeople) { let peopleCandies = []; for (let i = 0; i < numPeople; i++) { peopleCandies.push(0); } return peopleCandies; } function distributeCandies(candies, numPeople) { let peopleCandies = initPeopleCandies(numPeople); let numOfCandies = 1; let index = 0; while (candies) { let candiesToAssign = numOfCandies > candies ? candies : numOfCandies; peopleCandies[index] += candiesToAssign; candies -= candiesToAssign; numOfCandies++; index = (index + 1) % numPeople; } return peopleCandies; } ================================================ FILE: coding_interviews/leetcode/easy/divide-a-string-into-groups-of-size-k/divide-a-string-into-groups-of-size-k.js ================================================ function fillChar(lastGroup, fill, length) { let chars = []; for (let i = 1; i <= length; i++) { chars.push(fill); } return lastGroup + chars.join(''); } function divideString(s, k, fill) { let groups = []; let groupSize = 0; let group = []; for (let index = 0; index < s.length; index++) { group.push(s[index]); groupSize++; if (groupSize === k) { groups.push(group.join('')); groupSize = 0; group = []; } else if (index === s.length - 1) { groups.push(group.join('')); } } let lastGroup = groups[groups.length - 1]; let lastGroupLength = lastGroup.length; if (lastGroupLength !== k) { lastGroup = fillChar(lastGroup, fill, k - lastGroupLength); groups[groups.length - 1] = lastGroup; } return groups; } ================================================ FILE: coding_interviews/leetcode/easy/divide-array-into-equal-pairs/divide-array-into-equal-pairs.js ================================================ export function divideArray(nums) { const map = {}; for (let num of nums) { if (map[num]) { map[num] += 1; } else { map[num] = 1; } } let hasEqualPairs = true; for (let num of Object.values(map)) { if (num % 2 !== 0) { hasEqualPairs = false; break; } } return hasEqualPairs; } ================================================ FILE: coding_interviews/leetcode/easy/divide-array-into-equal-pairs/tests/divide-array-into-equal-pairs.test.js ================================================ import { describe, expect, it } from 'vitest'; import { divideArray } from '../divide-array-into-equal-pairs'; describe('divideArray', () => { it('', () => { expect(divideArray([3, 2, 3, 2, 2, 2])).toEqual(true); }); it('', () => { expect(divideArray([1, 2, 3, 4])).toEqual(false); }); it('', () => { expect(divideArray([2, 2])).toEqual(true); }); }); ================================================ FILE: coding_interviews/leetcode/easy/divisible-and-non-divisible-sums-difference/divisible-and-non-divisible-sums-difference.js ================================================ // https://leetcode.com/problems/divisible-and-non-divisible-sums-difference function differenceOfSums(n, m) { let num1 = 0, num2 = 0; for (let num = 1; num <= n; num++) { if (num % m === 0) num2 += num; else num1 += num; } return num1 - num2; } ================================================ FILE: coding_interviews/leetcode/easy/divisor-game/divisor-game.js ================================================ // https://leetcode.com/problems/divisor-game function divisorGame(n) { return n % 2 === 0; } ================================================ FILE: coding_interviews/leetcode/easy/equal_reversed_arrays/equal_reversed_arrays.py ================================================ # https://leetcode.com/problems/make-two-arrays-equal-by-reversing-sub-arrays ''' Given two integer arrays of equal length target and arr. In one step, you can select any non-empty sub-array of arr and reverse it. You are allowed to make any number of steps. Return True if you can make arr equal to target, or False otherwise. Input: target = [1,2,3,4], arr = [2,4,1,3] Output: true Input: target = [7], arr = [7] Output: true Input: target = [1,12], arr = [12,1] Output: true ''' # 0(nlogn) def can_be_equal(target, arr): return target == arr or sorted(target) == sorted(arr) # 0(n) def can_be_equal(target, arr): counter = {} for index in range(len(target)): target_item, arr_item = target[index], arr[index] if target_item in counter: counter[target_item] += 1 else: counter[target_item] = 1 if arr_item in counter: counter[arr_item] += 1 else: counter[arr_item] = 1 for _, value in counter.items(): if value % 2 != 0: return False return True def can_be_equal(target, arr): return collections.Counter(target) == collections.Counter(arr) ================================================ FILE: coding_interviews/leetcode/easy/evaluate-boolean-binary-tree/evaluate-boolean-binary-tree.js ================================================ const values = { or: 2, and: 3, }; function evaluateTree(root) { if ([0, 1].includes(root.val)) return Boolean(root.val); const left = evaluateTree(root.left); const right = evaluateTree(root.right); return root.val === values.or ? left || right : left && right; } ================================================ FILE: coding_interviews/leetcode/easy/even_digits/even_digits.py ================================================ # https://leetcode.com/problems/find-numbers-with-even-number-of-digits/ def find_numbers(nums): counter = 0 for num in nums: if len(str(num)) % 2 == 0: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/excel-sheet-column-number/excel-sheet-column-number.js ================================================ function toNumber(char) { return char.charCodeAt(0) - 64; } function titleToNumber(columnTitle) { let columnNumber = 0; for (let col of columnTitle) { const num = toNumber(col); columnNumber = columnNumber * 26 + num; } return columnNumber; } ================================================ FILE: coding_interviews/leetcode/easy/fair-candy-swap/fair-candy-swap-optimized.js ================================================ function sum(nums) { let sumOfNums = 0; for (let num of nums) { sumOfNums += num; } return sumOfNums; } function buildMap(bobSizes) { let hashmap = new Map(); for (let bobSize of bobSizes) { hashmap.set(bobSize, bobSize); } return hashmap; } function fairCandySwap(aliceSizes, bobSizes) { let aliceCandies = sum(aliceSizes); let bobCandies = sum(bobSizes); let hashmap = buildMap(bobSizes); for (let aliceSize of aliceSizes) { let bobCandy = (bobCandies + 2 * aliceSize - aliceCandies) / 2; if (hashmap.has(bobCandy)) { return [aliceSize, bobCandy]; } } } ================================================ FILE: coding_interviews/leetcode/easy/fair-candy-swap/fair-candy-swap.js ================================================ function sum(nums) { let sumOfNums = 0; for (let num of nums) { sumOfNums += num; } return sumOfNums; } function fairCandySwap(aliceSizes, bobSizes) { let aliceCandies = sum(aliceSizes); let bobCandies = sum(bobSizes); for (let i = 0; i < aliceSizes.length; i++) { for (let j = 0; j < bobSizes.length; j++) { let aliceCandy = aliceSizes[i]; let bobCandy = bobSizes[j]; if ( aliceCandies - aliceCandy + bobCandy === bobCandies - bobCandy + aliceCandy ) { return [aliceCandy, bobCandy]; } } } } ================================================ FILE: coding_interviews/leetcode/easy/faulty-keyboard/faulty-keyboard.js ================================================ // https://leetcode.com/problems/faulty-keyboard function reverse(s) { let reversedS = []; for (let index = s.length - 1; index >= 0; index--) { reversedS.push(s[index]); } return reversedS; } function finalString(s) { let subS = []; for (let char of s) { if (char === 'i') subS = reverse(subS); else subS.push(char); } return subS.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/fibonacci_number/fibonacci_number.py ================================================ # https://leetcode.com/problems/fibonacci-number def fib(n): cache = [0, 1] prev_1, prev_2 = 0, 1 if n == 0: return 0 if n == 1: return 1 for _ in range(2, n + 1): cache.append(cache[prev_1] + cache[prev_2]) prev_1 += 1 prev_2 += 1 return cache[-1] ================================================ FILE: coding_interviews/leetcode/easy/final-value-after-operations/final-value-after-operations.js ================================================ /* There is a programming language with only four operations and one variable X: ++X and X++ increments the value of the variable X by 1. --X and X-- decrements the value of the variable X by 1. Initially, the value of X is 0. Given an array of strings operations containing a list of operations, return the final value of X after performing all the operations. # Example 1 Input: operations = ["--X","X++","X++"] Output: 1 Explanation: The operations are performed as follows: Initially, X = 0. --X: X is decremented by 1, X = 0 - 1 = -1. X++: X is incremented by 1, X = -1 + 1 = 0. X++: X is incremented by 1, X = 0 + 1 = 1. # Example 2 Input: operations = ["++X","++X","X++"] Output: 3 Explanation: The operations are performed as follows: Initially, X = 0. ++X: X is incremented by 1, X = 0 + 1 = 1. ++X: X is incremented by 1, X = 1 + 1 = 2. X++: X is incremented by 1, X = 2 + 1 = 3. # Example 3 Input: operations = ["X++","++X","--X","X--"] Output: 0 Explanation: The operations are performed as follows: Initially, X = 0. X++: X is incremented by 1, X = 0 + 1 = 1. ++X: X is incremented by 1, X = 1 + 1 = 2. --X: X is decremented by 1, X = 2 - 1 = 1. X--: X is decremented by 1, X = 1 - 1 = 0. */ const operationsMap = { '--X': -1, 'X--': -1, '++X': +1, 'X++': +1, }; function finalValueAfterOperations(operations = []) { let x = 0; operations.forEach((operation) => { x += operationsMap[operation]; }); return x; } console.log(finalValueAfterOperations(['--X', 'X++', 'X++']), 1); console.log(finalValueAfterOperations(['++X', '++X', 'X++']), 3); console.log(finalValueAfterOperations(['X++', '++X', '--X', 'X--']), 0); ================================================ FILE: coding_interviews/leetcode/easy/find-all-k-distant-indices-in-an-array/find-all-k-distant-indices-in-an-array.js ================================================ function getJs(nums, key) { let js = []; for (let index = 0; index < nums.length; index++) { if (nums[index] === key) js.push(index); } return js; } function isKDistant(index, js, k) { for (let j of js) { if (Math.abs(index - j) <= k) return true; } return false; } function findKDistantIndices(nums, key, k) { const js = getJs(nums, key); const output = []; console.log('js', js); for (let index = 0; index < nums.length; index++) { if (isKDistant(index, js, k)) { output.push(index); } } return output; } ================================================ FILE: coding_interviews/leetcode/easy/find-all-numbers-disappeared-in-an-array/find-all-numbers-disappeared-in-an-array.js ================================================ function buildMap(nums) { let hashmap = new Map(); for (let num of nums) { hashmap.set(num, true); } return hashmap; } function findDisappearedNumbers(nums) { let hashmap = buildMap(nums); let output = []; for (let num = 1; num <= nums.length; num++) { if (!hashmap.has(num)) output.push(num); } return output; } ================================================ FILE: coding_interviews/leetcode/easy/find-center-of-star-graph/find-center-of-star-graph.js ================================================ function addConnection(nodeToConnectionsCount, node) { if (nodeToConnectionsCount[node]) { nodeToConnectionsCount[node]++; } else { nodeToConnectionsCount[node] = 1; } } function findCenter(edges) { let nodeToConnectionsCount = {}; for (let [first, second] of edges) { addConnection(nodeToConnectionsCount, first); addConnection(nodeToConnectionsCount, second); } let star; let maxConnections = -Infinity; Object.entries(nodeToConnectionsCount).forEach(([node, count]) => { if (count > maxConnections) { star = node; maxConnections = count; } }); return star; } ================================================ FILE: coding_interviews/leetcode/easy/find-champion-i/find-champion-i-no-map.js ================================================ // https://leetcode.com/problems/find-champion-i function findChampion(grid) { for (let i = 0; i < grid.length; i++) { let count = 0; for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 1) { count++; } } if (count === grid.length - 1) { return i; } } } ================================================ FILE: coding_interviews/leetcode/easy/find-champion-i/find-champion-i.js ================================================ // https://leetcode.com/problems/find-champion-i function findChampion(grid) { let winners = new Map(); for (let i = 0; i < grid.length; i++) { for (let j = 0; j < grid[i].length; j++) { if (grid[i][j] === 1) { winners.set(i, (winners.get(i) || 0) + 1); } } } for (let [key, value] of winners.entries()) { if (value === grid.length - 1) { return key; } } } ================================================ FILE: coding_interviews/leetcode/easy/find-first-palindromic-string-in-the-array/find-first-palindromic-string-in-the-array.js ================================================ export function isPalindrome(word) { for (let i = 0; i < Math.floor(word.length / 2); i++) { if (word[i] !== word[word.length - 1 - i]) { return false; } } return true; } export function firstPalindrome(words) { let palindromicWord = ''; for (let i = 0; i < words.length; i++) { if (isPalindrome(words[i])) { palindromicWord = words[i]; break; } } return palindromicWord; } ================================================ FILE: coding_interviews/leetcode/easy/find-first-palindromic-string-in-the-array/tests/find-first-palindromic-string-in-the-array.test.js ================================================ import { describe, expect, it } from 'vitest'; import { firstPalindrome, isPalindrome, } from '../find-first-palindromic-string-in-the-array'; describe('firstPalindrome', () => { it('', () => { expect(firstPalindrome(['abc', 'car', 'ada', 'racecar', 'cool'])).toEqual( 'ada' ); }); it('', () => { expect(firstPalindrome(['notapalindrome', 'racecar'])).toEqual('racecar'); }); it('', () => { expect(firstPalindrome(['def', 'ghi'])).toEqual(''); }); }); describe('isPalindrome', () => { it('', () => { expect(isPalindrome('ada')).toBeTruthy(); }); it('', () => { expect(isPalindrome('')).toBeTruthy(); }); it('', () => { expect(isPalindrome('eda')).toBeFalsy(); }); }); ================================================ FILE: coding_interviews/leetcode/easy/find-greatest-common-divisor-of-array/find-greatest-common-divisor-of-array.js ================================================ // https://leetcode.com/problems/find-greatest-common-divisor-of-array const findSmallestAndLargest = (nums) => { let smallest = Infinity; let largest = -Infinity; for (let i = 0; i < nums.length; i++) { smallest = Math.min(smallest, nums[i]); largest = Math.max(largest, nums[i]); } return [smallest, largest]; }; const gcd = (num1, num2) => (num2 ? gcd(num2, num1 % num2) : num1); const findGCD = (nums) => { const [smallest, largest] = findSmallestAndLargest(nums); return gcd(smallest, largest); }; ================================================ FILE: coding_interviews/leetcode/easy/find-indices-with-index-and-value-difference-i/find-indices-with-index-and-value-difference-i.js ================================================ // https://leetcode.com/problems/find-indices-with-index-and-value-difference-i function findIndices(nums, indexDifference, valueDifference) { for (let i = 0; i < nums.length; i++) { for (let j = 0; j < nums.length; j++) { if ( Math.abs(i - j) >= indexDifference && Math.abs(nums[i] - nums[j]) >= valueDifference ) { return [i, j]; } } } return [-1, -1]; } ================================================ FILE: coding_interviews/leetcode/easy/find-lucky-integer-in-an-array/find-lucky-integer-in-an-array.js ================================================ function buildNumCounter(nums) { let counter = new Map(); for (let num of nums) { if (counter.has(num)) counter.set(num, counter.get(num) + 1); else counter.set(num, 1); } return counter; } function findLucky(nums) { let largestLuckyInteger = -1; let counter = buildNumCounter(nums); for (let num of nums) { if (num === counter.get(num) && num > largestLuckyInteger) { largestLuckyInteger = num; } } return largestLuckyInteger; } ================================================ FILE: coding_interviews/leetcode/easy/find-maximum-number-of-string-pairs/find-maximum-number-of-string-pairs.js ================================================ // https://leetcode.com/problems/find-maximum-number-of-string-pairs function paired(s1, s2) { for (let i = 0; i < s1.length; i++) { if (s1[i] !== s2[s2.length - 1 - i]) { return false; } } return true; } function maximumNumberOfStringPairs(words) { let max = 0; for (let i = 0; i < words.length - 1; i++) { for (let j = i + 1; j < words.length; j++) { if (paired(words[i], words[j])) { max++; } } } return max; } ================================================ FILE: coding_interviews/leetcode/easy/find-nearest-point-that-has-the-same-x-or-y-coordinate/find-nearest-point-that-has-the-same-x-or-y-coordinate.js ================================================ // https://leetcode.com/problems/find-nearest-point-that-has-the-same-x-or-y-coordinate // points = [] - not empty // x and y positive numbers const nearestValidPoint = (x, y, points) => { let minDistance = Infinity; let pointIndex = -1; points.forEach((point, index) => { if (isValid([x, y], point)) { const manhattanDistance = calculateManhattanDistance([x, y], point); if (manhattanDistance < minDistance) { pointIndex = index; minDistance = manhattanDistance; } } }); return pointIndex; }; const isValid = (position, point) => { const [x, y] = position; const [pointX, pointY] = point; return x === pointX || y === pointY; }; const calculateManhattanDistance = (position, point) => { const [x, y] = position; const [pointX, pointY] = point; return Math.abs(x - pointX) + Math.abs(y - pointY); }; ================================================ FILE: coding_interviews/leetcode/easy/find-subarrays-with-equal-sum/find-subarrays-with-equal-sum.js ================================================ function findSubarrays(nums) { for (let i = 0; i < nums.length - 2; i++) { for (let j = i + 1; j < nums.length - 1; j++) { if (nums[i] + nums[i + 1] === nums[j] + nums[j + 1]) return true; } } return false; } ================================================ FILE: coding_interviews/leetcode/easy/find-target-indices-after-sorting-array/find-target-indices-after-sorting-array.js ================================================ export function targetIndices(nums, target) { const sortedNums = nums.sort((num1, num2) => num1 - num2); const result = []; sortedNums.forEach((num, index) => { if (num === target) { result.push(index); } }); return result; } ================================================ FILE: coding_interviews/leetcode/easy/find-target-indices-after-sorting-array/tests/find-target-indices-after-sorting-array.test.js ================================================ import { describe, expect, it } from 'vitest'; import { targetIndices } from '../find-target-indices-after-sorting-array'; describe('targetIndices', () => { it('', () => { expect( targetIndices( [ 48, 90, 9, 21, 31, 35, 19, 69, 29, 52, 100, 54, 21, 86, 6, 45, 42, 5, 62, 77, 15, 38, ], 6 ) ).toEqual([1]); }); it('', () => { expect(targetIndices([1, 2, 5, 2, 3], 2)).toEqual([1, 2]); }); it('', () => { expect(targetIndices([1, 2, 5, 2, 3], 3)).toEqual([3]); }); it('', () => { expect(targetIndices([1, 2, 5, 2, 3], 5)).toEqual([4]); }); }); ================================================ FILE: coding_interviews/leetcode/easy/find-the-array-concatenation-value/find-the-array-concatenation-value.js ================================================ function concat(num1, num2) { return Number(num1.toString() + num2.toString()); } function findTheArrayConcVal(nums) { let pointer1 = 0; let pointer2 = nums.length - 1; let output = 0; while (pointer1 <= pointer2) { if (pointer1 === pointer2) output += nums[pointer1]; else output += concat(nums[pointer1], nums[pointer2]); pointer1++; pointer2--; } return output; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-difference/find-the-difference.js ================================================ function buildMap(string) { let hashmap = new Map(); for (let char of string) { if (hashmap.has(char)) hashmap.set(char, hashmap.get(char) + 1); else hashmap.set(char, 1); } return hashmap; } function findTheDifference(s, t) { let hashmap = buildMap(s); for (let char of t) { if (hashmap.has(char) && hashmap.get(char) > 0) { hashmap.set(char, hashmap.get(char) - 1); continue; } return char; } } ================================================ FILE: coding_interviews/leetcode/easy/find-the-difference-of-two-arrays/find-the-difference-of-two-arrays.js ================================================ function buildHashmap(nums) { let hashmap = new Map(); for (let num of nums) { hashmap.set(num, true); } return hashmap; } function buildDistinct(nums, hashmap) { let distinct = []; for (let num of nums) { if (!hashmap.has(num)) { distinct.push(num); hashmap.set(num, true); } } return distinct; } function findDifference(nums1, nums2) { let hashmap1 = buildHashmap(nums1); let hashmap2 = buildHashmap(nums2); let distinct1 = buildDistinct(nums1, hashmap2); let distinct2 = buildDistinct(nums2, hashmap1); return [distinct1, distinct2]; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-distance-value-between-two-arrays/find-the-distance-value-between-two-arrays.js ================================================ // https://leetcode.com/problems/find-the-distance-value-between-two-arrays function hasSmallerValue(num, arr, d) { for (let number of arr) { if (Math.abs(num - number) <= d) return true; } return false; } function findTheDistanceValue(arr1, arr2, d) { let count = 0; for (let num1 of arr1) { if (!hasSmallerValue(num1, arr2, d)) count++; } return count; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-distinct-difference-array/find-the-distinct-difference-array.js ================================================ // https://leetcode.com/problems/find-the-distinct-difference-array function countDistinct(nums, startIndex, endIndex) { let count = 0; let distinct = new Map(); for (let i = startIndex; i <= endIndex; i++) { if (!distinct.has(nums[i])) { distinct.set(nums[i], nums[i]); count++; } } return count; } function countDistinctPrefix(nums, index) { return countDistinct(nums, 0, index); } function countDistinctSufix(nums, index) { return countDistinct(nums, index + 1, nums.length - 1); } function distinctDifferenceArray(nums) { let diff = []; for (let index = 0; index < nums.length; index++) { let prefix = countDistinctPrefix(nums, index); let sufix = countDistinctSufix(nums, index); diff.push(prefix - sufix); } return diff; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-distinct-difference-array/optimized-find-the-distinct-difference-array.js ================================================ // https://leetcode.com/problems/find-the-distinct-difference-array function distinctDifferenceArray(nums) { let distinctDiff = []; let countInLeft = 0; let countInRight = 0; let leftCounterMap = new Map(); let rightCounterMap = new Map(); for (let num of nums) { if (leftCounterMap.has(num)) { leftCounterMap.set(num, leftCounterMap.get(num) + 1); } else { leftCounterMap.set(num, 1); countInLeft++; } } distinctDiff.unshift(countInLeft - countInRight); for (let index = nums.length - 1; index > 0; index--) { let num = nums[index]; leftCounterMap.set(num, leftCounterMap.get(num) - 1); if (leftCounterMap.get(num) === 0) countInLeft--; rightCounterMap.set(num, (rightCounterMap.get(num) || 0) + 1); if (rightCounterMap.get(num) === 1) countInRight++; distinctDiff.unshift(countInLeft - countInRight); } return distinctDiff; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-maximum-achievable-number/find-the-maximum-achievable-number.js ================================================ // https://leetcode.com/problems/find-the-maximum-achievable-number function theMaximumAchievableX(num, t) { return t * 2 + num; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-middle-index-in-array/find-the-middle-index-in-array.js ================================================ function sum(nums) { return nums.reduce((sumOfNums, num) => sumOfNums + num, 0); } function findMiddleIndex(nums) { let sumOfNums = sum(nums) - nums[0]; let firstHalfSum = 0; let index = 0; while (index < nums.length - 1 && sumOfNums !== firstHalfSum) { sumOfNums -= nums[index + 1]; firstHalfSum += nums[index]; index++; } return sumOfNums === firstHalfSum ? index : -1; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-pivot-integer/find-the-pivot-integer.js ================================================ const NO_PIVOT = -1; function sum(n) { let sumOfNs = 0; for (let num = 1; num <= n; num++) { sumOfNs += num; } return sumOfNs; } function pivotInteger(n) { let sumOfNs = sum(n); let leftSum = 0; for (let num = 1; num <= n; num++) { leftSum += num; if (sumOfNs === leftSum) return num; sumOfNs -= num; } return NO_PIVOT; } ================================================ FILE: coding_interviews/leetcode/easy/find-the-width-of-columns-of-a-grid/find-the-width-of-columns-of-a-grid.js ================================================ // https://leetcode.com/problems/find-the-width-of-columns-of-a-grid function findColumnWidth(grid) { let output = []; for (let col = 0; col < grid[0].length; col++) { let max = -Infinity; for (let row = 0; row < grid.length; row++) { let cell = grid[row][col]; let length = cell.toString().length; max = Math.max(max, length); } output.push(max); } return output; } ================================================ FILE: coding_interviews/leetcode/easy/find-words-containing-character/find-words-containing-character.js ================================================ // https://leetcode.com/problems/find-words-containing-character function findWordsContaining(words, x) { let indices = []; for (let index = 0; index < words.length; index++) { for (let char of words[index]) { if (char === x) { indices.push(index); break; } } } return indices; } ================================================ FILE: coding_interviews/leetcode/easy/find-words-that-can-be-formed-by-characters/find-words-that-can-be-formed-by-characters.js ================================================ function buildCounter(chars) { let counter = new Map(); for (let char of chars) { if (counter.has(char)) counter.set(char, counter.get(char) + 1); else counter.set(char, 1); } return counter; } function isGood(word, counterCopy) { for (let char of word) { if (counterCopy.has(char) && counterCopy.get(char) > 0) counterCopy.set(char, counterCopy.get(char) - 1); else return false; } return true; } function countCharacters(words, chars) { let counter = buildCounter(chars); let counterCopy; let goodWords = []; for (let word of words) { counterCopy = new Map(counter); if (isGood(word, counterCopy)) goodWords.push(word); } return goodWords.reduce((lengths, word) => lengths + word.length, 0); } ================================================ FILE: coding_interviews/leetcode/easy/find_common_characters/find_common_characters.py ================================================ # https://leetcode.com/problems/find-common-characters def common_chars(A): if len(A) == 1: return [char for char in A] word = A[0] words = A[1:] result = [] for char in word: all = True for index, other_word in enumerate(words): if char in other_word: other_word_index = other_word.index(char) words[index] = words[index][:other_word_index] + words[index][other_word_index+1:] else: all = False break if all: result.append(char) return result ================================================ FILE: coding_interviews/leetcode/easy/find_the_highest_altitude/find_the_highest_altitude.py ================================================ # https://leetcode.com/problems/find-the-highest-altitude def largest_altitude(gain): highest_altitude, current_altitude = 0, 0 for net_gain in gain: current_altitude += net_gain if current_altitude > highest_altitude: highest_altitude = current_altitude return highest_altitude ================================================ FILE: coding_interviews/leetcode/easy/first-bad-version/first-bad-version-binary-search.js ================================================ function getMiddle(start, end) { return Math.floor((start + end) / 2); } function binarySearchFirstBadVersion(isBadVersion) { return (n) => { let start = 1; let end = n; let middle = getMiddle(start, end); let firstBadVersion = middle; while (start < end) { if (isBadVersion(middle)) { end = middle - 1; } else { start = middle + 1; } middle = getMiddle(start, end); if (isBadVersion(middle)) { firstBadVersion = middle; } } return firstBadVersion; }; } function solution(isBadVersion) { return binarySearchFirstBadVersion(isBadVersion); } ================================================ FILE: coding_interviews/leetcode/easy/first-bad-version/first-bad-version.js ================================================ function solution(isBadVersion) { return function (n) { for (let version = 1; version <= n; version++) { if (isBadVersion(version)) { return version; } } }; } ================================================ FILE: coding_interviews/leetcode/easy/first-letter-to-appear-twice/first-letter-to-appear-twice.js ================================================ function repeatedCharacter(s) { let counter = new Map(); for (let char of s) { if (counter.has(char)) { return char; } counter.set(char, 1); } } ================================================ FILE: coding_interviews/leetcode/easy/first-unique-character-in-a-string/first-unique-character-in-a-string.js ================================================ function firstUniqChar(s) { let charCount = {}; for (let char of s) { if (charCount[char]) { charCount[char]++; } else { charCount[char] = 1; } } for (let index = 0; index < s.length; index++) { if (charCount[s[index]] === 1) { return index; } } return -1; } ================================================ FILE: coding_interviews/leetcode/easy/first_bad_version/first_bad_version.py ================================================ ''' Approach #1 (Linear Scan) [Time Limit Exceeded] The straight forward way is to brute force it by doing a linear scan. Complexity analysis Time complexity : O(n)O(n). Assume that isBadVersion(version)isBadVersion(version) takes constant time to check if a version is bad. It takes at most n - 1n−1 checks, therefore the overall time complexity is O(n)O(n). Space complexity : O(1)O(1). Approach #2 (Binary Search) [Accepted] It is not difficult to see that this could be solved using a classic algorithm - Binary search. Let us see how the search space could be halved each time below. Scenario #1: isBadVersion(mid) => false 1 2 3 4 5 6 7 8 9 G G G G G G B B B G = Good, B = Bad | | | left mid right Let us look at the first scenario above where isBadVersion(mid) \Rightarrow falseisBadVersion(mid)⇒false. We know that all versions preceding and including midmid are all good. So we set left = mid + 1left=mid+1 to indicate that the new search space is the interval [mid + 1, right][mid+1,right] (inclusive). Scenario #2: isBadVersion(mid) => true 1 2 3 4 5 6 7 8 9 G G G B B B B B B G = Good, B = Bad | | | left mid right The only scenario left is where isBadVersion(mid) \Rightarrow trueisBadVersion(mid)⇒true. This tells us that midmid may or may not be the first bad version, but we can tell for sure that all versions after midmid can be discarded. Therefore we set right = midright=mid as the new search space of interval [left,mid][left,mid] (inclusive). In our case, we indicate leftleft and rightright as the boundary of our search space (both inclusive). This is why we initialize left = 1left=1 and right = nright=n. How about the terminating condition? We could guess that leftleft and rightright eventually both meet and it must be the first bad version, but how could you tell for sure? The formal way is to prove by induction, which you can read up yourself if you are interested. Here is a helpful tip to quickly prove the correctness of your binary search algorithm during an interview. We just need to test an input of size 2. Check if it reduces the search space to a single element (which must be the answer) for both of the scenarios above. If not, your algorithm will never terminate. If you are setting mid = \frac{left + right}{2}mid= 2 left+right ​ , you have to be very careful. Unless you are using a language that does not overflow such as Python, left + rightleft+right could overflow. One way to fix this is to use left + \frac{right - left}{2}left+ 2 right−left ​ instead. If you fall into this subtle overflow bug, you are not alone. Even Jon Bentley's own implementation of binary search had this overflow bug and remained undetected for over twenty years. Complexity analysis Time complexity : O(logn). The search space is halved each time, so the time complexity is O(\log n)O(logn). Space complexity : O(1). ''' def is_bad_version(version): True def first_bad_version(n): start = 1 last = n while start < last: middle = (start + last) / 2 if is_bad_version(middle): last = middle else: start = middle + 1 return start ================================================ FILE: coding_interviews/leetcode/easy/fizz-buzz/fizz-buzz.js ================================================ function fizzBuzz(n) { const answer = []; for (let i = 1; i <= n; i++) { if (i % 3 === 0 && i % 5 === 0) { answer.push('FizzBuzz'); continue; } if (i % 3 === 0) { answer.push('Fizz'); continue; } if (i % 5 === 0) { answer.push('Buzz'); continue; } answer.push(String(i)); } return answer; } ================================================ FILE: coding_interviews/leetcode/easy/flipping_an_image.py ================================================ # https://leetcode.com/problems/flipping-an-image/description/ # input: [[1,1,0], [1,0,1], [0,0,0]] # output: [[1,0,0], [0,1,0], [1,1,1]] def flip_and_invert_image(image): for i in range(len(image)): image[i] = image[i][::-1] for i in range(len(image)): for j in range(len(image[i])): image[i][j] = 1 - image[i][j] return image print(flip_and_invert_image([[1,1,0], [1,0,1], [0,0,0]])) ================================================ FILE: coding_interviews/leetcode/easy/flood-fill/flood-fill-without-visited.js ================================================ function isInsideTheGrid(image, row, col) { const validRow = row >= 0 && row < image.length; const validCol = col >= 0 && col < image[0].length; return validRow && validCol; } function dfs(image, row, col, newColor, startingPixel) { if (isInsideTheGrid(image, row, col) && image[row][col] === startingPixel) { image[row][col] = newColor; dfs(image, row - 1, col, newColor, startingPixel); dfs(image, row, col + 1, newColor, startingPixel); dfs(image, row, col - 1, newColor, startingPixel); dfs(image, row + 1, col, newColor, startingPixel); } } function floodFill(image, row, col, newColor) { if (image[row][col] !== newColor) { dfs(image, row, col, newColor, image[row][col]); } return image; } ================================================ FILE: coding_interviews/leetcode/easy/flood-fill/flood-fill.js ================================================ /** - is it inside the grid? - is it equal to the target value? - update the pixe with newColor - recursive call for: top, left, right, bottom */ function isInsideTheGrid(image, row, col) { const validRow = row >= 0 && row < image.length; const validCol = col >= 0 && col < image[0].length; return validRow && validCol; } function floodFillHelper(image, sr, sc, newColor, startingPixel, visited) { if (isInsideTheGrid(image, sr, sc)) { let currentPixel = image[sr][sc]; if (currentPixel === startingPixel && !visited[sr][sc]) { image[sr][sc] = newColor; visited[sr][sc] = true; let topPosition = { row: sr - 1, col: sc, }; let rightPosition = { row: sr, col: sc + 1, }; let leftPosition = { row: sr, col: sc - 1, }; let bottomPosition = { row: sr + 1, col: sc, }; floodFillHelper( image, topPosition.row, topPosition.col, newColor, startingPixel, visited ); floodFillHelper( image, rightPosition.row, rightPosition.col, newColor, startingPixel, visited ); floodFillHelper( image, leftPosition.row, leftPosition.col, newColor, startingPixel, visited ); floodFillHelper( image, bottomPosition.row, bottomPosition.col, newColor, startingPixel, visited ); } } } function buildVisitedMatrix(image) { let matrix = []; for (let row = 0; row < image.length; row++) { let r = []; for (let col = 0; col < image[row].length; col++) { r.push(false); } matrix.push(r); } return matrix; } function floodFill(image, sr, sc, newColor) { let visited = buildVisitedMatrix(image); floodFillHelper(image, sr, sc, newColor, image[sr][sc], visited); return image; } ================================================ FILE: coding_interviews/leetcode/easy/furthest-point-from-origin/furthest-point-from-origin.js ================================================ // https://leetcode.com/problems/furthest-point-from-origin function furthestDistanceFromOrigin(moves) { let diff = 0; let underlines = 0; for (let move of moves) { if (move === '_') underlines++; if (move === 'R') diff++; if (move === 'L') diff--; } return Math.abs(diff) + underlines; } ================================================ FILE: coding_interviews/leetcode/easy/generate_the_string/generate_the_string.py ================================================ # https://leetcode.com/problems/generate-a-string-with-characters-that-have-odd-counts def generate_the_string(n): if n % 2 == 0: return 'a' * (n - 1) + 'b' return 'a' * n ================================================ FILE: coding_interviews/leetcode/easy/goal_parser_interpretation/goal_parser_interpretation.py ================================================ # https://leetcode.com/problems/goal-parser-interpretation def interpret(command): result, empty_paren = [], True for char in command: if char == 'G': result.append('G') else: if char == ')': if empty_paren: result.append('o') else: result.append('al') empty_paren = True elif char != '(': empty_paren = False return ''.join(result) ================================================ FILE: coding_interviews/leetcode/easy/greatest-english-letter-in-upper-and-lower-case/greatest-english-letter-in-upper-and-lower-case.js ================================================ function greatestLetter(string) { let greatest = [-Infinity, '']; let charsToCode = new Map(); for (let char of string) { let lowerCasedChar = char.toLowerCase(); let charCode = char.charCodeAt(); if ( charsToCode.has(lowerCasedChar) && charsToCode.get(lowerCasedChar) !== charCode ) { const greaterCharCode = Math.max( charCode, charsToCode.get(lowerCasedChar) ); greatest = greaterCharCode > greatest[0] ? [greaterCharCode, char.toUpperCase()] : greatest; } else if (!charsToCode.has(lowerCasedChar)) { charsToCode.set(lowerCasedChar, charCode); } } return greatest[1]; } ================================================ FILE: coding_interviews/leetcode/easy/greatest_candies/greatest_candies.py ================================================ # https://leetcode.com/problems/kids-with-the-greatest-number-of-candies/ ''' [2, 3, 3, 1, 3] 2 [True, True, True, True, True] ''' def kids_with_candies(candies, extra_candies): greatest = get_greatest(candies) return map_can_be_greatest(candies, extra_candies, greatest) def map_can_be_greatest(candies, extra_candies, greatest_candy): greatest_possibilities = [] for candy in candies: greatest_possibilities.append(candy + extra_candies >= greatest_candy) return greatest_possibilities def get_greatest(candies): greatest = candies[0] for candy in candies: if candy > greatest: greatest = candy return greatest data_tests = [ ([2, 3, 3, 1, 3], 2, [True, True, True, True, True]), ([4, 2, 1, 1, 2], 1, [True, False, False, False, False]), ([12, 1, 12], 10, [True, False, True]), ] for candies, extra_candies, expected in data_tests: result = kids_with_candies(candies, extra_candies) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/guess-number-higher-or-lower/guess-number-higher-or-lower.js ================================================ // https://leetcode.com/problems/guess-number-higher-or-lower function guessNumber(n) { let start = 1; let end = n; let middle = Math.round(n / 2); while (guess(middle)) { if (guess(middle) > 0) { start = middle + 1; } else { end = middle - 1; } middle = Math.round(end + start) / 2; } return middle; } ================================================ FILE: coding_interviews/leetcode/easy/halves_are_alike/halves_are_alike.py ================================================ # https://leetcode.com/problems/determine-if-string-halves-are-alike/ def halves_are_alike(s): vowels = { 'a': True, 'e': True, 'i': True, 'o': True, 'u': True, 'A': True, 'E': True, 'I': True, 'O': True, 'U': True, } middle_index = len(s) // 2 a, b = s[:middle_index], s[middle_index:] a_counter, b_counter = 0, 0 for char in a: if char in vowels: a_counter += 1 for char in b: if char in vowels: b_counter += 1 return a_counter == b_counter ================================================ FILE: coding_interviews/leetcode/easy/hamming_distance/hamming_distance.py ================================================ def get_bit(number): return "{0:b}".format(number) def hamming_distance(x, y): x_bit = get_bit(x) y_bit = get_bit(y) min_len = min(len(x_bit), len(y_bit)) max_len = max(len(x_bit), len(y_bit)) diff_len = max_len - min_len if len(x_bit) > len(y_bit): max_bit = x_bit min_bit = y_bit else: max_bit = y_bit min_bit = x_bit min_bit = '0' * diff_len + min_bit counter = 0 for index in range(max_len): if max_bit[index] != min_bit[index]: counter += 1 return counter def hamming_distance_2(x, y): counter = 0 while x or y: if (x % 2) != (y % 2): counter += 1 x //= 2 y //= 2 return counter ================================================ FILE: coding_interviews/leetcode/easy/height_checker/height_checker.py ================================================ # https://leetcode.com/problems/height-checker def height_checker(heights): sorted_heights, counter = sorted(heights), 0 for index in range(len(heights)): if heights[index] != sorted_heights[index]: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/implement-queue-using-stacks/implement-queue-using-stacks.js ================================================ const MyQueue = function () { this.list = []; }; MyQueue.prototype.push = function (x) { this.list.push(x); }; MyQueue.prototype.pop = function () { return this.list.shift(); }; MyQueue.prototype.peek = function () { return this.list[0]; }; MyQueue.prototype.empty = function () { return this.list.length === 0; }; ================================================ FILE: coding_interviews/leetcode/easy/implement-stack-using-queues/implement-stack-using-queues.js ================================================ function MyStack() { this.items = []; } MyStack.prototype.push = function (x) { this.items.push(x); }; MyStack.prototype.pop = function () { return this.items.pop(); }; MyStack.prototype.top = function () { return this.items.at(-1); }; MyStack.prototype.empty = function () { return this.items.length === 0; }; ================================================ FILE: coding_interviews/leetcode/easy/increasing_decreasing_string/incresing_decreasin_string.py ================================================ # https://leetcode.com/problems/increasing-decreasing-string/ def sort_string(s): result = [] while len(s): last_appended, to_be_appended, chosen_index = float('-Inf'), float('Inf'), float('Inf') while chosen_index is not None: chosen_index = None for index, char in enumerate(s): unicode_char = ord(char) if unicode_char > last_appended and unicode_char < to_be_appended: to_be_appended = unicode_char chosen_index = index if chosen_index is not None: result.append(chr(to_be_appended)) last_appended = to_be_appended to_be_appended = float('Inf') s = s[0:chosen_index] + s[chosen_index+1:] last_appended, to_be_appended, chosen_index = float('Inf'), float('-Inf'), float('Inf') while chosen_index is not None: chosen_index = None for index, char in enumerate(s): unicode_char = ord(char) if unicode_char < last_appended and unicode_char > to_be_appended: to_be_appended = unicode_char chosen_index = index if chosen_index is not None: result.append(chr(to_be_appended)) last_appended = to_be_appended to_be_appended = float('-Inf') s = s[0:chosen_index] + s[chosen_index+1:] return ''.join(result) ================================================ FILE: coding_interviews/leetcode/easy/increasing_order_search_tree/increasing_order_search_tree.py ================================================ def increasingBST(root): arr = [] helper(root, arr) ans = current = TreeNode(arr[0]) for val in arr[1:]: current.right = TreeNode(val) current = current.right return ans def helper(self, old_tree, arr): if old_tree.left: helper(old_tree.left, arr) arr.append(old_tree.val) if old_tree.right: helper(old_tree.right, arr) ================================================ FILE: coding_interviews/leetcode/easy/intersection-of-multiple-arrays/intersection-of-multiple-arrays.js ================================================ function intersection(nums) { const numberCounts = new Map(); const numsLength = nums.length; const intersectionNums = []; for (let numsList of nums) { for (let num of numsList) { if (numberCounts.has(num)) { numberCounts.set(num, numberCounts.get(num) + 1); } else { numberCounts.set(num, 1); } } } for (let [num, count] of numberCounts.entries()) { if (count === numsLength) { intersectionNums.push(num); } } return intersectionNums.sort((a, b) => a - b); } ================================================ FILE: coding_interviews/leetcode/easy/intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.js ================================================ /* nums1 = [1,2,2,1], nums2 = [2,2] => [2] => [] result = [2,2] Runtime: O(N^3) Space: O(N) nums1 = [1,2,2,1], nums2 = [2,2] hashmap = { 1: 2, 2: 2 }; => { 1: 2, 2: 1 }; => { 1: 2, 2: 0 }; result = [2, 2] Runtime: O(N) + O(N) => O(N) Space: O(N) + O(N) => O(N) */ function intersect(nums1, nums2) { let numsCount = {}; for (let num of nums1) { if (numsCount[num]) { numsCount[num]++; } else { numsCount[num] = 1; } } let result = []; for (let num of nums2) { if (numsCount[num]) { numsCount[num]--; result.push(num); } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/intersection_of_two_arrays/intersection_of_two_arrays.py ================================================ # https://leetcode.com/problems/intersection-of-two-arrays/ def intersection(nums1, nums2): intersect_set = set() for num1 in nums1: for num2 in nums2: if num1 == num2: intersect_set.add(num1) return intersect_set def intersection(nums1, nums2): return set(nums1).intersection(nums2) def intersection(nums1, nums2): nums_mapper = {} for num in nums1: nums_mapper[num] = True nums = set() for num in nums2: if num in nums_mapper: nums.add(num) return nums ================================================ FILE: coding_interviews/leetcode/easy/intersection_of_two_arrays_ii/intersection_of_two_arrays.py ================================================ # https://leetcode.com/problems/intersection-of-two-arrays-ii def intersection(nums1, nums2): hash_map = {} for num in nums1: if num in hash_map: hash_map[num] += 1 else: hash_map[num] = 1 nums = [] for num in nums2: if num in hash_map and hash_map[num]: nums.append(num) hash_map[num] -= 1 return nums ================================================ FILE: coding_interviews/leetcode/easy/invert-binary-tree/invert-binary-tree.js ================================================ function invertTree(root) { if (!root) { return root; } let leftNode = root.left; let rightNode = root.right; root.left = invertTree(rightNode); root.right = invertTree(leftNode); return root; } ================================================ FILE: coding_interviews/leetcode/easy/is-subsequence/is-subsequence.js ================================================ // https://leetcode.com/problems/is-subsequence function isSubsequence(s, t) { let sIndex = 0; let tIndex = 0; while (sIndex < s.length && tIndex < t.length) { let sChar = s[sIndex]; let tChar = t[tIndex]; if (sChar === tChar) { sIndex++; tIndex++; } else { tIndex++; } } return sIndex === s.length; } ================================================ FILE: coding_interviews/leetcode/easy/is_palindrome.py ================================================ # https://leetcode.com/problems/palindrome-number/description/ def is_palindrome(x): if x < 0: return False s = '' while x > 0: s += str(x % 10) x /= 10 return s == s[::-1] ================================================ FILE: coding_interviews/leetcode/easy/is_sum_equal/is_sum_equal.py ================================================ # https://leetcode.com/problems/check-if-word-equals-summation-of-two-words alphabet = { 'a': '0', 'b': '1', 'c': '2', 'd': '3', 'e': '4', 'f': '5', 'g': '6', 'h': '7', 'i': '8', 'j': '9', } def get_numerical_value(word): list_of_chars = [] for char in word: list_of_chars.append(alphabet[char]) return int(''.join(list_of_chars)) def is_sum_equal(first_word, second_word, target_word): first_num = get_numerical_value(first_word) second_num = get_numerical_value(second_word) target_num = get_numerical_value(target_word) return first_num + second_num == target_num ================================================ FILE: coding_interviews/leetcode/easy/island-perimeter/island-perimeter.js ================================================ function isOffGrid(grid, row, col) { return row < 0 || row >= grid.length || col < 0 || col >= grid[0].length; } function isWater(grid, row, col) { return grid[row][col] === 0; } function isPartOfIsland(grid, row, col) { return grid[row][col] === 1; } function wasAlreadyVisited(grid, row, col) { return grid[row][col] === 2; } function dfs(grid, row, col) { if (isOffGrid(grid, row, col) || isWater(grid, row, col)) { return 1; } if (wasAlreadyVisited(grid, row, col)) { return 0; } grid[row][col] = 2; return ( dfs(grid, row, col - 1) + dfs(grid, row, col + 1) + dfs(grid, row - 1, col) + dfs(grid, row + 1, col) ); } function islandPerimeter(grid) { let perimeter = 0; for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length; col++) { if (isPartOfIsland(grid, row, col)) { perimeter += dfs(grid, row, col); } } } return perimeter; } ================================================ FILE: coding_interviews/leetcode/easy/jewels_and_stones.py ================================================ # https://leetcode.com/problems/jewels-and-stones/description/ # input: J = "aA" | S = "aAAbbbb" # output: 3 # input: J = "z", S = "ZZ" # output: 0 # Solution: O(N^2) def num_jewels_in_stones(J, S): jewels = 0 for j in J: for s in S: if s == j: jewels += 1 return jewels print(num_jewels_in_stones("aA", "aAAbbbb")) print(num_jewels_in_stones("z", "ZZ")) # Solution: O(N) def num_jewels_in_stones_opt(J, S): number_by_chars = {} counter = 0 for char in J: if char in number_by_chars: number_by_chars[char] += 1 else: number_by_chars[char] = 1 for char in S: if char in number_by_chars: counter += number_by_chars[char] return counter print(num_jewels_in_stones_opt("aA", "aAAbbbb")) print(num_jewels_in_stones_opt("z", "ZZ")) ================================================ FILE: coding_interviews/leetcode/easy/judge_route_circle.py ================================================ ''' https://leetcode.com/problems/judge-route-circle/description/ Example 1: Input: "UD" Output: true Example 2: Input: "LL" Output: false ''' def judge_circle(moves): horizontal, vertical = 0, 0 moves_mapper = { 'U': 1, 'D': -1, 'R': 1, 'L': -1 } for move in moves: if move in ['U', 'D']: vertical += moves_mapper[move] else: horizontal += moves_mapper[move] return horizontal == 0 and vertical == 0 print(judge_circle("UD")) print(judge_circle("LL")) ================================================ FILE: coding_interviews/leetcode/easy/judge_route_circle_one_line.py ================================================ ''' https://leetcode.com/problems/judge-route-circle/description/ Example 1: Input: "UD" Output: true Example 2: Input: "LL" Output: false ''' def judge_circle(moves): return moves.count("U") == moves.count("D") and moves.count("R") == moves.count("L") print(judge_circle("UD")) print(judge_circle("LL")) ================================================ FILE: coding_interviews/leetcode/easy/k-items-with-the-maximum-sum/k-items-with-the-maximum-sum-second.js ================================================ // https://leetcode.com/problems/k-items-with-the-maximum-sum function kItemsWithMaximumSum(numOnes, numZeros, numNegOnes, k) { if (k <= numOnes) { return k; } let sum = 0; if (numOnes) { sum += numOnes; k -= numOnes; } if (k > 0 && numZeros) { k -= numZeros; } if (k > 0 && numNegOnes) { sum -= k; } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/k-items-with-the-maximum-sum/k-items-with-the-maximum-sum.js ================================================ // https://leetcode.com/problems/k-items-with-the-maximum-sum function kItemsWithMaximumSum(numOnes, numZeros, numNegOnes, k) { let max = 0; let mutK = k; mutK -= numOnes; if (mutK <= 0) return k; max += numOnes; mutK -= numZeros; if (mutK <= 0) return max; if (mutK - numNegOnes < 0) return max - mutK; max -= numNegOnes; return max; } ================================================ FILE: coding_interviews/leetcode/easy/keep-multiplying-found-values-by-two/keep-multiplying-found-values-by-two.js ================================================ function findFinalValue(nums, original) { let keepProcessing = true; let originalCopy = original; while (keepProcessing) { let foundOriginal = false; for (let num of nums) { if (num === originalCopy) { foundOriginal = true; } } if (foundOriginal) { originalCopy *= 2; } else { keepProcessing = false; } } return originalCopy; } ================================================ FILE: coding_interviews/leetcode/easy/keyboard-row/keyboard-row.js ================================================ function stringToMap(string) { const map = new Map(); for (let char of string) { map.set(char, true); } return map; } const firstRow = stringToMap('qwertyuiop'); const secondRow = stringToMap('asdfghjkl'); const thirdRow = stringToMap('zxcvbnm'); function belongsToRow(word, row) { for (let char of word) { if (!row.has(char)) { return false; } } return true; } function belongsToSomeRow(word) { let belongsToARow = belongsToRow(word, firstRow); if (belongsToARow) return true; belongsToARow = belongsToRow(word, secondRow); if (belongsToARow) return true; belongsToARow = belongsToRow(word, thirdRow); return belongsToARow; } function findWords(words) { const result = []; for (let word of words) { if (belongsToSomeRow(word.toLowerCase())) { result.push(word); } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/kth-distinct-string-in-an-array/kth-distinct-string-in-an-array.js ================================================ function kthDistinct(arr, k) { let count = 0; let hashmap = new Map(); for (let string of arr) { if (hashmap.has(string)) { hashmap.set(string, hashmap.get(string) + 1); } else { hashmap.set(string, 1); } } let distinctStrings = []; hashmap.forEach((count, string) => { if (count === 1) { distinctStrings.push(string); } }); for (let string of distinctStrings) { count++; if (count === k) return string; } return ''; } function kthDistinct(arr, k) { let hashmap = new Map(); for (let string of arr) { if (hashmap.has(string)) { hashmap.set(string, hashmap.get(string) + 1); } else { hashmap.set(string, 1); } } let distinctStrings = []; hashmap.forEach((count, string) => { if (count === 1) { distinctStrings.push(string); } }); return distinctStrings[k - 1] || ''; } ================================================ FILE: coding_interviews/leetcode/easy/largest-local-values-in-a-matrix/largest-local-values-in-a-matrix.js ================================================ function getLargestFromGrid(grid, startRow, startCol, endRow, endCol) { let largest = -Infinity; for (let row = startRow; row <= endRow; row++) { for (let col = startCol; col <= endCol; col++) { largest = Math.max(largest, grid[row][col]); } } return largest; } function largestLocal(grid) { const generatedGrid = []; for (let row = 0; row < grid.length - 2; row++) { const generatedRow = []; for (let col = 0; col < grid[row].length - 2; col++) { generatedRow.push(getLargestFromGrid(grid, row, col, row + 2, col + 2)); } generatedGrid.push(generatedRow); } return generatedGrid; } ================================================ FILE: coding_interviews/leetcode/easy/largest-number-after-digit-swaps-by-parity/largest-number-after-digit-swaps-by-parity.js ================================================ // https://leetcode.com/problems/largest-number-after-digit-swaps-by-parity const isEven = (num) => num % 2 === 0; const isOdd = (num) => !isEven(num); function largestInteger(num) { let numString = num.toString().split(''); for (let index = 0; index < numString.length - 1; index++) { let digit = Number(numString[index]); let isDigitEven = isEven(digit); let maxDigit = digit; let swapIndex1 = index; let swapIndex2; for ( let digitIndex = index + 1; digitIndex < numString.length; digitIndex++ ) { let otherDigit = Number(numString[digitIndex]); let isOtherDigitEven = isEven(otherDigit); if (isDigitEven && isOtherDigitEven && otherDigit > maxDigit) { maxDigit = otherDigit; swapIndex2 = digitIndex; } if (!isDigitEven && !isOtherDigitEven && otherDigit > maxDigit) { maxDigit = otherDigit; swapIndex2 = digitIndex; } } if (swapIndex2) { let aux = numString[swapIndex1]; numString[swapIndex1] = numString[swapIndex2]; numString[swapIndex2] = aux; } } return numString.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/largest-positive-integer-that-exists-with-its-negative/largest-positive-integer-that-exists-with-its-negative.js ================================================ function findMaxK(nums) { const hashmap = new Map(); for (let num of nums) { if (!hashmap.has(num)) hashmap.set(num, true); } let output = -1; for (let num of nums) { if (num > output && hashmap.has(num * -1)) { output = num; } } return output; } ================================================ FILE: coding_interviews/leetcode/easy/last-stone-weight/last-stone-weight.js ================================================ function getTwoHaviest(stones) { const first = stones[0]; const second = stones[1]; let heaviest = first > second ? first : second; let secondHeaviest = first > second ? second : first; for (let i = 2; i < stones.length; i++) { const stone = stones[i]; if (stone > heaviest) { secondHeaviest = heaviest; heaviest = stone; continue; } if (stone > secondHeaviest) { secondHeaviest = stone; continue; } } return { heaviest, secondHeaviest }; } function removeStone(stones, stoneToBeRemoved) { for (let i = 0; i < stones.length; i++) { if (stones[i] === stoneToBeRemoved) { stones.splice(i, 1); return; } } } function updateStone(stones, stone, stoneWeight) { for (let i = 0; i < stones.length; i++) { if (stones[i] === stone) { stones[i] = stoneWeight; return; } } } export function lastStoneWeight(stones) { while (stones.length > 1) { const { heaviest, secondHeaviest } = getTwoHaviest(stones); if (heaviest === secondHeaviest) { removeStone(stones, heaviest); removeStone(stones, secondHeaviest); } if (heaviest !== secondHeaviest) { updateStone(stones, heaviest, heaviest - secondHeaviest); removeStone(stones, secondHeaviest); } } return stones[0] || 0; } ================================================ FILE: coding_interviews/leetcode/easy/last-stone-weight/tests/last-stone-weight.test.js ================================================ import { describe, expect, it } from 'vitest'; import { lastStoneWeight } from '../last-stone-weight'; describe('lastStoneWeight', () => { it('', () => { expect(lastStoneWeight([2, 7, 4, 1, 8, 1])).toEqual(1); }); it('', () => { expect(lastStoneWeight([1])).toEqual(1); }); it('', () => { expect(lastStoneWeight([2, 2])).toEqual(0); }); it('', () => { expect(lastStoneWeight([10, 4, 2, 10])).toEqual(2); }); }); ================================================ FILE: coding_interviews/leetcode/easy/last-visited-integers/last-visited-integers.js ================================================ // https://leetcode.com/problems/last-visited-integers function getLastInteger(words, lastNumberIndex, consecutivePrevs) { for (let index = lastNumberIndex; index >= 0; index--) { while (words[index] === 'prev') { index--; } if (index < 0) { return -1; } if (consecutivePrevs === 0) { return words[index]; } if (words[index] !== 'prev') { consecutivePrevs--; } } return -1; } function lastVisitedIntegers(words) { let result = []; let consecutivePrevs = 0; let lastNumberIndex; for (let index = 0; index < words.length; index++) { if (words[index] === 'prev') { result.push(getLastInteger(words, lastNumberIndex, consecutivePrevs)); consecutivePrevs++; } else { lastNumberIndex = index; consecutivePrevs = 0; } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/leaf-similar-trees/leaf-similar-trees.js ================================================ /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ function getLeafValueSequence(node, leafValueSequence) { if (!node) return; if (!node.left && !node.right) { leafValueSequence.push(node.val); return; } getLeafValueSequence(node.left, leafValueSequence); getLeafValueSequence(node.right, leafValueSequence); } function hasSimilarLeafSequence(leafValueSequence1, leafValueSequence2) { if (leafValueSequence1.length !== leafValueSequence2.length) return false; for (let index = 0; index < leafValueSequence1.length; index++) { if (leafValueSequence1[index] !== leafValueSequence2[index]) return false; } return true; } function leafSimilar(root1, root2) { let leafValueSequence1 = []; let leafValueSequence2 = []; getLeafValueSequence(root1, leafValueSequence1); getLeafValueSequence(root2, leafValueSequence2); return hasSimilarLeafSequence(leafValueSequence1, leafValueSequence2); } ================================================ FILE: coding_interviews/leetcode/easy/left-and-right-sum-differences/left-and-right-sum-differences.js ================================================ function sum(nums) { let sumOfNums = 0; for (let num of nums) { sumOfNums += num; } return sumOfNums; } function leftRigthDifference(nums) { let rightSum = sum(nums); let leftSum = 0; let previous = 0; let answer = []; for (let num of nums) { leftSum += previous; rightSum -= num; previous = num; answer.push(Math.abs(leftSum - rightSum)); } return answer; } ================================================ FILE: coding_interviews/leetcode/easy/length-of-last-word/length-of-last-word.js ================================================ // https://leetcode.com/problems/length-of-last-word const lengthOfLastWord = (s) => { const words = s.trim().split(' '); return words[words.length - 1].length; }; const lengthOfLastWord = (s) => { let lastWordLength = 0; for (let i = s.length - 1; i >= 0; i--) { if (s[i] !== ' ') lastWordLength++; if (s[i] === ' ' && lastWordLength > 0) break; } return lastWordLength; }; ================================================ FILE: coding_interviews/leetcode/easy/lexicographically-smallest-palindrome/lexicographically-smallest-palindrome.js ================================================ function makeSmallestPalindrome(string) { let start = 0; let end = string.length - 1; let palindrome = []; while (start <= end) { let charCode1 = string.charCodeAt(start); let charCode2 = string.charCodeAt(end); if (charCode1 <= charCode2) { palindrome[start] = string[start]; palindrome[end] = string[start]; } if (charCode2 < charCode1) { palindrome[start] = string[end]; palindrome[end] = string[end]; } start++; end--; } return palindrome.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/linked-list-cycle/linked-list-cycle.js ================================================ function hasCycle(head) { let fast = head; while (fast && fast.next) { head = head.next; fast = fast.next.next; if (head === fast) { return true; } } return false; } ================================================ FILE: coding_interviews/leetcode/easy/longer-contiguous-segments-of-ones-than-zeros/longer-contiguous-segments-of-ones-than-zeros.js ================================================ function checkZeroOnes(s) { let zerosLongestContinuousSegment = 0; let onesLongestContinuousSegment = 0; let zerosContinuousSegment = 0; let onesContinuousSegment = 0; for (let index = 0; index < s.length; index++) { let char = s[index]; if (char === '1') { zerosLongestContinuousSegment = Math.max( zerosLongestContinuousSegment, zerosContinuousSegment ); zerosContinuousSegment = 0; onesContinuousSegment++; } else { onesLongestContinuousSegment = Math.max( onesLongestContinuousSegment, onesContinuousSegment ); onesContinuousSegment = 0; zerosContinuousSegment++; } if (index === s.length - 1) { if (char === '1') { onesLongestContinuousSegment = Math.max( onesLongestContinuousSegment, onesContinuousSegment ); } else { zerosLongestContinuousSegment = Math.max( zerosLongestContinuousSegment, zerosContinuousSegment ); } } } return onesLongestContinuousSegment > zerosLongestContinuousSegment; } ================================================ FILE: coding_interviews/leetcode/easy/longest-nice-substring/longest-nice-substring.js ================================================ function isNice(substring, map) { for (let char of substring) { if (!map.has(char.toLowerCase()) || !map.has(char.toUpperCase())) { return false; } } return true; } function longestNiceSubstring(s) { let substring = ''; for (let i = 0; i < s.length; i++) { let newSubstring = [s[i]]; let map = new Map([[s[i], true]]); for (let j = i + 1; j < s.length; j++) { newSubstring.push(s[j]); map.set(s[j], true); if (isNice(newSubstring, map) && newSubstring.length > substring.length) { substring = newSubstring.join(''); } } } return substring; } ================================================ FILE: coding_interviews/leetcode/easy/longest-subsequence-with-limited-sum/longest-subsequence-with-limited-sum.js ================================================ function immutableSort(nums) { return [...nums].sort((a, b) => a - b); } function buildAllSums(nums) { let allSums = []; let sum = 0; for (num of nums) { sum += num; allSums.push(sum); } return allSums; } function answerQueries(nums, queries) { let answer = []; let sortedNums = immutableSort(nums); let allSums = buildAllSums(sortedNums); for (let query of queries) { let num; for (let index = 0; index < allSums.length; index++) { let sum = allSums[index]; if (sum <= query) { num = index + 1; if (index === allSums.length - 1) answer.push(num); } else { if (num) answer.push(num); break; } } if (!num) answer.push(0); } return answer; } ================================================ FILE: coding_interviews/leetcode/easy/longest_palindrome.py ================================================ def count_pairs(letters): hash = {} result = {"pair": 0, "single": 0} for letter in letters: if hash.get(letter): hash[letter] += 1 else: hash[letter] = 1 for k, v in hash.items(): if v > 1: result["pair"] += v - (v % 2) result["single"] += v % 2 else: result["single"] += 1 return result def main(letters): counter = 0 pairs = count_pairs(letters) counter += pairs["pair"] if pairs["single"] > 0: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/lowest-common-ancestor-of-a-binary-search-tree/lowest-common-ancestor-of-a-binary-search-tree.js ================================================ function lowestCommonAncestor(root, p, q) { if (root === p || root === q) { return root; } if ( (p.val < root.val && q.val > root.val) || (p.val > root.val && q.val < root.val) ) { return root; } if (p.val < root.val && q.val < root.val) { return lowestCommonAncestor(root.left, p, q); } if (p.val > root.val && q.val > root.val) { return lowestCommonAncestor(root.right, p, q); } } ================================================ FILE: coding_interviews/leetcode/easy/lucky_numbers_in_a_matrix/lucky_numbers_in_a_matrix.py ================================================ # https://leetcode.com/problems/lucky-numbers-in-a-matrix def lucky_numbers(matrix): all_lucky_numbers, all_mins = [], [] for row in matrix: found_min, col_index = float('Inf'), -1 for index, column in enumerate(row): if column < found_min: found_min = column col_index = index all_mins.append([found_min, col_index]) for a_min in all_mins: [min_value, min_column] = a_min maximum = float('-Inf') for index in range(len(matrix)): num = matrix[index][min_column] maximum = max(num, maximum) if maximum == min_value: all_lucky_numbers.append(min_value) return all_lucky_numbers ================================================ FILE: coding_interviews/leetcode/easy/majority-element/majority-element.js ================================================ function majorityElement(nums) { let hashmap = {}; let result; for (let num of nums) { if (hashmap[num]) { hashmap[num]++; } else { hashmap[num] = 1; } } Object.entries(hashmap).forEach(([num, count]) => { if (count > nums.length / 2) { result = num; } }); return result; } ================================================ FILE: coding_interviews/leetcode/easy/make-array-zero-by-subtracting-equal-amounts/make-array-zero-by-subtracting-equal-amounts.js ================================================ function minimumOperationsAllInOne(nums) { let count = 0; let smallest = 0; for (let num of nums) { if (num > 0) { smallest = smallest ? Math.min(smallest, num) : num; } } while (smallest) { let smallestToSubtract = smallest; smallest = 0; for (let index = 0; index < nums.length; index++) { let subtractionResult = nums[index] - smallestToSubtract; nums[index] = subtractionResult > 0 ? subtractionResult : 0; if (subtractionResult > 0) { smallest = smallest ? Math.min(smallest, subtractionResult) : subtractionResult; } } count++; } return count; } // -------------------------------------------------- function smallestExceptZeros(smallest, num) { return smallest ? Math.min(smallest, num) : num; } function getSmallest(nums) { let smallest = 0; for (let num of nums) { if (num > 0) { smallest = smallestExceptZeros(smallest, num); } } return smallest; } function performSubtraction(nums, smallestToSubtract, smallest) { for (let index = 0; index < nums.length; index++) { let subtractionResult = nums[index] - smallestToSubtract; nums[index] = subtractionResult > 0 ? subtractionResult : 0; if (subtractionResult > 0) { smallest = smallestExceptZeros(smallest, subtractionResult); } } return smallest; } function minimumOperations(nums) { let count = 0; let smallest = getSmallest(nums); while (smallest) { smallest = performSubtraction(nums, smallest, 0); count++; } return count; } // -------------------------------------------------- function minimumOperationsSet(nums) { return new Set(nums.filter((num) => num !== 0)); } ================================================ FILE: coding_interviews/leetcode/easy/make-the-string-great/make-the-string-great.js ================================================ function isUpperCase(char1, char2) { return char1 !== char1.toUpperCase() && char1.toUpperCase() === char2; } function isLowerCase(char1, char2) { return char2.toLowerCase() !== char2 && char2.toLowerCase() === char1; } function isBadPair(char1, char2) { return ( isUpperCase(char1, char2) || isUpperCase(char2, char1) || isLowerCase(char1, char2) || isLowerCase(char2, char1) ); } function makeGood(string, pointer1 = 0, pointer2 = 1) { if (string.length <= 1) return string; if (pointer2 === string.length) return string; console.log( string[pointer1], string[pointer2], isBadPair(string[pointer1], string[pointer2]) ); if (isBadPair(string[pointer1], string[pointer2])) { return makeGood( string.slice(0, pointer1) + string.slice(pointer2 + 1), 0, 1 ); } return makeGood(string, pointer1 + 1, pointer2 + 1); } ================================================ FILE: coding_interviews/leetcode/easy/matrix-cells-in-distance-order/matrix-cells-in-distance-order.js ================================================ function sortDistances(distances) { return [...distances].sort((distance1, distance2) => distance1 - distance2); } function allCellsDistOrder(rows, cols, rCenter, cCenter) { const distancesMap = new Map(); const distances = []; for (let row = 0; row < rows; row++) { for (let col = 0; col < cols; col++) { const distance = Math.abs(row - rCenter) + Math.abs(col - cCenter); if (distancesMap.has(distance)) { distancesMap.set(distance, [...distancesMap.get(distance), [row, col]]); } else { distances.push(distance); distancesMap.set(distance, [[row, col]]); } } } return sortDistances(distances) .map((distance) => distancesMap.get(distance)) .flatMap((cell) => cell); } ================================================ FILE: coding_interviews/leetcode/easy/matrix_diagonal_sum/matrix_diagonal_sum.py ================================================ # https://leetcode.com/problems/matrix-diagonal-sum ''' Time Complexity: O(N) Space Complexity: O(1) ''' def diagonal_sum(mat): diagonals_sum, mat_length = 0, len(mat) # left-top --> right-bottom & right-top --> left-bottom for index in range(mat_length): diagonals_sum += mat[index][index] + mat[index][mat_length-index-1] if len(mat) % 2 == 0: return diagonals_sum center = mat_length // 2 return diagonals_sum - mat[center][center]] ================================================ FILE: coding_interviews/leetcode/easy/matrix_negative_numbers/matrix_negative_numbers.py ================================================ def count_negatives(grid): counter = 0 for i in range(len(grid)): for j in range(len(grid[i])): if grid[i][j] < 0: counter += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/max-consecutive-ones/max-consecutive-ones.js ================================================ function findMaxConsecutiveOnes(nums) { let max = 0; let consecutive = 0; for (let index = 0; index < nums.length; index++) { if (nums[index] === 1) consecutive++; if (nums[index] === 0 || index === nums.length - 1) { max = Math.max(max, consecutive); consecutive = 0; } } return max; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-69-number/maximum-69-number.js ================================================ function maximum69Number(num) { let nums = String(num).split(''); let firstSixIndex; for (let index = 0; index < nums.length; index++) { if (nums[index] === '6' && firstSixIndex === undefined) { firstSixIndex = index; } } nums[firstSixIndex] = '9'; return Number(nums.join('')); } ================================================ FILE: coding_interviews/leetcode/easy/maximum-ascending-subarray-sum/maximum-ascending-subarray-sum.js ================================================ function maxAscendingSum(nums) { let max = 0; let maxSubsequence = 0; let previous = -Infinity; for (let index = 0; index < nums.length; index++) { let num = nums[index]; if (num > previous) { maxSubsequence += num; previous = num; if (index === nums.length - 1) max = Math.max(max, maxSubsequence); } else { max = Math.max(max, maxSubsequence); previous = num; maxSubsequence = num; } } return max; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-count-of-positive-integer-and-negative-integer/maximum-count-of-positive-integer-and-negative-integer.js ================================================ function maximumCount(nums) { let pos = 0; let neg = 0; for (let num of nums) { if (num > 0) pos++; if (num < 0) neg++; } return Math.max(pos, neg); } ================================================ FILE: coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree-2.js ================================================ function getMaximumDepth(node, depth) { if (!node) { return depth; } return Math.max( getMaximumDepth(node.left, depth + 1), getMaximumDepth(node.right, depth + 1) ); } function maxDepth(root) { if (!root) { return 0; } return Math.max( getMaximumDepth(root.left, 1), getMaximumDepth(root.right, 1) ); } // shorter without a helper function function maxDepth(root, depth = 0) { return root ? Math.max(maxDepth(root.left, depth + 1), maxDepth(root.right, depth + 1)) : depth; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-depth-of-binary-tree/maximum-depth-of-binary-tree.js ================================================ // https://leetcode.com/problems/maximum-depth-of-binary-tree const maxDepth = (root) => maxDepthHelper(root, 0); const maxDepthHelper = (node, depth) => { if (!node) return depth; const leftDepth = maxDepthHelper(node.left, depth + 1); const rightDepth = maxDepthHelper(node.right, depth + 1); return Math.max(leftDepth, rightDepth); }; ================================================ FILE: coding_interviews/leetcode/easy/maximum-depth-of-n-ary-tree/maximum-depth-of-n-ary-tree.js ================================================ function maxDepth(root, depth = 1) { if (!root) return depth - 1; let depths = []; for (let child of root.children) { const childDepth = maxDepth(child, depth + 1); depths.push(childDepth); } return depths.length ? Math.max(...depths) : depth; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-number-of-balloons/maximum-number-of-balloons.js ================================================ function buildHashmap(text) { const hashmap = new Map(); for (let char of text) { if (hashmap.has(char)) hashmap.set(char, hashmap.get(char) + 1); else hashmap.set(char, 1); } return hashmap; } function maxNumberOfBalloons(text) { let hashmap = buildHashmap(text); let minCharCount = Infinity; let balloon = 'balon'; for (let char of balloon) { if (!hashmap.has(char)) return 0; if (['l', 'o'].includes(char)) minCharCount = Math.min(minCharCount, Math.floor(hashmap.get(char) / 2)); else minCharCount = Math.min(minCharCount, hashmap.get(char)); } return minCharCount; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-number-of-pairs-in-array/maximum-number-of-pairs-in-array.js ================================================ function numberOfPairs(nums) { let countNums = new Map(); for (let num of nums) { if (countNums.has(num)) { countNums.set(num, countNums.get(num) + 1); } else { countNums.set(num, 1); } } let pairs = 0; let rest = 0; countNums.forEach((num) => { pairs += Math.floor(num / 2); rest += Math.floor(num % 2); }); return [pairs, rest]; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-odd-binary-number/maximum-odd-binary-number.js ================================================ // https://leetcode.com/problems/maximum-odd-binary-number function countOnesAndZeros(s) { let countOnes = 0; let countZeros = 0; for (let char of s) { if (char === '1') { countOnes++; } else { countZeros++; } } return { countOnes, countZeros }; } function maximumOddBinaryNumber(s) { const { countOnes, countZeros } = countOnesAndZeros(s); let result = ''; for (let one = 1; one <= countOnes - 1; one++) { result += '1'; } for (let zero = 1; zero <= countZeros; zero++) { result += '0'; } return result + '1'; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-subarray/maximum-subarray.js ================================================ function maxSubArray(nums) { let maxSum = nums[0]; let localSum = nums[0]; for (let index = 1; index < nums.length; index++) { localSum = Math.max(nums[index], localSum + nums[index]); maxSum = Math.max(maxSum, localSum); } return maxSum; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-sum-with-exactly-k-elements/maximum-sum-with-exactly-k-elements.js ================================================ function getBiggest(nums) { let biggest = -Infinity; for (let num of nums) { biggest = Math.max(biggest, num); } return biggest; } function maximizeSum(nums, k) { let biggest = getBiggest(nums); let sum = 0; while (k--) { sum += biggest; biggest++; } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/maximum-units-on-a-truck/maximum-units-on-a-truck.py ================================================ # https://leetcode.com/problems/maximum-units-on-a-truck def maximum_units(box_types, truck_size): sorted_by_units_per_box = sorted(box_types, key=lambda box_type: box_type[1], reverse=True) units = 0 for [num_of_boxes, num_of_units] in sorted_by_units_per_box: num_of_boxes_to_put_on_the_truck = min(truck_size, num_of_boxes) truck_size -= num_of_boxes_to_put_on_the_truck units += num_of_boxes_to_put_on_the_truck * num_of_units if truck_size <= 0: break return units ================================================ FILE: coding_interviews/leetcode/easy/maximum-value-of-a-string-in-an-array/maximum-value-of-a-string-in-an-array.js ================================================ function maximumValue(strs) { return strs.reduce( (max, string) => Math.max( max, Number.isNaN(Number(string)) ? string.length : Number(string) ), 0 ); } ================================================ FILE: coding_interviews/leetcode/easy/maximum_nesting_depth_of_the_parentheses/maximum_nesting_depth_of_the_parentheses.py ================================================ # https://leetcode.com/problems/maximum-nesting-depth-of-the-parentheses def max_depth(s): depth = open_paren = 0 for char in s: if char == '(': open_paren += 1 depth = max(depth, open_paren) if char == ')': open_paren -= 1 return depth ================================================ FILE: coding_interviews/leetcode/easy/maximum_number_of_balls_in_a_box/maximum_number_of_balls_in_a_box.py ================================================ # https://leetcode.com/problems/maximum-number-of-balls-in-a-box def get_box(ball): count = 0 while ball > 0: count += ball % 10 ball //= 10 return count def count_balls(low_limit, high_limit): hash_counter = {} for ball in range(low_limit, high_limit + 1): box = get_box(ball) if box in hash_counter: hash_counter[box] += 1 else: hash_counter[box] = 1 max_balls = float('-Inf') for key, value in hash_counter.items(): max_balls = max(max_balls, value) return max_balls ================================================ FILE: coding_interviews/leetcode/easy/maximum_number_of_words_you_can_type/maximum_number_of_words_you_can_type.js ================================================ // https://leetcode.com/problems/maximum-number-of-words-you-can-type const canBeTypedWords = function (text, brokenLetters) { const words = text.split(' '); const broken = buildBrokenMapper(brokenLetters); const okWords = words.filter((word) => { let foundBroken = false; for (let char of word) { if (broken[char]) { foundBroken = true; } } return !foundBroken; }); return okWords.length; }; const buildBrokenMapper = (brokenLetters) => { const mapper = {}; for (let letter of brokenLetters) { mapper[letter] = true; } return mapper; }; ================================================ FILE: coding_interviews/leetcode/easy/maximum_population/maximum_population.py ================================================ # https://leetcode.com/problems/maximum-population-year def maximum_population(logs): population_by_year = {} for [birth, death] in logs: for year in range(birth, death): if year in population_by_year: population_by_year[year] += 1 else: population_by_year[year] = 1 earliest_year = 0 max_population = 0 for year, population in population_by_year.items(): if population == max_population: earliest_year = min(earliest_year, year) if population > max_population: earliest_year = year max_population = population return earliest_year ================================================ FILE: coding_interviews/leetcode/easy/maximum_product/maximum_product.py ================================================ # https://leetcode.com/problems/maximum-product-of-two-elements-in-an-array def max_product(nums): sorted_list = sorted(nums) return (sorted_list[-1] - 1) * (sorted_list[-2] - 1) def max_product(nums): max, second_max = 0, 0 for num in nums: if num >= max: second_max = max max = num elif num >= second_max: second_max = num return (max - 1) * (second_max - 1) ================================================ FILE: coding_interviews/leetcode/easy/maximum_product_difference_between_two_pairs/maximum_product_difference_between_two_pairs.js ================================================ // https://leetcode.com/problems/maximum-product-difference-between-two-pairs const maxProductDifference = function (nums) { nums.sort((a, b) => a - b); const greatest = nums[nums.length - 1]; const secondGreatest = nums[nums.length - 2]; const smallest = nums[0]; const secondSmallest = nums[1]; return greatest * secondGreatest - smallest * secondSmallest; }; const max = maxProductDifference([1, 6, 7, 5, 2, 4, 10, 6, 4]); console.log(max); ================================================ FILE: coding_interviews/leetcode/easy/mean-of-array-after-removing-some-elements/mean-of-array-after-removing-some-elements.js ================================================ function removeFivePercent(numbers) { let totalNumbers = numbers.length; let fivePercent = numbers.length * 0.05; return numbers.slice(fivePercent, totalNumbers - fivePercent); } function sum(numbers) { return numbers.reduce((sumOfNums, num) => sumOfNums + num, 0); } function trimMean(numbers) { numbers.sort((a, b) => a - b); const withoutFivePercent = removeFivePercent(numbers); const sumOfNums = sum(withoutFivePercent); return sumOfNums / withoutFivePercent.length; } ================================================ FILE: coding_interviews/leetcode/easy/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js ================================================ export class ListNode { constructor(val, next) { this.val = val === undefined ? 0 : val; this.next = next === undefined ? null : next; } } export function mergeNodes(head) { let nonZeroHead; let node; let nextNode; let currentNode = head.next; let valueSum = 0; let gotFirstNode = false; while (currentNode) { valueSum += currentNode.val; if (currentNode.val === 0) { nextNode = new ListNode(valueSum); valueSum = 0; if (gotFirstNode) { node.next = nextNode; node = node.next; } else { node = nextNode; nonZeroHead = nextNode; gotFirstNode = true; } } currentNode = currentNode.next; } return nonZeroHead; } ================================================ FILE: coding_interviews/leetcode/easy/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js ================================================ import { describe, it, expect } from 'vitest'; import { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros'; function buildList(nums, initValue = 0) { let head = new ListNode(initValue); let node = head; let nextNode; for (let i = 1; i < nums.length; i++) { nextNode = new ListNode(nums[i]); node.next = nextNode; node = node.next; } return head; } describe('mergeNodes', () => { it('removes zeros and merges nodes', () => { const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]); const result = buildList([4, 11], 4); expect(mergeNodes(head)).toEqual(result); }); it('removes zeros and merges nodes', () => { const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]); const result = buildList([1, 3, 4], 1); expect(mergeNodes(head)).toEqual(result); }); }); ================================================ FILE: coding_interviews/leetcode/easy/merge-similar-items/merge-similar-items.js ================================================ function fillHashmapAndList(items, hashmap, list) { for (let [value, weight] of items) { if (hashmap.has(value)) { hashmap.set(value, hashmap.get(value) + weight); } else { hashmap.set(value, weight); list.push(value); } } } function mergeSimilarItems(items1, items2) { let hashmap = new Map(); let list = []; fillHashmapAndList(items1, hashmap, list); fillHashmapAndList(items2, hashmap, list); return list.sort((a, b) => a - b).map((value) => [value, hashmap.get(value)]); } ================================================ FILE: coding_interviews/leetcode/easy/merge-sorted-array/merge-sorted-array.js ================================================ /* nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3 [1,2,2,3,5,6] nums1 = [0,0,0], m = 0, nums2 = [1,2,3], n = 3 [1,2,3] time: O(n + m) space: O(n + m) */ function merge(nums1, m, nums2, n) { let pointer1 = 0; let pointer2 = 0; let numbers = []; let mIndex = m - 1; let nIndex = n - 1; while (pointer1 <= mIndex || pointer2 <= nIndex) { if (pointer1 <= mIndex && pointer2 <= nIndex) { let num1 = nums1[pointer1]; let num2 = nums2[pointer2]; if (num1 <= num2) { numbers.push(num1); pointer1++; } else { numbers.push(num2); pointer2++; } } if (pointer1 <= mIndex && pointer2 > nIndex) { numbers.push(nums1[pointer1]); pointer1++; } if (pointer2 <= nIndex && pointer1 > mIndex) { numbers.push(nums2[pointer2]); pointer2++; } } for (let [index, num] of numbers.entries()) { nums1[index] = num; } } ================================================ FILE: coding_interviews/leetcode/easy/merge-two-2d-arrays-by-summing-values/merge-two-2d-arrays-by-summing-values.js ================================================ function mergeArrays(nums1, nums2) { let nums = []; let index1 = 0; let index2 = 0; while (index1 < nums1.length && index2 < nums2.length) { let [id1, val1] = nums1[index1]; let [id2, val2] = nums2[index2]; if (id1 < id2) { nums.push([id1, val1]); index1++; } else if (id2 < id1) { nums.push([id2, val2]); index2++; } else { nums.push([id1, val1 + val2]); index1++; index2++; } } while (index1 < nums1.length) { nums.push(nums1[index1]); index1++; } while (index2 < nums2.length) { nums.push(nums2[index2]); index2++; } return nums; } ================================================ FILE: coding_interviews/leetcode/easy/merge-two-binary-trees/merge-two-binary-trees.js ================================================ function mergeTrees(root1, root2) { let root = new TreeNode(); if (root1 && root2) { root.val = root1.val + root2.val; root.left = mergeTrees(root1.left, root2.left); root.right = mergeTrees(root1.right, root2.right); } else if (root1) { root = root1; } else if (root2) { root = root2; } else { return null; } return root; } ================================================ FILE: coding_interviews/leetcode/easy/merge-two-sorted-lists/merge-two-sorted-lists.js ================================================ export class ListNode { constructor(val, next) { this.val = val === undefined ? 0 : val; this.next = next === undefined ? null : next; } } export function mergeTwoLists(list1, list2) { if (!list1 && !list2) { return null; } if (!list1) { return list2; } if (!list2) { return list1; } let newList; if (list1.val <= list2.val) { newList = new ListNode(list1.val); list1 = list1.next; } else { newList = new ListNode(list2.val); list2 = list2.next; } let node = newList; while (list1 && list2) { if (list1.val <= list2.val) { node.next = new ListNode(list1.val); list1 = list1.next; } else { node.next = new ListNode(list2.val); list2 = list2.next; } node = node.next; } while (list1) { node.next = new ListNode(list1.val); node = node.next; list1 = list1.next; } while (list2) { node.next = new ListNode(list2.val); node = node.next; list2 = list2.next; } return newList; } ================================================ FILE: coding_interviews/leetcode/easy/merge-two-sorted-lists/tests/merge-two-sorted-lists.test.js ================================================ import { describe, it, expect } from 'vitest'; import { mergeTwoLists, ListNode } from '../merge-two-sorted-lists'; function buildList(nums) { if (nums.length === 0) { return null; } let head = new ListNode(nums[0]); let node = head; let nextNode; for (let i = 1; i < nums.length; i++) { nextNode = new ListNode(nums[i]); node.next = nextNode; node = node.next; } return head; } describe('mergeTwoLists', () => { it('', () => { const list1 = buildList([1, 2, 4]); const list2 = buildList([1, 3, 4]); const result = buildList([1, 1, 2, 3, 4, 4]); expect(mergeTwoLists(list1, list2)).toEqual(result); }); it('', () => { const list1 = buildList([]); const list2 = buildList([]); const result = buildList([]); expect(mergeTwoLists(list1, list2)).toEqual(result); }); it('', () => { const list1 = buildList([]); const list2 = buildList([0]); const result = buildList([0]); expect(mergeTwoLists(list1, list2)).toEqual(result); }); }); ================================================ FILE: coding_interviews/leetcode/easy/merge_strings_alternately/merge_strings_alternately.py ================================================ # https://leetcode.com/problems/merge-strings-alternately/ def mergeAlternately(word1, word2): smallest_length = min(len(word1), len(word2)) letters = [] for index in range(smallest_length): letters.append(word1[index]) letters.append(word2[index]) if len(word1) > len(word2): biggest_word = word1 else: biggest_word = word2 return ''.join(letters) + biggest_word[smallest_length:] ================================================ FILE: coding_interviews/leetcode/easy/merge_trees.py ================================================ ''' https://leetcode.com/problems/merge-two-binary-trees/description/ Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree 3 / \ 4 5 / \ \ 5 4 7 ''' class TreeNode(object): def __init__(self, val): self.val = val self.left = None self.right = None def merge_trees(t1, t2): if not t1 and not t2: return None new_node = TreeNode((t1.val if t1 else 0) + (t2.val if t2 else 0)) new_node.left = merge_trees(t1 and t1.left, t2 and t2.left) new_node.right = merge_trees(t1 and t1.right, t2 and t2.right) return new_node ================================================ FILE: coding_interviews/leetcode/easy/merge_two_lists.py ================================================ # https://leetcode.com/problems/merge-two-sorted-lists/description/ class ListNode(object): def __init__(self, x): self.val = x self.next = None def merge_two_lists(l1, l2): if l1 == None and l2 == None: return l1 elif l1 == None: return l2 elif l2 == None: return l1 else: n = root = ListNode(0) while l1 and l2: if l1.val <= l2.val: n.next = l1 l1 = l1.next else: n.next = l2 l2 = l2.next n = n.next if l1: n.next = l1 if l2: n.next = l2 return root.next ================================================ FILE: coding_interviews/leetcode/easy/middle-of-the-linked-list/middle-of-the-linked-list-fast-slow.js ================================================ function middleNode(head) { let slow = head; let fast = head; while (fast && fast.next) { slow = slow.next; fast = fast.next.next; } return slow; } ================================================ FILE: coding_interviews/leetcode/easy/middle-of-the-linked-list/middle-of-the-linked-list.js ================================================ /** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** head = [1,2,3,4,5] => n = 5 => 5 / 2 => 2.5 => 2 [3,4,5] head = [1] => n = 1 => 1 / 2 => 0.5 => 0 [1] head = [1,2,3,4,5,6] => n = 6 => 6 / 2 => 3 [4,5,6] */ function getNodeCount(node, count) { return node ? getNodeCount(node.next, count + 1) : count; } function getNode(node, index) { return index ? getNode(node.next, index - 1) : node; } function middleNode(head) { let count = getNodeCount(head, 0); let middleIndex = Math.floor(count / 2); return getNode(head, middleIndex); } ================================================ FILE: coding_interviews/leetcode/easy/min-max-game/min-max-game.js ================================================ function minMaxGame(nums) { while (nums.length > 1) { let newNums = []; let middleIndex = nums.length / 2; for (let i = 0; i < middleIndex; i++) { if (i % 2 === 0) newNums.push(Math.min(nums[2 * i], nums[2 * i + 1])); else newNums.push(Math.max(nums[2 * i], nums[2 * i + 1])); } nums = newNums; } return nums; } ================================================ FILE: coding_interviews/leetcode/easy/minimize-string-length/minimize-string-length.js ================================================ // https://leetcode.com/problems/minimize-string-length function minimizedStringLength(s) { let set = new Set(); for (let char of s) { set.add(char); } return set.size; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-absolute-difference/minimum-absolute-difference.js ================================================ // https://leetcode.com/problems/minimum-absolute-difference const minimumAbsDifference = (arr) => { // runtime: O(NlogN) // space: O(N) let minDifference = Infinity; const differenceToPairs = {}; arr.sort((a, b) => a - b); for (let i = 0; i < arr.length - 1; i++) { const num1 = arr[i]; const num2 = arr[i + 1]; const currentDifference = num2 - num1; if (differenceToPairs[currentDifference]) { differenceToPairs[currentDifference].push([num1, num2]); } else { differenceToPairs[currentDifference] = [[num1, num2]]; } minDifference = Math.min(minDifference, currentDifference); } return differenceToPairs[minDifference]; }; ================================================ FILE: coding_interviews/leetcode/easy/minimum-absolute-difference-in-bst/minimum-absolute-difference-in-bst.js ================================================ function getMinimumDifference(root, rootVal = Infinity) { if (!root) return Infinity; return Math.min( Math.abs(root.val - rootVal), getMinimumDifference(root.left, root.val), getMinimumDifference(root.right, root.val) ); } // =============================================================== function traverse(node, list) { if (!node) return null; traverse(node.left, list); list.push(node.val); traverse(node.right, list); } function diff(list) { let minDiff = Infinity; let previous = list[0]; for (let index = 1; index < list.length; index++) { minDiff = Math.min(list[index] - previous, minDiff); previous = list[index]; } return minDiff; } function getMinimumDifference(root) { let list = []; traverse(root, list); return diff(list); } ================================================ FILE: coding_interviews/leetcode/easy/minimum-bit-flips-to-convert-number/minimum-bit-flips-to-convert-number.js ================================================ function toBinary(number) { const binary = []; while (number) { binary.push((number % 2).toString()); number = Math.floor(number / 2); } return binary; } export function minBitFlips(start, goal) { const startBinary = toBinary(start); const goalBinary = toBinary(goal); const greatestLength = startBinary.length > goalBinary.length ? startBinary.length : goalBinary.length; let flips = 0; for (let i = 0; i < greatestLength; i++) { const startBit = startBinary[i] || '0'; const goalBit = goalBinary[i] || '0'; if (startBit !== goalBit) { flips++; } } return flips; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-bit-flips-to-convert-number/tests/minimum-bit-flips-to-convert-number.test.js ================================================ import { describe, expect, it } from 'vitest'; import { minBitFlips } from '../minimum-bit-flips-to-convert-number'; describe('minBitFlips', () => { it('', () => { expect(minBitFlips(10, 7)).toEqual(3); }); it('', () => { expect(minBitFlips(1, 16)).toEqual(2); }); it('', () => { expect(minBitFlips(3, 4)).toEqual(3); }); }); ================================================ FILE: coding_interviews/leetcode/easy/minimum-cost-to-move-chips-to-the-same-position/minimum-cost-to-move-chips-to-the-same-position.js ================================================ function minCostToMoveChips(positions) { let evenCount = 0; let oddCount = 0; for (let position of positions) { if (position % 2 === 0) evenCount++; else oddCount++; } return Math.min(evenCount, oddCount); } ================================================ FILE: coding_interviews/leetcode/easy/minimum-depth-of-binary-tree/minimum-depth-of-binary-tree.js ================================================ // https://leetcode.com/problems/minimum-depth-of-binary-tree /** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */ function minDepth(node, depth = 1) { if (!node) return 0; if (!node.left && !node.right) return depth; if (!node.left) return minDepth(node.right, depth + 1); if (!node.right) return minDepth(node.left, depth + 1); return Math.min( minDepth(node.left, depth + 1), minDepth(node.right, depth + 1) ); } ================================================ FILE: coding_interviews/leetcode/easy/minimum-distance-between-bst-nodes/minimum-distance-between-bst-nodes.js ================================================ function traverse(node, list) { if (!node) return; traverse(node.left, list); list.push(node.val); traverse(node.right, list); } function getMinDiff(list) { let minDiff = Infinity; let previous = list[0]; for (let index = 1; index < list.length; index++) { if (list[index] - previous < minDiff) minDiff = list[index] - previous; previous = list[index]; } return minDiff; } function minDiffInBST(root) { let list = []; traverse(root, list); return getMinDiff(list); } ================================================ FILE: coding_interviews/leetcode/easy/minimum-number-game/minimum-number-game.js ================================================ // https://leetcode.com/problems/minimum-number-game function numberGame(nums) { let arr = []; nums.sort((a, b) => a - b); for (let index = 0; index < nums.length; index += 2) { let alice = nums[index]; let bob = nums[index + 1]; arr.push(bob); arr.push(alice); } return arr; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-number-of-moves-to-seat-everyone/minimum-number-of-moves-to-seat-everyone.js ================================================ function sort(nums) { return [...nums].sort((a, b) => a - b); } export function minMovesToSeat(seats, students) { const sortedSeats = sort(seats); const sortedStudents = sort(students); const N = seats.length; let moves = 0; for (let i = 0; i < N; i++) { moves += Math.abs(sortedSeats[i] - sortedStudents[i]); } return moves; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-number-of-moves-to-seat-everyone/tests/minimum-number-of-moves-to-seat-everyone.test.js ================================================ import { describe, it, expect } from 'vitest'; import { minMovesToSeat } from '../minimum-number-of-moves-to-seat-everyone'; describe('minMovesToSeat', () => { it('', () => { expect(minMovesToSeat([3, 1, 5], [2, 7, 4])).toEqual(4); }); it('', () => { expect(minMovesToSeat([4, 1, 5, 9], [1, 3, 2, 6])).toEqual(7); }); it('', () => { expect(minMovesToSeat([2, 2, 6, 6], [1, 3, 2, 6])).toEqual(4); }); }); ================================================ FILE: coding_interviews/leetcode/easy/minimum-number-of-operations-to-convert-time/minimum-number-of-operations-to-convert-time.js ================================================ function toMinutes(stringTime) { const [hour, minutes] = stringTime.split(':'); return Number(hour) * 60 + Number(minutes); } function convertTime(current, correct) { let count = 0; let minutes = toMinutes(correct) - toMinutes(current); while (minutes) { if (minutes >= 60) minutes -= 60; else if (minutes >= 15) minutes -= 15; else if (minutes >= 5) minutes -= 5; else minutes -= 1; count++; } return count; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-string-length-after-removing-substrings/minimum-string-length-after-removing-substrings.js ================================================ // https://leetcode.com/problems/minimum-string-length-after-removing-substrings function minLength(s) { while (true) { let found = false; for (let index = 0; index < s.length - 1; index++) { let slice = s.slice(index, index + 2); if (['AB', 'CD'].includes(slice)) { s = s.slice(0, index) + s.slice(index + 2); found = true; break; } } if (!found) break; } return s.length; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-subsequence-in-non-increasing-order/minimum-subsequence-in-non-increasing-order.js ================================================ function sum(nums) { return nums.reduce((sumOfNums, num) => sumOfNums + num, 0); } function minSubsequence(nums) { const result = []; const sortedNums = [...nums].sort((a, b) => a - b); let index = nums.length - 1; let sumOfNums = sum(sortedNums); let otherHalfSum = 0; while (index >= 0 && otherHalfSum <= sumOfNums) { const num = sortedNums[index]; result.push(num); sumOfNums -= num; otherHalfSum += num; index--; } return result; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-sum/minimum-sum.js ================================================ /* You are given a positive integer num consisting of exactly four digits. Split num into two new integers new1 and new2 by using the digits found in num. Leading zeros are allowed in new1 and new2, and all the digits found in num must be used. For example, given num = 2932, you have the following digits: two 2's, one 9 and one 3. Some of the possible pairs [new1, new2] are [22, 93], [23, 92], [223, 9] and [2, 329]. Return the minimum possible sum of new1 and new2. # Example 1: Input: num = 2932 Output: 52 Explanation: Some possible pairs [new1, new2] are [29, 23], [223, 9], etc. The minimum sum can be obtained by the pair [29, 23]: 29 + 23 = 52. # Example 2: Input: num = 4009 Output: 13 Explanation: Some possible pairs [new1, new2] are [0, 49], [490, 0], etc. The minimum sum can be obtained by the pair [4, 9]: 4 + 9 = 13. */ // 2932 => 2, 9, 3, 2 => 2, 2 => 29, 23 function getAllDigits(number) { const stringNumber = number.toString(); const digits = []; for (let i = 0; i < stringNumber.length; i++) { digits.push(Number(stringNumber[i])); } return digits; } function sort(digits) { return digits.sort((digit1, digit2) => digit1 - digit2); } function minimumSum(number) { const digits = getAllDigits(number); const sortedDigits = sort(digits); const [digit1, digit2, digit3, digit4] = sortedDigits; return digit1 * 10 + digit3 + (digit2 * 10 + digit4); } console.log(minimumSum(2932), 52); console.log(minimumSum(4009), 13); function altMinimunSum(number) { const digits = number.toString().split('').sort(); return Number(digits[0] + digits[2]) + Number(digits[1] + digits[3]); } console.log(altMinimunSum(2932), 52); console.log(altMinimunSum(4009), 13); ================================================ FILE: coding_interviews/leetcode/easy/minimum-sum-of-mountain-triplets-i/minimum-sum-of-mountain-triplets-i.js ================================================ // https://leetcode.com/problems/minimum-sum-of-mountain-triplets-i function minimumSum(nums) { let min = Infinity; for (let i = 0; i < nums.length - 2; i++) { for (let j = i + 1; j < nums.length - 1; j++) { for (let k = j + 1; k < nums.length; k++) { if (nums[i] < nums[j] && nums[k] < nums[j]) { min = Math.min(min, nums[i] + nums[j] + nums[k]); } } } } return min == Infinity ? -1 : min; } ================================================ FILE: coding_interviews/leetcode/easy/minimum-time-to-type-word-using-special-typewriter/minimum-time-to-type-word-using-special-typewriter.js ================================================ // https://leetcode.com/problems/minimum-time-to-type-word-using-special-typewriter const minTimeToType = (word) => { const wordLength = word.length; let currentIndex = 0; let moves = wordLength; for (let i = 0; i < wordLength; i++) { const letter = word[i]; const charCode = letter.charCodeAt() - 97; const firstDistance = Math.abs(charCode - currentIndex); const secondDistance = charCode > currentIndex ? currentIndex + 26 - charCode : charCode + 26 - currentIndex; const minimumDistance = Math.min(firstDistance, secondDistance); moves += minimumDistance; currentIndex = charCode; } return moves; }; ================================================ FILE: coding_interviews/leetcode/easy/minimum-value-to-get-positive-step-by-step-sum/minimum-value-to-get-positive-step-by-step-sum.js ================================================ function getMinValue(nums) { let min = Infinity; let sum = 0; for (let num of nums) { sum += num; min = Math.min(min, sum); } return min; } function minStartValue(nums) { const minValue = getMinValue(nums); const result = 1 - minValue; return result >= 1 ? result : 1; } ================================================ FILE: coding_interviews/leetcode/easy/minimum_operations_to_make_the_array_increasing/minimum_operations_to_make_the_array_increasing.py ================================================ # https://leetcode.com/problems/minimum-operations-to-make-the-array-increasing def min_operations(nums): previous_num = nums[0] operations = 0 for index, num in enumerate(nums[1:]): if num <= previous_num: new_num = previous_num - num + 1 operations += new_num nums[index + 1] += new_num previous_num = nums[index + 1] return operations def min_operations(nums): prev, ops = 0, 0 for num in nums: if num <= prev: prev += 1 ops += prev - num else: prev = num return ops ================================================ FILE: coding_interviews/leetcode/easy/missing-number/missing-number.js ================================================ function buildHashmap(nums) { const hashmap = new Map(); for (let num of nums) { hashmap.set(num, true); } return hashmap; } function getMissingNumber(numsLength, hashmap) { for (let i = 0; i <= numsLength; i++) { if (!hashmap.has(i)) return i; } } function missingNumber(nums) { const hashmap = buildHashmap(nums); return getMissingNumber(nums.length, hashmap); } ================================================ FILE: coding_interviews/leetcode/easy/monotonic-array/monotonic-array.js ================================================ function isMonotonic(nums) { if (nums.length === 1) return true; let isIncreasing; let previous = nums[0]; for (let index = 1; index < nums.length; index++) { if (nums[index] === previous) { previous = nums[index]; continue; } if (isIncreasing === undefined) { isIncreasing = previous <= nums[index]; } if (isIncreasing && nums[index] < previous) return false; if (!isIncreasing && nums[index] > previous) return false; previous = nums[index]; } return true; } ================================================ FILE: coding_interviews/leetcode/easy/most-words-found/most-words-found.js ================================================ /* A sentence is a list of words that are separated by a single space with no leading or trailing spaces. You are given an array of strings sentences, where each sentences[i] represents a single sentence. Return the maximum number of words that appear in a single sentence. # Example 1: Input: sentences = ["alice and bob love leetcode", "i think so too", "this is great thanks very much"] Output: 6 Explanation: - The first sentence, "alice and bob love leetcode", has 5 words in total. - The second sentence, "i think so too", has 4 words in total. - The third sentence, "this is great thanks very much", has 6 words in total. Thus, the maximum number of words in a single sentence comes from the third sentence, which has 6 words. # Example 2: Input: sentences = ["please wait", "continue to fight", "continue to win"] Output: 3 Explanation: It is possible that multiple sentences contain the same number of words. In this example, the second and third sentences (underlined) have the same number of words. */ function mostWordsFound(sentences = []) { return Math.max(...sentences.map((sentence) => sentence.split(' ').length)); } console.log( mostWordsFound([ 'alice and bob love leetcode', 'i think so too', 'this is great thanks very much', ]), 6 ); console.log( mostWordsFound(['please wait', 'continue to fight', 'continue to win']), 3 ); ================================================ FILE: coding_interviews/leetcode/easy/move-zeroes/move-zeroes-in-place.js ================================================ function moveZeroes(nums) { let zeroesCount = 0; let inPlaceIndex = 0; for (let num of nums) { if (num) { nums[inPlaceIndex] = num; inPlaceIndex++; } else { zeroesCount++; } } while (zeroesCount) { nums[nums.length - zeroesCount] = 0; zeroesCount--; } } ================================================ FILE: coding_interviews/leetcode/easy/move-zeroes/move-zeroes.js ================================================ function moveZeroes(nums) { let numsWithZerosAtTheEnd = []; let zeroCount = 0; for (let num of nums) { if (num) { numsWithZerosAtTheEnd.push(num); } else { zeroCount++; } } while (zeroCount) { numsWithZerosAtTheEnd.push(0); zeroCount--; } return numsWithZerosAtTheEnd; } ================================================ FILE: coding_interviews/leetcode/easy/n_ary_tree_postorder_traversal/n_ary_tree_postorder_traversal.py ================================================ # https://leetcode.com/problems/n-ary-tree-postorder-traversal result = [] def postorder(root): if root is None: return [] for node in root.children: postorder(node) result.append(root.val) return result ================================================ FILE: coding_interviews/leetcode/easy/n_ary_tree_preorder_traversal/n_ary_tree_preorder_traversal.py ================================================ # https://leetcode.com/problems/n-ary-tree-postorder-traversal result = [] def preorder(root): if root is None: return [] result.append(root.val) for node in root.children: preorder(node) return result ================================================ FILE: coding_interviews/leetcode/easy/n_repeated_element_in_size_2n_array/n_repeated_element_in_size_2n_array.py ================================================ # https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ ''' In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times. Return the element repeated N times. Example 1: Input: [1,2,3,3] Output: 3 Example 2: Input: [2,1,2,5,3,2] Output: 2 Example 3: Input: [5,1,5,2,5,3,5,4] Output: 5 ''' def n_repeated_element_in_size_2n_array(A): map_counter = {} for number in A: if number in map_counter: map_counter[number] += 1 return number else: map_counter[number] = 1 data_tests = [ ([1, 2, 3, 3], 3), ([2, 1, 2, 5, 3, 2], 2), ([5, 1, 5, 2, 5, 3, 5, 4], 5) ] for numbers, expected in data_tests: result = n_repeated_element_in_size_2n_array(numbers) print(result, expected == result) ================================================ FILE: coding_interviews/leetcode/easy/neither-minimum-nor-maximum/neither-minimum-nor-maximum-on.js ================================================ // https://leetcode.com/problems/neither-minimum-nor-maximum function findNonMinOrMax(nums) { let min = Infinity, max = -Infinity; for (num of nums) { min = Math.min(min, num); max = Math.max(max, num); } for (let num of nums) { if (num !== min && num !== max) { return num; } } return -1; } ================================================ FILE: coding_interviews/leetcode/easy/neither-minimum-nor-maximum/neither-minimum-nor-maximum.js ================================================ // https://leetcode.com/problems/neither-minimum-nor-maximum function findNonMinOrMax(nums) { return nums.length > 2 ? nums.sort((a, b) => a - b)[1] : -1; } ================================================ FILE: coding_interviews/leetcode/easy/next-greater-element-i/next-greater-element-i-optimized.js ================================================ function peek(stack) { return stack[stack.length - 1]; } function isEmpty(stack) { return stack.length === 0; } export function nextGreaterElement(nums1, nums2) { const stack = []; const hashmap = new Map(); for (let num of nums2) { while (!isEmpty(stack) && num > peek(stack)) { hashmap.set(stack.pop(), num); } stack.push(num); } while (!isEmpty(stack)) { hashmap.set(stack.pop(), -1); } const result = []; for (let num of nums1) { if (hashmap.has(num)) { result.push(hashmap.get(num)); } else { result.push(-1); } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/next-greater-element-i/next-greater-element-i.js ================================================ export function nextGreaterElement(nums1, nums2) { const result = []; for (let num1 of nums1) { let foundNumber = false; let foundNextGreaterElement = false; for (let num2 of nums2) { if (num1 === num2) { foundNumber = true; } if (foundNumber && num2 > num1) { result.push(num2); foundNextGreaterElement = true; break; } } if (!foundNextGreaterElement) { result.push(-1); } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/next-greater-element-i/tests/next-greater-element-i-optimized.test.js ================================================ import { describe, expect, it } from 'vitest'; import { nextGreaterElement } from '../next-greater-element-i-optimized'; describe('nextGreaterElement', () => { it('', () => { expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])).toEqual([-1, 3, -1]); }); it('', () => { expect(nextGreaterElement([2, 4], [1, 2, 3, 4])).toEqual([3, -1]); }); it('', () => { expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2, 5])).toEqual([5, 3, 5]); }); it('', () => { expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1])).toEqual([5, -1, -1]); }); it('', () => { expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1, 6])).toEqual([ 5, 6, 6, ]); }); it('', () => { expect( nextGreaterElement([9, 8, 7, 3, 2, 1, 6], [9, 8, 7, 3, 2, 1, 6]) ).toEqual([-1, -1, -1, 6, 6, 6, -1]); }); }); ================================================ FILE: coding_interviews/leetcode/easy/next-greater-element-i/tests/next-greater-element-i.test.js ================================================ import { describe, expect, it } from 'vitest'; import { nextGreaterElement } from '../next-greater-element-i'; describe('nextGreaterElement', () => { it('', () => { expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2])).toEqual([-1, 3, -1]); }); it('', () => { expect(nextGreaterElement([2, 4], [1, 2, 3, 4])).toEqual([3, -1]); }); it('', () => { expect(nextGreaterElement([4, 1, 2], [1, 3, 4, 2, 5])).toEqual([5, 3, 5]); }); it('', () => { expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1])).toEqual([5, -1, -1]); }); it('', () => { expect(nextGreaterElement([4, 1, 2], [3, 4, 5, 2, 1, 6])).toEqual([ 5, 6, 6, ]); }); }); ================================================ FILE: coding_interviews/leetcode/easy/num_unique_emails/num_unique_emails.py ================================================ def num_unique_emails(emails): unique_emails = set() for email in emails: [local, domain] = email.split('@') splitted_local = local.split('+') new_local = ''.join(splitted_local[0].split('.')) unique_emails.add(new_local + '@' + domain) return len(unique_emails) ================================================ FILE: coding_interviews/leetcode/easy/number-of-1-bits/number-of-1-bits.js ================================================ function hammingWeight(n) { let sum = 0; while (n != 0) { sum += n & 1; n = n >>> 1; } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-arithmetic-triplets/number-of-arithmetic-triplets.js ================================================ function buildMap(nums) { const hashmap = new Map(); for (let num of nums) { hashmap.set(num, num); } return hashmap; } function arithmeticTriplets(nums, diff) { let hashmap = buildMap(nums); let counter = 0; for (let index = 0; index < nums.length - 2; index++) { const number = nums[index] + diff; const anotherNumber = number + diff; if (hashmap.has(number) && hashmap.has(anotherNumber)) { counter++; } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-common-factors/number-of-common-factors.js ================================================ function commonFactors(a, b) { let minValue = Math.min(a, b); let counter = 0; for (let num = 1; num <= minValue; num++) { if (a % num === 0 && b % num === 0) counter++; } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-employees-who-met-the-target/number-of-employees-who-met-the-target.js ================================================ function numberOfEmployeesWhoMetTarget(hours, target) { let count = 0; for (let hour of hours) { if (hour >= target) count++; } return count; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-even-and-odd-bits/number-of-even-and-odd-bits.js ================================================ function toBinary(n) { const binary = []; while (n > 0) { binary.push(n % 2); n = Math.floor(n / 2); } return binary; } function isEven(n) { return n % 2 === 0; } function isOdd(n) { return n % 2 !== 0; } function evenOddBit(n) { let binary = toBinary(n); let even = 0; let odd = 0; for (let index = 0; index < binary.length; index++) { if (isEven(index) && binary[index]) even++; if (isOdd(index) && binary[index]) odd++; } return [even, odd]; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-lines-to-write-string/number-of-lines-to-write-string.js ================================================ // https://leetcode.com/problems/number-of-lines-to-write-string function toWidthsIndex(char) { return char.charCodeAt() - 97; } function numberOfLines(widths, s) { let output = [1, 0]; for (let char of s) { let width = widths[toWidthsIndex(char)]; if (output[1] + width <= 100) { output[1] = output[1] + width; } else { output[0]++; output[1] = width; } } return output; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-senior-citizens/number-of-senior-citizens.js ================================================ function countSeniors(details) { let count = 0; for (let detail of details) { if (Number(detail.slice(11, 13)) > 60) { count++; } } return count; } ================================================ FILE: coding_interviews/leetcode/easy/number-of-senior-citizens/one-liner-number-of-senior-citizens.js ================================================ function countSeniors(details) { return details .filter((detail) => Number(detail.slice(11, 13)) > 60) .length; }; ================================================ FILE: coding_interviews/leetcode/easy/number-of-strings-that-appear-as-substrings-in-word/number-of-strings-that-appear-as-substrings-in-word.js ================================================ const isPatternInWord = (pattern, word) => { const patternLength = pattern.length; let hasPattern = false; for (let i = 0; i + patternLength <= word.length; i++) { console.log(word.substring(i, i + patternLength)); if (word.substring(i, i + patternLength) === pattern) { hasPattern = true; } } return hasPattern; }; const numOfStrings = (patterns, word) => { let count = 0; patterns.forEach((pattern) => { if (isPatternInWord(pattern, word)) { count++; } }); return count; }; const result = numOfStrings(['a', 'abc', 'bc', 'd'], 'abc'); console.log('result', result); ================================================ FILE: coding_interviews/leetcode/easy/number-of-unequal-triplets-in-array/number-of-unequal-triplets-in-array.js ================================================ function unequalTriplets(nums) { let counter = 0; for (let i = 0; i < nums.length - 2; i++) { for (let j = i + 1; j < nums.length - 1; j++) { for (let k = j + 1; k < nums.length; k++) { let iNum = nums[i]; let jNum = nums[j]; let kNum = nums[k]; if (iNum !== jNum && iNum !== kNum && jNum !== kNum) counter++; } } } return counter; } ================================================ FILE: coding_interviews/leetcode/easy/number_complement.py ================================================ ''' https://leetcode.com/problems/number-complement/description/ Input: 5 Output: 2 Input: 1 Output: 0 ''' def to_binary(num): binary_num = '' copy_num = num while copy_num > 0: binary_num += str(copy_num % 2) copy_num /= 2 return binary_num def to_binary_complement(binary_num): return ''.join(['1' if binary == '0' else '0' for binary in binary_num]) def to_complement(complement_binary_num): return sum([pow(2, index) for index, binary in enumerate(complement_binary_num) if binary == '1']) def find_complement(num): binary_num = to_binary(num) complement_binary_num = to_binary_complement(binary_num) return to_complement(complement_binary_num) print(find_complement(5) == 2) print(find_complement(1) == 0) print(find_complement(8) == 7) ================================================ FILE: coding_interviews/leetcode/easy/number_of_good_pairs/number_of_good_pairs.py ================================================ def factorial(n): if n <= 1: return 1 return factorial(n - 1) * n def permutation(n, r): return factorial(n) // (factorial(n - r) * factorial(r)) def number_of_good_pairs(nums): nums_counter = {} for num in nums: if num in nums_counter: nums_counter[num] += 1 else: nums_counter[num] = 1 counter = 0 for num, num_counter in nums_counter.items(): if num_counter > 1: counter += permutation(num_counter, 2) return counter # ------------------------------------------------------------ from math import factorial def permutation(n, r): return factorial(n) // (factorial(n - r) * factorial(r)) def number_of_good_pairs(nums): nums_counter = {} for num in nums: if num in nums_counter: nums_counter[num] += 1 else: nums_counter[num] = 1 counter = 0 for num, num_counter in nums_counter.items(): if num_counter > 1: counter += permutation(num_counter, 2) return counter # ------------------------------------------------------------ def number_of_good_pairs(nums): nums_counter = {} counter = 0 for num in nums: if num in nums_counter: counter += nums_counter[num] nums_counter[num] += 1 else: nums_counter[num] = 1 return counter # ------------------------------------------------------------ from collections import Counter def number_of_good_pairs(nums): nums_counter = Counter() counter = 0 for num in nums: counter += nums_counter[num] nums_counter[num] += 1 return counter ================================================ FILE: coding_interviews/leetcode/easy/number_of_recent_calls/number_of_recent_calls.py ================================================ # https://leetcode.com/problems/number-of-recent-calls class RecentCounter: def __init__(self): self.requests = [] def ping(self, t: int) -> int: self.requests.append(t) initial_time = t - 3000 counter = 0 for request in self.requests: if request >= initial_time and request <= t: counter += 1 return counter class RecentCounter: def __init__(self): self.requests = deque() def ping(self, t: int) -> int: self.requests.append(t) while self.requests[0] < t - 3000: self.requests.popleft() return len(self.requests) ================================================ FILE: coding_interviews/leetcode/easy/number_of_students/number_of_students.py ================================================ def busy_student(start_time, end_time, query_time): number_of_students = 0 for index in range(len(start_time)): start, end = start_time[index], end_time[index] if query_time >= start and query_time <= end: number_of_students += 1 return number_of_students def busy_student(start_time, end_time, query_time): number_of_students = 0 for start, end in zip(start_time, end_time): if query_time >= start and query_time <= end: number_of_students += 1 return number_of_students ================================================ FILE: coding_interviews/leetcode/easy/odd-string-difference/odd-string-difference.js ================================================ function toCode(char) { return char.charCodeAt() - 97; } function buildDiffIntegerArray(word) { let diffIntegerArray = []; let previous = word[0]; for (let index = 1; index < word.length; index++) { let current = word[index]; diffIntegerArray.push(toCode(current) - toCode(previous)); previous = current; } return diffIntegerArray; } function joinIntegersString(diff) { return diff.map((diffNum) => diffNum.toString()).join('*'); } function oddString(words) { let hashmap = new Map(); for (let word of words) { let key = joinIntegersString(buildDiffIntegerArray(word)); if (hashmap.has(key)) { hashmap.set(key, [hashmap.get(key)[0] + 1, word]); } else { hashmap.set(key, [1, word]); } } for (let [_, [count, word]] of hashmap.entries()) { if (count === 1) { return word; } } } ================================================ FILE: coding_interviews/leetcode/easy/odd_in_matrix/odd_in_matrix.py ================================================ def init_matrix(rows, columns): return [[0 for _ in range(columns)] for _ in range(rows)] def odd_cells(n, m, indices): matrix = init_matrix(n, m) for [ri, ci] in indices: for column in range(m): matrix[ri][column] += 1 for row in range(n): matrix[row][ci] += 1 odds = 0 for row in range(n): for column in range(m): if matrix[row][column] % 2 != 0: odds += 1 return odds ================================================ FILE: coding_interviews/leetcode/easy/partition_labels.py ================================================ ''' https://leetcode.com/problems/partition-labels/description/ Input: S = "ababcbacadefegdehijhklij" Output: [9, 7, 8] Input: S = "abc" Output: [1, 1, 1] Input: S = "abbaa" Output: [5] ''' def partition_labels(S): partitions = [] start_index = 0 last_index = S.rfind(S[0]) for i, c in enumerate(S, 1): if i == len(S): partitions.append(S[start_index:]) elif last_index == i - 1: partitions.append(S[start_index:i]) start_index = i last_index = S.rfind(S[i]) elif S.rfind(S[i]) > last_index: last_index = S.rfind(S[i]) return [len(partition) for partition in partitions] print(partition_labels("ababcbacadefegdehijhklij") == [9, 7, 8]) print(partition_labels("abc") == [1, 1, 1]) print(partition_labels("abbaa") == [5]) ================================================ FILE: coding_interviews/leetcode/easy/pascals-triangle/pascals-triangle.js ================================================ function generate(numRows) { let triangle = [[1]]; for (let row = 1; row < numRows; row++) { let triangleRow = []; for (let index = 0; index <= row; index++) { const num1 = index - 1 >= 0 ? triangle[row - 1][index - 1] : 0; const num2 = index < triangle[row - 1].length ? triangle[row - 1][index] : 0; triangleRow.push(num1 + num2); } triangle.push(triangleRow); } return triangle; } ================================================ FILE: coding_interviews/leetcode/easy/path-sum/path-sum.js ================================================ function hasPathSum(root, targetSum, sum = 0) { if (!root) { return false; } if (!root.left && !root.right) { return sum + root.val === targetSum; } return ( hasPathSum(root.left, targetSum, sum + root.val) || hasPathSum(root.right, targetSum, sum + root.val) ); } ================================================ FILE: coding_interviews/leetcode/easy/peak_index_mountain.py ================================================ ''' https://leetcode.com/problems/peak-index-in-a-mountain-array/description/ Input: [0, 1, 0] Output: 1 Input: [0, 2, 1, 0] Output: 1 ''' def peak_index_in_mountain_array(A): peak = A[0] peak_index = 0 for index, mountain_height in enumerate(A): if mountain_height > peak: peak_index = index peak = mountain_height return peak_index print(peak_index_in_mountain_array([0, 1, 0]) == 1) print(peak_index_in_mountain_array([0, 2, 1, 0]) == 1) ================================================ FILE: coding_interviews/leetcode/easy/percentage-of-letter-in-string/percentage-of-letter-in-string.js ================================================ function percentageLetter(s, letter) { let counter = new Map(); for (let char of s) { if (counter.has(char)) { counter.set(char, counter.get(char) + 1); } else { counter.set(char, 1); } } let letterCount = counter.has(letter) ? counter.get(letter) : 0; return Math.floor((letterCount / s.length) * 100); } ================================================ FILE: coding_interviews/leetcode/easy/plus_one/plus_one.js ================================================ // https://leetcode.com/problems/plus-one/ function add_one(digits) { return plus_one(digits, 1); } function plus_one(digits, inc) { if (digits.length == 0 && inc > 0) { return [1]; } if (digits.length == 0 && inc == 0) { return []; } let new_inc; let last_digit; last_digit = digits[digits.length - 1]; last_digit = last_digit + inc; if (last_digit == 10) { new_inc = 1; } else { new_inc = 0; } return plus_one( digits.slice(0, digits.length - 1), new_inc ).concat([last_digit % 10]); } console.log(add_one([1, 2, 3])) // [1, 2, 4] console.log(add_one([4, 3, 2, 1])) // [4, 3, 2, 2] console.log(add_one([1, 2, 9])) // [1, 3, 0] console.log(add_one([1, 9, 9])) // [2, 0, 0] console.log(add_one([9, 9, 9])) // [1, 0, 0, 0] console.log(add_one([1, 0, 0, 0, 0])) // [1, 0, 0, 0, 1] ================================================ FILE: coding_interviews/leetcode/easy/plus_one/plus_one.py ================================================ # https://leetcode.com/problems/plus-one/ def add_one(digits): return plus_one(digits, 1) def plus_one(digits, inc): if digits == [] and inc > 0: return [1] if digits == [] and inc == 0: return [] last_digit = digits[-1] last_digit = last_digit + inc if last_digit == 10: new_inc = 1 else: new_inc = 0 return plus_one(digits[0:-1], new_inc) + [last_digit % 10] print(add_one([1, 2, 3])) # [1, 2, 4] print(add_one([4, 3, 2, 1])) # [4, 3, 2, 2] print(add_one([1, 2, 9])) # [1, 3, 0] print(add_one([1, 9, 9])) # [2, 0, 0] print(add_one([9, 9, 9])) # [1, 0, 0, 0] print(add_one([1, 0, 0, 0, 0])) # [1, 0, 0, 0, 1] ================================================ FILE: coding_interviews/leetcode/easy/points-that-intersect-with-cars/points-that-intersect-with-cars.js ================================================ // https://leetcode.com/problems/points-that-intersect-with-cars function numberOfPoints(nums) { let map = new Map(); let points = 0; for ([start, end] of nums) { for (let num = start; num <= end; num++) { if (!map.has(num)) { points++; map.set(num, true); } } } return points; } ================================================ FILE: coding_interviews/leetcode/easy/power-of-two/power-of-two.js ================================================ function isPowerOfTwo(n) { if (n <= 0) { return false; } while (n > 1) { if (n % 2 !== 0) { return false; } n /= 2; } return true; } ================================================ FILE: coding_interviews/leetcode/easy/prime-number-of-set-bits-in-binary-representation/prime-number-of-set-bits-in-binary-representation.js ================================================ // https://leetcode.com/problems/prime-number-of-set-bits-in-binary-representation function toBinary(n) { let binary = []; while (n) { binary.push((n % 2).toString()); n = Math.floor(n / 2); } return binary.join(''); } function getNumberOfSetBits(binary) { let count = 0; for (let digit of binary) { if (digit === '1') count++; } return count; } function isPrime(num) { for (let i = 2, s = Math.sqrt(num); i <= s; i++) { if (num % i === 0) return false; } return num > 1; } function countPrimeSetBits(left, right) { let count = 0; for (let num = left; num <= right; num++) { let binary = toBinary(num); let setBits = getNumberOfSetBits(binary); if (isPrime(setBits)) { count++; } } return count; } ================================================ FILE: coding_interviews/leetcode/easy/projection-area-of-3d-shapes/projection-area-of-3d-shapes.js ================================================ // https://leetcode.com/problems/projection-area-of-3d-shapes function projectionArea(grid) { let xy = 0; let xz = 0; let yz = 0; for (let x = 0; x < grid.length; x++) { for (let y = 0; y < grid[x].length; y++) { if (grid[x][y] > 0) xy++; } } for (let x = 0; x < grid.length; x++) { let max = -Infinity; for (let z = 0; z < grid[x].length; z++) { max = Math.max(max, grid[x][z]); } xz += max; } let allAreas = []; for (let y = 0; y < grid.length; y++) { for (let z = 0; z < grid[y].length; z++) { allAreas[z] = Math.max(allAreas[z] || 0, grid[y][z]); } } yz = allAreas.reduce((sum, area) => sum + area, 0); return xy + xz + yz; } ================================================ FILE: coding_interviews/leetcode/easy/range_sum_of_bst/range_sum_of_bst.py ================================================ # https://leetcode.com/problems/range-sum-of-bst/submissions/ ''' Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). The binary search tree is guaranteed to have unique values. Example 1: Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 Output: 32 Example 2: Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 Output: 23 ''' def rangeSumBST(root, L, R): left_sum = 0 right_sum = 0 root_sum = 0 if root.left is not None and root.val > L: left_sum = rangeSumBST(root.left, L, R) if root.right is not None and root.val < R: right_sum = rangeSumBST(root.right, L, R) if root.val >= L and root.val <= R: root_sum = root.val return root_sum + left_sum + right_sum ================================================ FILE: coding_interviews/leetcode/easy/rank-transform-of-an-array/rank-transform-of-an-array-less-memory.js ================================================ // https://leetcode.com/problems/rank-transform-of-an-array /** * [40,10,20,30] * [10,20,30,40] => O(NlogN) * {10: 1, 20: 2, 30: 3, 40: 4} => O(N), N = array size * [4,1,2,3] => O(N) * runtime: O(NlogN) * space: O(N) */ function buildMap(set) { let map = new Map(); let index = 1; for (let num of set.values()) { map.set(num, index); index++; } return map; } function buildRank(arr, map) { for (let index = 0; index < arr.length; index++) { arr[index] = map.get(arr[index]); } return arr; } function arrayRankTransform(arr) { const sortedSet = new Set([...arr].sort((a, b) => a - b)); const map = buildMap(sortedSet); return buildRank(arr, map); } ================================================ FILE: coding_interviews/leetcode/easy/rank-transform-of-an-array/rank-transform-of-an-array.js ================================================ // https://leetcode.com/problems/rank-transform-of-an-array /** * [40,10,20,30] * [10,20,30,40] => O(NlogN) * {10: 1, 20: 2, 30: 3, 40: 4} => O(N), N = array size * [4,1,2,3] => O(N) * runtime: O(NlogN) * space: O(N) */ function buildMap(set) { let map = new Map(); let index = 1; for (let num of set.values()) { map.set(num, index); index++; } return map; } function buildRank(arr, map) { let rank = []; for (let num of arr) { rank.push(map.get(num)); } return rank; } function arrayRankTransform(arr) { const sortedSet = new Set([...arr].sort((a, b) => a - b)); const map = buildMap(sortedSet); return buildRank(arr, map); } ================================================ FILE: coding_interviews/leetcode/easy/ransom-note/ransom-note.js ================================================ function canConstruct(ransomNote, magazine) { let map = {}; for (let char of magazine) { if (map[char]) { map[char] += 1; } else { map[char] = 1; } } for (let char of ransomNote) { if (map[char]) { map[char]--; } else { return false; } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/ransom_note/ransom_note.py ================================================ def can_construct(ransom_note, magazine): if ransom_note == '': return True if magazine == '': return False letters_counter = {} for letter in magazine: if letter in letters_counter: letters_counter[letter] += 1 else: letters_counter[letter] = 1 for char in ransom_note: if char not in letters_counter or letters_counter[char] == 0: return False letters_counter[char] -= 1 return True ================================================ FILE: coding_interviews/leetcode/easy/reduce_zero/reduce_zero.py ================================================ # https://leetcode.com/problems/number-of-steps-to-reduce-a-number-to-zero/ def reduce_number(num): if num % 2 == 0: return num / 2 else: return num - 1 def number_of_steps(num): counter = 0 while num: counter += 1 num = reduce_number(num) return counter data_tests = [ (14, 6), (8, 4) ] for number, expected in data_tests: result = number_of_steps(number) print(result, expected == result) ================================================ FILE: coding_interviews/leetcode/easy/reformat-date/reformat-date.js ================================================ // https://leetcode.com/problems/reformat-date function getDateInfo(date) { let dateInfo = []; let info = ''; for (let index = 0; index < date.length; index++) { let char = date[index]; if (char === ' ') { dateInfo.push(info); info = ''; } else if (index === date.length - 1) { dateInfo.push(info + char); } else { info += char; } } return dateInfo; } const monthStringToNumber = { Jan: '01', Feb: '02', Mar: '03', Apr: '04', May: '05', Jun: '06', Jul: '07', Aug: '08', Sep: '09', Oct: '10', Nov: '11', Dec: '12', }; function formatDay(day) { return day.length === 1 ? `0${day}` : day; } function reformatDate(date) { let [day, month, year] = getDateInfo(date); let dateDay = ''; let dateMonth = monthStringToNumber[month]; for (let char of day) { if (!Number.isNaN(Number(char))) { dateDay += char; } } return `${year}-${dateMonth}-${formatDay(dateDay)}`; } ================================================ FILE: coding_interviews/leetcode/easy/reformat-phone-number/reformat-phone-number.js ================================================ function removeSpacesAndDashes(number) { return number.replaceAll('-', '').replaceAll(' ', ''); } function reformatNumber(number) { let num = removeSpacesAndDashes(number); let blocks = []; let block = []; let blockLimit = 2; let numLength = num.length; for (let index = 0; index < numLength; index++) { if (block.length === 0) { if (numLength - index === 2) { blocks.push(num.slice(index)); break; } if (numLength - index === 4) { blocks.push(num.slice(index, index + 2)); blocks.push(num.slice(index + 2)); break; } } if (index === blockLimit) { blockLimit = index + 3; block.push(num[index]); blocks.push(block.join('')); block = []; } else { block.push(num[index]); } } return blocks.join('-'); } ================================================ FILE: coding_interviews/leetcode/easy/relative-ranks/relative-ranks.js ================================================ function sortDesc(list) { return list.sort((a, b) => b - a); } const mapper = { 0: 'Gold Medal', 1: 'Silver Medal', 2: 'Bronze Medal', }; function buildHashmap(list) { let hashmap = new Map(); for (let [index, item] of list.entries()) { hashmap.set(item, mapper[index] || (index + 1).toString()); } return hashmap; } function getRelativeRanks(score, hashmap) { let rank = []; for (let value of score) { rank.push(hashmap.get(value)); } return rank; } function findRelativeRanks(score) { const sortedScore = sortDesc([...score]); const hashmap = buildHashmap(sortedScore); return getRelativeRanks(score, hashmap); } ================================================ FILE: coding_interviews/leetcode/easy/relative-sort-array/relative-sort-array.js ================================================ // https://leetcode.com/problems/relative-sort-array const relativeSortArray = (arr1, arr2) => { const mapper1 = {}; const mapper2 = {}; arr2.forEach((num) => (mapper2[num] = true)); arr1.forEach((num) => { if (mapper1[num]) mapper1[num].push(num); else if (mapper2[num]) mapper1[num] = [num]; else if (mapper1['other']) mapper1['other'].push(num); else mapper1['other'] = [num]; }); const sortedArr = []; arr2.forEach((num) => { sortedArr.push(...mapper1[num]); }); if (mapper1['other']) sortedArr.push(...mapper1['other'].sort((a, b) => a - b)); return sortedArr; }; ================================================ FILE: coding_interviews/leetcode/easy/remove-duplicates-from-sorted-list/remove-duplicates-from-sorted-list.js ================================================ function deleteDuplicates(head) { if (!head || !head.next) { return head; } let current = head; let next = current.next; while (next) { if (current.val === next.val) { next = next.next; current.next = next; } else { current = next; next = next.next; } } return head; } ================================================ FILE: coding_interviews/leetcode/easy/remove-linked-list-elements/remove-linked-list-elements.js ================================================ function removeElements(head, val) { if (!head) return head; while (head && head.val === val) { head = head.next; } if (!head) return head; let previous = head; let current = head.next; while (current) { if (current.val === val) { previous.next = current.next; current = previous.next; } else { previous = previous.next; current = current.next; } } return head; } ================================================ FILE: coding_interviews/leetcode/easy/remove-outermost-parentheses/remove-outermost-parentheses.js ================================================ export function removeOuterParentheses(string) { const stack = []; const result = []; for (let i = 0; i < string.length; i++) { const char = string[i]; if (char === '(') { if (stack.length) { result.push(char); } stack.push(char); } else { if (stack.length > 1) { result.push(char); } stack.pop(); } } return result.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/remove-outermost-parentheses/tests/remove-outermost-parentheses.test.js ================================================ import { describe, expect, it } from 'vitest'; import { removeOuterParentheses } from '../remove-outermost-parentheses'; describe('removeOuterParentheses', () => { it('', () => { expect(removeOuterParentheses('(()())(())')).toEqual('()()()'); }); it('', () => { expect(removeOuterParentheses('(()())(())(()(()))')).toEqual( '()()()()(())' ); }); it('', () => { expect(removeOuterParentheses('()()')).toEqual(''); }); }); ================================================ FILE: coding_interviews/leetcode/easy/remove-palindromic-subsequences/remove-palindromic-subsequences.js ================================================ function isPalindrome(s) { return s === s.split('').reverse().join(''); } function removePalindromeSub(s) { return isPalindrome(s) ? 1 : 2; } ================================================ FILE: coding_interviews/leetcode/easy/remove-trailing-zeros-from-a-string/remove-trailing-zeros-from-a-string.js ================================================ function removeTrailingZeros(num) { let result = ''; let trailing = true; for (let index = num.length - 1; index >= 0; index--) { if (num[index] === '0' && trailing) { continue; } else { trailing = false; result = num[index] + result; } } return result; } ================================================ FILE: coding_interviews/leetcode/easy/remove_duplicates/remove_duplicates.py ================================================ # https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string def remove_duplicates(S): if len(S) <= 1: return S start, end = 0, 1 while end < len(S): if S[start] != S[end]: start = end end = start + 1 elif S[start] == S[end] and end + 1 == len(S): S = S[0:start] elif S[start] == S[end]: S = S[0:start] + S[end+1:] start, end = 0, 1 return S def remove_duplicates(S): stack = [] for char in S: if len(stack) and stack[-1] == char: stack.pop() else: stack.append(char) return ''.join(stack) ================================================ FILE: coding_interviews/leetcode/easy/remove_duplicates.py ================================================ # https://leetcode.com/problems/remove-duplicates-from-sorted-array/description/ ''' - Examples: [1, 1, 2] # => 2 [] # => 0 [1, 1, 1] # => 1 [1, 2, 3, 3, 4, 5] # => 5 ''' def remove_duplicates(nums): if not nums: return 0 total_result = 1 num = nums[0] for index in range(1, len(nums)): if nums[index] != num: nums[total_result] = nums[index] total_result += 1 num = nums[index] return total_result list1 = [1, 1, 2] list2 = [] list3 = [1, 1, 1] list4 = [1, 2, 3, 3, 4, 5] print remove_duplicates(list1) print remove_duplicates(list2) print remove_duplicates(list3) print remove_duplicates(list4) print list1 print list2 print list3 print list4 ================================================ FILE: coding_interviews/leetcode/easy/remove_duplicates_from_list.py ================================================ # https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ class ListNode(object): def __init__(self, value): self.val = value self.next = None def remove_duplicates(head): if head is None: return current_node = head while current_node and current_node.next: if current_node.val == current_node.next.val: current_node.next = current_node.next.next else: current_node = current_node.next return head # 1 -> 1 -> 2 print('1 -> 1 -> 2') head = ListNode(1) head.next = ListNode(1) head.next.next = ListNode(2) current_node = remove_duplicates(head) while current_node: print(current_node.val) current_node = current_node.next # 1 -> 1 -> 2 -> 3 -> 3 print('\n1 -> 1 -> 2 -> 3 -> 3') head = ListNode(1) head.next = ListNode(1) head.next.next = ListNode(2) head.next.next.next = ListNode(3) head.next.next.next.next = ListNode(3) current_node = remove_duplicates(head) while current_node: print(current_node.val) current_node = current_node.next ================================================ FILE: coding_interviews/leetcode/easy/remove_element.py ================================================ # https://leetcode.com/problems/remove-element/description/ ''' nums = [3, 2, 2, 3], val = 3 # => 2 nums = [3, 2, 2, 3], val = 2 # => 2 nums = [1, 2, 2, 4], val = 3 # => 4 nums = [], val = 3 # => 0 ''' def remove_element(nums, val): while val in nums: nums.remove(val) return len(nums) ================================================ FILE: coding_interviews/leetcode/easy/replace_digits/replace_digits.py ================================================ # https://leetcode.com/problems/replace-all-digits-with-characters def replace_digits(s): replaced_string = [] for index in range(len(s)): if index % 2 == 0: replaced_string.append(s[index]) else: replaced_string.append(shift(s[index-1], s[index])) return ''.join(replaced_string) def shift(char, digit): return chr(ord(char) + int(digit)) ================================================ FILE: coding_interviews/leetcode/easy/replace_elements/replace_elements.py ================================================ # https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side def replace_elements(arr): index, max_num = len(arr) - 1, -1 for number in reversed(arr): arr[index] = max_num max_num = max(number, max_num) index -= 1 return arr ================================================ FILE: coding_interviews/leetcode/easy/reshape-the-matrix/reshape-the-matrix.js ================================================ function matrixReshape(mat, r, c) { if (mat.length * mat[0].length !== r * c) { return mat; } let reshapedMatrix = []; let reshapedMatrixRow = []; let index = 0; for (let row = 0; row < mat.length; row++) { for (let col = 0; col < mat[row].length; col++) { const num = mat[row][col]; if (index < c) { reshapedMatrixRow.push(num); } else { reshapedMatrix.push(reshapedMatrixRow); reshapedMatrixRow = [num]; index = 0; } index++; } } reshapedMatrix.push(reshapedMatrixRow); return reshapedMatrix; } ================================================ FILE: coding_interviews/leetcode/easy/reverse-linked-list/reverse-linked-list.js ================================================ function reverseList(head) { if (!head) { return head; } let firstNode = head; let secondNode = head.next; let auxiliaryNode = null; let previousNode = null; while (secondNode) { auxiliaryNode = secondNode.next; secondNode.next = firstNode; firstNode.next = previousNode; previousNode = firstNode; firstNode = secondNode; secondNode = auxiliaryNode; } return firstNode; } function reverseListSimpler(head) { let previous = null; let current = head; let next; while (current) { next = current.next; current.next = previous; previous = current; current = next; } return previous; } ================================================ FILE: coding_interviews/leetcode/easy/reverse-only-letters/reverse-only-letters.js ================================================ function isEnglishLetter(char) { return ( (char.charCodeAt() >= 65 && char.charCodeAt() <= 90) || (char.charCodeAt() >= 97 && char.charCodeAt() <= 122) ); } function reverseOnlyLetters(s) { const englishLetter = []; for (let char of s) { if (isEnglishLetter(char)) englishLetter.push(char); } let index = englishLetter.length - 1; let output = s.split(''); for (let i = 0; i < s.length; i++) { if (isEnglishLetter(s[i])) { output[i] = englishLetter[index]; index--; } } return output.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/reverse-prefix-of-word/reverse-prefix-of-word.js ================================================ function reverse(charsList) { const reversedCharsList = []; for (let i = charsList.length - 1; i >= 0; i--) { reversedCharsList.push(charsList[i]); } return reversedCharsList; } export function reversePrefix(word, char) { let charsList = []; let foundFirstOccurrence = false; for (let i = 0; i < word.length; i++) { const wordChar = word[i]; charsList.push(wordChar); if (wordChar === char && !foundFirstOccurrence) { foundFirstOccurrence = true; charsList = reverse(charsList); } } return charsList.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/reverse-prefix-of-word/tests/reverse-prefix-of-word.test.js ================================================ import { describe, it, expect } from 'vitest'; import { reversePrefix } from '../reverse-prefix-of-word'; describe('reversePrefix', () => { it('reverses the prefix', () => { expect(reversePrefix('abcdefd', 'd')).toEqual('dcbaefd'); }); it('reverses the prefix', () => { expect(reversePrefix('xyxzxe', 'z')).toEqual('zxyxxe'); }); it('reverses the prefix', () => { expect(reversePrefix('abcd', 'z')).toEqual('abcd'); }); }); ================================================ FILE: coding_interviews/leetcode/easy/reverse-string/reverse-string-in-place.js ================================================ function reverseString(s) { let pointer1 = 0; let pointer2 = s.length - 1; let auxiliaryChar; while (pointer1 < pointer2) { auxiliaryChar = s[pointer1]; s[pointer1] = s[pointer2]; s[pointer2] = auxiliaryChar; pointer1++; pointer2--; } } ================================================ FILE: coding_interviews/leetcode/easy/reverse-string/reverse-string.js ================================================ function reverseString(s) { let reversedString = []; for (let index = s.length - 1; index >= 0; index--) { reversedString.push(s[index]); } return reversedString; } ================================================ FILE: coding_interviews/leetcode/easy/reverse-vowels-of-a-string/reverse-vowels-of-a-string.js ================================================ function reverseVowels(s) { const allVowels = []; const vowels = 'aeiouAEIOU'; for (let char of s) { if (vowels.includes(char)) allVowels.push(char); } const reversedVowels = []; for ( let index = 0, vowelIndex = allVowels.length - 1; index < s.length; index++ ) { if (vowels.includes(s[index])) { reversedVowels.push(allVowels[vowelIndex]); vowelIndex--; } else { reversedVowels.push(s[index]); } } return reversedVowels.join(''); } ================================================ FILE: coding_interviews/leetcode/easy/reverse-words-in-a-string-iii/reverse-words-in-a-string-iii.js ================================================ function reverseWords(s) { let reversedString = []; let splittedString = s.split(' '); for (let word of splittedString) { let reversedWord = []; for (let index = word.length - 1; index >= 0; index--) { reversedWord.push(word[index]); } reversedString.push(reversedWord.join('')); } return reversedString.join(' '); } ================================================ FILE: coding_interviews/leetcode/easy/reverse_integer.py ================================================ # https://leetcode.com/problems/reverse-integer/ def reverse(x): number_list = [] if x < 0: negative = True x *= -1 else: negative = False while x > 0: number_list.append(x % 10) x /= 10 result_number = 0 for index, n in enumerate(number_list): result_number += n * pow(10, len(number_list) - 1 - index) if negative: result_number *= -1 if (result_number < 2147483648*-1 or result_number > 2147483647): return 0 return result_number ================================================ FILE: coding_interviews/leetcode/easy/reverse_string.py ================================================ ''' https://leetcode.com/problems/reverse-string/description/ input: "hello" output: "olleh" ''' def reverse_string(s): return s[::-1] ================================================ FILE: coding_interviews/leetcode/easy/reverse_vowels.py ================================================ ''' https://leetcode.com/problems/reverse-vowels-of-a-string/description/ input: "hello" output: "holle" input: "leetcode" output: "leotcede" ''' def vowel(char): return char in ['a', 'e', 'i', 'o', 'u'] def reverse_vowels(s): vowels = [char for char in s if vowel(char)] index = len(vowels) - 1 result = '' for char in s: if vowel(char): result += vowels[index] index -= 1 else: result += char return result print(reverse_vowels('hello') == 'holle') print(reverse_vowels('leetcode') == 'leotcede') ================================================ FILE: coding_interviews/leetcode/easy/reverse_words_string.py ================================================ ''' https://leetcode.com/problems/reverse-words-in-a-string-iii/description/ input: "Let's take LeetCode contest" output: "s'teL ekat edoCteeL tsetnoc" ''' def reverse_words(s): return ' '.join([word[::-1] for word in s.split(' ')]) print(reverse_words("Let's take LeetCode contest") == "s'teL ekat edoCteeL tsetnoc") ================================================ FILE: coding_interviews/leetcode/easy/rings-and-rods/rings-and-rods.js ================================================ /* There are n rings and each ring is either red, green, or blue. The rings are distributed across ten rods labeled from 0 to 9. You are given a string rings of length 2n that describes the n rings that are placed onto the rods. Every two characters in rings forms a color-position pair that is used to describe each ring where: The first character of the ith pair denotes the ith ring's color ('R', 'G', 'B'). The second character of the ith pair denotes the rod that the ith ring is placed on ('0' to '9'). For example, "R3G2B1" describes n == 3 rings: a red ring placed onto the rod labeled 3, a green ring placed onto the rod labeled 2, and a blue ring placed onto the rod labeled 1. Return the number of rods that have all three colors of rings on them. Input: rings = "B0B6G0R6R0R6G9" Output: 1 Input: rings = "B0R0G0R9R0B0G0" Output: 1 */ export function countPoints(rings = '') { const rods = { 0: new Set(), 1: new Set(), 2: new Set(), 3: new Set(), 4: new Set(), 5: new Set(), 6: new Set(), 7: new Set(), 8: new Set(), 9: new Set(), }; for (let i = 0; i < rings.length - 1; i += 2) { const color = rings[i]; const position = rings[i + 1]; rods[position].add(color); } return Object.values(rods).reduce( (count, colors) => (colors.size === 3 ? count + 1 : count), 0 ); } ================================================ FILE: coding_interviews/leetcode/easy/rings-and-rods/tests/rings-and-rods.test.js ================================================ import { describe, expect, it } from 'vitest'; import { countPoints } from '../rings-and-rods'; describe('countPoints', () => { it('', () => { expect(countPoints('B0B6G0R6R0R6G9')).toEqual(1); }); it('', () => { expect(countPoints('B0R0G0R9R0B0G0')).toEqual(1); }); }); ================================================ FILE: coding_interviews/leetcode/easy/root-equals-sum-of-children/index.js ================================================ function checkTree(root) { return root.val === root.left.val + root.right.val; } ================================================ FILE: coding_interviews/leetcode/easy/row-with-maximum-ones/row-with-maximum-ones.js ================================================ // https://leetcode.com/problems/row-with-maximum-ones function rowAndMaximumOnes(mat) { let rowIndex; let maxCountOfOnes = -Infinity; for (let row = 0; row < mat.length; row++) { let countOfOnes = 0; for (let num of mat[row]) { if (num === 1) { countOfOnes++; } } if (countOfOnes > maxCountOfOnes) { maxCountOfOnes = countOfOnes; rowIndex = row; } } return [rowIndex, maxCountOfOnes]; } ================================================ FILE: coding_interviews/leetcode/easy/running_array_sum/running_array_sum.py ================================================ def running_sum(nums): sum = 0 result = [] for num in nums: sum += num result.append(sum) return result ================================================ FILE: coding_interviews/leetcode/easy/same-tree/same-tree.js ================================================ function isSameTree(p, q) { if (!p && !q) return true; if ((!p && q) || (!q && p)) return false; return ( p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right) ); } ================================================ FILE: coding_interviews/leetcode/easy/same_tree.py ================================================ # https://leetcode.com/problems/same-tree/description/ def is_same_tree(p, q): if (p and not q) or (not p and q): return False if not p and not q: return True return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right) def is_same_tree(p, q): if p and q: return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right) return p is q ================================================ FILE: coding_interviews/leetcode/easy/search-in-a-binary-search-tree/search-in-a-binary-search-tree.js ================================================ function searchBST(root, val) { if (!root) { return null; } if (root.val === val) { return root; } return searchBST(root.left, val) || searchBST(root.right, val); } ================================================ FILE: coding_interviews/leetcode/easy/search-insert-position/search-insert-position-new.js ================================================ function getMiddle(start, end) { return Math.floor((start + end) / 2); } function searchInsert(nums, target) { let start = 0; let end = nums.length - 1; let middle = getMiddle(start, end); while (start <= end) { if (target < nums[middle]) { end = middle - 1; middle = getMiddle(start, end); } else if (target > nums[middle]) { start = middle + 1; middle = getMiddle(start, end); } else { return middle; } } return middle + 1; } ================================================ FILE: coding_interviews/leetcode/easy/search-insert-position/search-insert-position.js ================================================ // https://leetcode.com/problems/search-insert-position const searchInsert = (nums, target) => { let start = 0; let end = nums.length - 1; while (start <= end) { middle = Math.floor((start + end) / 2); if (nums[middle] === target) return middle; if (target > nums[middle]) start = middle + 1; if (target < nums[middle]) end = middle - 1; } return start; }; const print = (nums, target) => console.log(searchInsert(nums, target)); print([1, 3, 5, 6], 5); print([1, 3, 5, 6], 2); print([1, 3, 5, 6], 7); print([1, 3, 5, 6], 0); print([1], 0); ================================================ FILE: coding_interviews/leetcode/easy/search_in_a_binary_search_tree/search_in_a_binary_search_tree.py ================================================ # https://leetcode.com/problems/search-in-a-binary-search-tree def searchBST(root, val): if root and val < root.val: return searchBST(root.left, val) if root and val > root.val: return searchBST(root.right, val) return root ================================================ FILE: coding_interviews/leetcode/easy/second-largest-digit-in-a-string/second-largest-digit-in-a-string.js ================================================ // https://leetcode.com/problems/second-largest-digit-in-a-string function secondHighest(s) { let highest = -1; let secHighest = -1; for (let char of s) { let numChar = Number(char); let isInt = Number.isInteger(numChar); if (isInt && numChar > highest) { secHighest = highest; highest = numChar; } else if (isInt && numChar !== highest && numChar > secHighest) { secHighest = numChar; } } return highest === secHighest ? -1 : secHighest; } ================================================ FILE: coding_interviews/leetcode/easy/self_dividing_numbers.py ================================================ ''' https://leetcode.com/problems/self-dividing-numbers/description/ Input: left = 1, right = 22 Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22] ''' def self_dividing_numbers(left, right): output = [number for number in range(left, right + 1) if dividing(number, number)] return output def dividing(number, original): if number == 0: return True if number % 10 == 0: return False return dividing(number / 10, original) and original % (number % 10) == 0 print(self_dividing_numbers(1, 22) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]) ================================================ FILE: coding_interviews/leetcode/easy/semi-ordered-permutation/semi-ordered-permutation.js ================================================ // https://leetcode.com/problems/semi-ordered-permutation function semiOrderedPermutation(nums) { let N = nums.length; let indexFirst; let indexLast; for (let index = 0; index < N; index++) { if (nums[index] === 1) indexFirst = index; if (nums[index] === N) indexLast = index; } let swaps = indexFirst; if (indexFirst > indexLast) swaps += N - indexLast - 2; else swaps += N - indexLast - 1; return swaps; } ================================================ FILE: coding_interviews/leetcode/easy/separate-the-digits-in-an-array/separate-the-digits-in-an-array.js ================================================ function separateDigits(nums) { const answer = []; for (let num of nums) { const numString = num.toString(); for (let charNum of numString) { answer.push(Number(charNum)); } } return answer; } ================================================ FILE: coding_interviews/leetcode/easy/shortest_to_char/shortest_to_char.py ================================================ # https://leetcode.com/problems/shortest-distance-to-a-character def shortest_to_char(s, c): all_c_indexes = [] for index, char in enumerate(s): if char == c: all_c_indexes.append(index) answer = [] for index, char in enumerate(s): if char == c: answer.append(0) else: answer_index = float('Inf') for c_index in all_c_indexes: answer_index = min(answer_index, abs(c_index - index)) answer.append(answer_index) return answer def shortest_to_char(s, c): previous = float('-Inf') answer = [] for index, char in enumerate(s): if char == c: previous = index answer.append(index - previous) previous = float('Inf') for index in range(len(s) - 1, -1, -1): if s[index] == c: previous = index answer[index] = min(answer[index], previous - index) return answer ================================================ FILE: coding_interviews/leetcode/easy/shuffle_string/shuffle_string.py ================================================ # shuffle string # https://leetcode.com/problems/shuffle-string def restore_string(s, indices): index_to_char_mapper = {} for index in range(len(s)): index_to_char_mapper[indices[index]] = s[index] return ''.join([index_to_char_mapper[index] for index in range(len(s))]) ================================================ FILE: coding_interviews/leetcode/easy/shuffle_the_array/shuffle_the_array.py ================================================ def shuffle(nums, n): first_half = nums[:n] last_half = nums[n:] final_list = [] for index in range(len(first_half)): final_list.append(first_half[index]) final_list.append(last_half[index]) return final_list ================================================ FILE: coding_interviews/leetcode/easy/sign_of_the_product_of_an_array/sign_of_the_product_of_an_array.py ================================================ # https://leetcode.com/problems/sign-of-the-product-of-an-array def array_sign(nums): product = 1 for num in nums: if num == 0: return 0 product *= num if product > 0: return 1 if product < 0: return -1 ================================================ FILE: coding_interviews/leetcode/easy/single-number/single-number.js ================================================ function singleNumber(nums) { let hashmap = {}; for (let num of nums) { if (hashmap[num]) { hashmap[num]++; } else { hashmap[num] = 1; } } for (let num of nums) { if (hashmap[num] === 1) { return num; } } } ================================================ FILE: coding_interviews/leetcode/easy/single_number/single_number.py ================================================ # https://leetcode.com/problems/single-number def single_number(nums): counter = {} for num in nums: if num in counter: counter[num] += 1 else: counter[num] = 1 for num in nums: if counter[num] == 1: return num ================================================ FILE: coding_interviews/leetcode/easy/slowest-key/slowest-key.js ================================================ function isLexicographicallyLarger(keysPressed, keyPressedIndex, index) { return keysPressed[index] > keysPressed[keyPressedIndex]; } function slowestKey(releaseTimes, keysPressed) { let longestDuration = releaseTimes[0]; let previousRelease = releaseTimes[0]; let keyPressedIndex = 0; for (let index = 1; index < releaseTimes.length; index++) { let currentRelease = releaseTimes[index]; let currentDuration = currentRelease - previousRelease; if (currentDuration > longestDuration) { longestDuration = currentDuration; keyPressedIndex = index; } if ( currentDuration === longestDuration && isLexicographicallyLarger(keysPressed, keyPressedIndex, index) ) { longestDuration = currentDuration; keyPressedIndex = index; } previousRelease = currentRelease; } return keysPressed[keyPressedIndex]; } function slowestKey(releaseTimes, keysPressed) { let longestDuration = releaseTimes[0]; let previousRelease = releaseTimes[0]; let keyPressedIndex = 0; for (let index = 1; index < releaseTimes.length; index++) { let currentRelease = releaseTimes[index]; let currentDuration = currentRelease - previousRelease; if ( currentDuration > longestDuration || (currentDuration === longestDuration && isLexicographicallyLarger(keysPressed, keyPressedIndex, index)) ) { longestDuration = currentDuration; keyPressedIndex = index; } previousRelease = currentRelease; } return keysPressed[keyPressedIndex]; } ================================================ FILE: coding_interviews/leetcode/easy/smallest-even-multiple/smallest-even-multiple.js ================================================ function smallestEvenMultiple(n) { return n % 2 === 0 ? n : n * 2; } ================================================ FILE: coding_interviews/leetcode/easy/smallest-index-with-equal-value/smallest-index-with-equal-value.js ================================================ function smallestEqual(nums) { for (let [index, num] of nums.entries()) { if (index % 10 === num) { return index; } } return -1; } ================================================ FILE: coding_interviews/leetcode/easy/smallest-range-i/optimized-smallest-range-i.js ================================================ // https://leetcode.com/problems/smallest-range-i function minMax(nums) { let min = Infinity; let max = -Infinity; for (let num of nums) { min = Math.min(min, num); max = Math.max(max, num); } return [min, max]; } function smallestRangeI(nums, k) { let [min, max] = minMax(nums); return Math.max(0, max - k - (min + k)); } ================================================ FILE: coding_interviews/leetcode/easy/smallest-range-i/smallest-range-i.js ================================================ // https://leetcode.com/problems/smallest-range-i function smallestRangeI(nums, k) { let smaller = Infinity; let bigger = -Infinity; for (let num of nums) { smaller = Math.min(smaller, num); bigger = Math.max(bigger, num); } let middle = Math.floor((bigger + smaller) / 2); let min = Infinity; let max = -Infinity; if (k > bigger - middle) { max = middle; } else { max = bigger - k; } if (k > middle - smaller) { min = middle; } else { min = smaller + k; } return max - min; } ================================================ FILE: coding_interviews/leetcode/easy/smallest-range-i/smallest-range-iI.js ================================================ // https://leetcode.com/problems/smallest-range-i function smallestRangeI(nums, k) { let min = Math.min(...nums); let max = Math.max(...nums); return Math.max(0, max - k - (min + k)); } ================================================ FILE: coding_interviews/leetcode/easy/smallest_numbers/smallest_numbers.py ================================================ # https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number ''' nums = [8,1,2,2,3] [4,0,1,1,3] nums = [6,5,4,8] [2,1,0,3] ''' ''' O(Nˆ2): Runtime / O(N): Space ''' def smaller_numbers_than_current(nums): smaller_numbers_counters = [] for num in nums: counter = 0 for compared_num in nums: if compared_num < num: counter += 1 smaller_numbers_counters.append(counter) return smaller_numbers_counters ''' O(NlogN): Runtime / O(N): Space ''' def smaller_numbers_than_current_2(nums): smaller_numbers_counters = {} for index, num in enumerate(sorted(nums)): if num not in smaller_numbers_counters: smaller_numbers_counters[num] = index return [smaller_numbers_counters[num] for num in nums] data_tests = [ ([8, 1, 2, 2, 3], [4, 0, 1, 1, 3]), ([6, 5, 4, 8], [2, 1, 0, 3]) ] for numbers, expected in data_tests: result = smaller_numbers_than_current(numbers) print(result, result == expected) result = smaller_numbers_than_current_2(numbers) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/sort-array-by-increasing-frequency/sort-array-by-increasing-frequency.js ================================================ function buildCounter(nums) { let counter = new Map(); for (let num of nums) { if (counter.has(num)) counter.set(num, counter.get(num) + 1); else counter.set(num, 1); } return counter; } function toPairs(counter) { const pairs = []; for (let [key, value] of counter.entries()) { pairs.push([key, value]); } return pairs; } function byCount(pair1, pair2) { if (pair1[1] < pair2[1]) return -1; if (pair1[1] === pair2[1] && pair1[0] >= pair2[0]) return -1; if (pair1[1] === pair2[1] && pair1[0] < pair2[0]) return 1; if (pair1[1] > pair2[1]) return 1; return 0; } function buildResult(pairs) { const result = []; for (let [num, count] of pairs) { for (let counter = 1; counter <= count; counter++) { result.push(num); } } return result; } function frequencySort(nums) { const counter = buildCounter(nums); const pairs = toPairs(counter); pairs.sort(byCount); return buildResult(pairs); } ================================================ FILE: coding_interviews/leetcode/easy/sort-array-by-parity/sort-array-by-parity-two-loops.js ================================================ // https://leetcode.com/problems/sort-array-by-parity function sortArrayByParity(nums) { let output = []; for (let num of nums) { if (num % 2 === 0) output.push(num); } for (let num of nums) { if (num % 2 !== 0) output.push(num); } return output; } ================================================ FILE: coding_interviews/leetcode/easy/sort-array-by-parity/sort-array-by-parity.js ================================================ // https://leetcode.com/problems/sort-array-by-parity function sortArrayByParity(nums) { let odd = []; let even = []; for (let num of nums) { if (num % 2 === 0) even.push(num); else odd.push(num); } return [...even, ...odd]; } ================================================ FILE: coding_interviews/leetcode/easy/sort-array-by-parity-ii/sort-array-by-parity-ii.js ================================================ function isEven(num) { return num % 2 === 0; } function separateIntoEvensAndOdds(nums) { let evens = []; let odds = []; for (let num of nums) { if (isEven(num)) evens.push(num); else odds.push(num); } return [evens, odds]; } export function sortArrayByParityII(nums) { let [evens, odds] = separateIntoEvensAndOdds(nums); let result = []; for (let index = 0; index < evens.length; index++) { result.push(evens[index]); result.push(odds[index]); } return result; } export function sortArrayByParityIIInPlace(nums) { for (let index = 0; index < nums.length - 1; index++) { if (isEven(index) !== isEven(nums[index])) { for (let index2 = index + 1; index2 < nums.length; index2++) { if (isEven(index) === isEven(nums[index2])) { let num = nums[index]; nums[index] = nums[index2]; nums[index2] = num; break; } } } } return nums; } ================================================ FILE: coding_interviews/leetcode/easy/sort-array-by-parity-ii/tests/sort-array-by-parity-ii.test.js ================================================ import { describe, it, expect } from 'vitest'; import { sortArrayByParityII, sortArrayByParityIIInPlace, } from '../sort-array-by-parity-ii'; describe('sortArrayByParityII', () => { it('', () => { expect(sortArrayByParityII([4, 2, 5, 7])).toEqual([4, 5, 2, 7]); }); it('', () => { expect(sortArrayByParityII([2, 3])).toEqual([2, 3]); }); it('', () => { expect(sortArrayByParityII([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual([ 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, ]); }); it('', () => { expect(sortArrayByParityII([2, 3, 1, 1, 4, 0, 0, 4, 3, 3])).toEqual([ 2, 3, 4, 1, 0, 1, 0, 3, 4, 3, ]); }); }); describe('sortArrayByParityIIInPlace', () => { it('', () => { expect(sortArrayByParityIIInPlace([4, 2, 5, 7])).toEqual([4, 5, 2, 7]); }); it('', () => { expect(sortArrayByParityIIInPlace([2, 3])).toEqual([2, 3]); }); it('', () => { expect(sortArrayByParityIIInPlace([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])).toEqual( [2, 1, 4, 3, 6, 5, 8, 7, 10, 9] ); }); it('', () => { expect(sortArrayByParityIIInPlace([2, 3, 1, 1, 4, 0, 0, 4, 3, 3])).toEqual([ 2, 3, 4, 1, 0, 1, 0, 3, 4, 3, ]); }); }); ================================================ FILE: coding_interviews/leetcode/easy/sort-even-and-odd-indices-independently/sort-even-and-odd-indices-independently.js ================================================ function decreasing(a, b) { return b - a; } function increasing(a, b) { return a - b; } function sortEvenOdd(nums) { let evens = []; let odds = []; for (let index = 0; index < nums.length; index++) { if (index % 2 === 0) evens.push(nums[index]); else odds.push(nums[index]); } evens.sort(increasing); odds.sort(decreasing); let result = []; let biggerLength = evens.length > odds.length ? evens.length : odds.length; for (let index = 0; index < biggerLength; index++) { if (index < evens.length) result.push(evens[index]); if (index < odds.length) result.push(odds[index]); } return result; } ================================================ FILE: coding_interviews/leetcode/easy/sort-integers-by-the-number-of-1-bits/sort-integers-by-the-number-of-1-bits.js ================================================ function toBinary(num) { if (num === 0) return { binary: '0', numberOfOneBits: 0 }; let binary = []; let numberOfOneBits = 0; let numCopy = num; while (numCopy > 0) { const binaryDigit = numCopy % 2; if (binaryDigit) numberOfOneBits++; binary.unshift(String(binaryDigit)); numCopy = Math.floor(numCopy / 2); } return { num, binary: binary.join(''), numberOfOneBits }; } function byNumberOfOneBits(binary1, binary2) { if (binary1.numberOfOneBits < binary2.numberOfOneBits) return -1; if (binary1.numberOfOneBits > binary2.numberOfOneBits) return 1; if ( binary1.numberOfOneBits === binary2.numberOfOneBits && binary1.num < binary2.num ) return -1; return 0; } function sortByBits(nums) { const hashmap = new Map(); const binaries = []; const result = []; for (let num of nums) { const binary = toBinary(num); hashmap.set(binary.binary, num); binaries.push(binary); } binaries.sort(byNumberOfOneBits); for (let { binary } of binaries) { result.push(hashmap.get(binary)); } return result; } ================================================ FILE: coding_interviews/leetcode/easy/sort-the-people/sort-the-people.js ================================================ function sortPeople(names, heights) { const heightToName = new Map(); for (let index = 0; index < names.length; index++) { const name = names[index]; const height = heights[index]; heightToName.set(height, name); } return heights .sort((height1, height2) => height2 - height1) .map((height) => heightToName.get(height)); } ================================================ FILE: coding_interviews/leetcode/easy/sort_array_by_parity/sort_array_by_parity.py ================================================ # https://leetcode.com/problems/sort-array-by-parity/submissions/ ''' Given an array A of non-negative integers, return an array consisting of all the even elements of A, followed by all the odd elements of A. You may return any answer array that satisfies this condition. Example: Input: [3,1,2,4] Output: [2,4,3,1] ''' def sort_array_by_parity(A): even_numbers = [] odd_numbers = [] for number in A: if number % 2 == 0: even_numbers.append(number) else: odd_numbers.append(number) return even_numbers + odd_numbers data_tests = [ ([1, 2, 3, 4], [2, 4, 1, 3]), ([3, 1, 2, 4], [2, 4, 3, 1]), ] for numbers, expected in data_tests: result = sort_array_by_parity(numbers) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/sort_sentence/sort_sentence.py ================================================ # https://leetcode.com/problems/sorting-the-sentence def sort_sentence(s): words = s.split() index_to_word = {} for word in words: index = int(word[-1]) actual_word = word[:len(word) - 1] index_to_word[index] = actual_word sentence = [] for index in range(1, len(words) + 1): sentence.append(index_to_word[index]) return ' '.join(sentence) ================================================ FILE: coding_interviews/leetcode/easy/special-positions-in-a-binary-matrix/special-positions-in-a-binary-matrix-cache.js ================================================ function countOnesInRow(matrix, row) { let ones = 0; for (let col = 0; col < matrix[row].length; col++) { if (matrix[row][col] === 1) ones++; } return ones; } function countOnesInCol(matrix, col) { let ones = 0; for (let row = 0; row < matrix.length; row++) { if (matrix[row][col] === 1) ones++; } return ones; } function numSpecial(matrix) { let specialPositions = 0; let hashmapRow = new Map(); let hashmapCol = new Map(); for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { let rowOnes = hashmapRow.has(row) ? hashmapRow.get(row) : countOnesInRow(matrix, row); hashmapRow.set(row, rowOnes); let colOnes = hashmapCol.has(col) ? hashmapCol.get(col) : countOnesInCol(matrix, col); hashmapCol.set(col, colOnes); if (matrix[row][col] === 1 && rowOnes === 1 && colOnes === 1) { specialPositions++; } } } return specialPositions; } ================================================ FILE: coding_interviews/leetcode/easy/special-positions-in-a-binary-matrix/special-positions-in-a-binary-matrix.js ================================================ function countOnesInRow(matrix, row) { let ones = 0; for (let col = 0; col < matrix[row].length; col++) { if (matrix[row][col] === 1) ones++; } return ones; } function countOnesInCol(matrix, col) { let ones = 0; for (let row = 0; row < matrix.length; row++) { if (matrix[row][col] === 1) ones++; } return ones; } function numSpecial(matrix) { let specialPositions = 0; for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { if ( matrix[row][col] === 1 && countOnesInRow(matrix, row) === 1 && countOnesInCol(matrix, col) === 1 ) { specialPositions++; } } } return specialPositions; } ================================================ FILE: coding_interviews/leetcode/easy/split-strings-by-separator/split-strings-by-separator.js ================================================ // https://leetcode.com/problems/split-strings-by-separator function splitWordsBySeparator(words, separator) { let output = []; for (let word of words) { let start = 0; for (let index = 0; index < word.length; index++) { if (word[index] === separator) { const str = word.slice(start, index); if (str.length) output.push(str); start = index + 1; } else if (index === word.length - 1) { output.push(word.slice(start, index + 1)); start = index + 1; } } } return output; } ================================================ FILE: coding_interviews/leetcode/easy/split-with-minimum-sum/split-with-minimum-sum.js ================================================ function splitNum(num) { let numsString = num .toString() .split('') .sort((a, b) => a - b); let firstHalf = []; let lastHalf = []; let isFirstHalf = true; for (let charNum of numsString) { if (isFirstHalf) firstHalf.push(charNum); else lastHalf.push(charNum); isFirstHalf = !isFirstHalf; } return Number(firstHalf.join('')) + Number(lastHalf.join('')); } ================================================ FILE: coding_interviews/leetcode/easy/split_string_in_balanced_strings/split_string_in_balanced_strings.py ================================================ # https://leetcode.com/problems/split-a-string-in-balanced-strings/ def balanced_string_split(s): els = 0 ares = 0 max = 0 for char in s: if char == 'L': els += 1 else: ares += 1 if els == ares: max += 1 els = 0 ares = 0 return max ================================================ FILE: coding_interviews/leetcode/easy/squares-of-a-sorted-array/squares-of-a-sorted-array-on.js ================================================ function buildArray(n) { const list = []; for (let i = 1; i <= n; i++) { list.push(0); } return list; } function sortedSquares(nums) { let sortedSquaresNumbers = buildArray(0); let leftIndex = 0; let rightIndex = nums.length - 1; let pointer = nums.length - 1; while (leftIndex <= rightIndex) { let left = nums[leftIndex]; let right = nums[rightIndex]; if (Math.abs(left) > Math.abs(right)) { sortedSquaresNumbers[pointer] = Math.pow(left, 2); leftIndex++; } else { sortedSquaresNumbers[pointer] = Math.pow(right, 2); rightIndex--; } pointer--; } return sortedSquaresNumbers; } ================================================ FILE: coding_interviews/leetcode/easy/squares-of-a-sorted-array/squares-of-a-sorted-array.js ================================================ function square(num) { return num * num; } function byIncreasingOrder(num1, num2) { return num1 - num2; } function sortedSquares(nums) { return nums.map(square).sort(byIncreasingOrder); } ================================================ FILE: coding_interviews/leetcode/easy/squares_of_a_sorted_array/squares_of_a_sorted_array.py ================================================ # https://leetcode.com/problems/squares-of-a-sorted-array ''' Given an array of integers A sorted in non-decreasing order, return an array of the squares of each number, also in sorted non-decreasing order. Example 1: Input: [-4,-1,0,3,10] Output: [0,1,9,16,100] Example 2: Input: [-7,-3,2,3,11] Output: [4,9,9,49,121] ''' def squares_of_a_sorted_array(A): new_array = [] for number in A: new_array.append(number * number) return sorted(new_array) def squares_of_a_sorted_array_in_place(A): for index in range(len(A)): A[index] = A[index] * A[index] return sorted(A) data_tests = [ ([-4, -1, 0, 3, 10], [0, 1, 9, 16, 100]), ([-7, -3, 2, 3, 11], [4, 9, 9, 49, 121]) ] for numbers, expected in data_tests: result = squares_of_a_sorted_array(numbers) print(result, result == expected) result = squares_of_a_sorted_array_in_place(numbers) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/str_str/str_str.py ================================================ ''' https://leetcode.com/problems/implement-strstr Implement strStr(). Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. - Example 1: Input: haystack = "hello", needle = "ll" Output: 2 - Example 2: Input: haystack = "aaaaa", needle = "bba" Output: -1 ''' def strStr(haystack, needle): if needle == '': return 0 neddle_length = len(needle) for index in range(len(haystack) - neddle_length + 1): if haystack[index:index+neddle_length] == needle: return index return -1 test_data = [ ("hello", "ll", 2), ("aaaaa", "bba", -1), ("other", "", 0), ] for haystack, needle, expected in test_data: result = strStr(haystack, needle) print('result as expected?', result == expected) ================================================ FILE: coding_interviews/leetcode/easy/string-matching-in-an-array/string-matching-in-an-array.js ================================================ function isSubstring(subword, word) { for (let index = 0; index <= word.length - subword.length; index++) { if (subword === word.slice(index, index + subword.length)) { return true; } } return false; } function addSubstring(word1, word2, answer) { if (word1.length <= word2.length) { isSubstring(word1, word2) && answer.add(word1); } else { isSubstring(word2, word1) && answer.add(word2); } } function stringMatching(words) { let answer = new Set([]); for (let i = 0; i < words.length - 1; i++) { for (let j = i + 1; j < words.length; j++) { let word1 = words[i]; let word2 = words[j]; addSubstring(word1, word2, answer); } } return [...answer]; } ================================================ FILE: coding_interviews/leetcode/easy/subarrays-distinct-element-sum-of-squares-i/subarrays-distinct-element-sum-of-squares-i.js ================================================ // https://leetcode.com/problems/subarrays-distinct-element-sum-of-squares-i function sumCounts(nums) { let sum = 0; for (let i = 0; i < nums.length; i++) { let set = new Set(); for (let j = i; j < nums.length; j++) { set.add(nums[j]); sum += set.size ** 2; } } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/subdomain_visit_count.py ================================================ ''' https://leetcode.com/problems/subdomain-visit-count/description/ Example 1: Input: ["9001 discuss.leetcode.com"] Output: ["9001 discuss.leetcode.com", "9001 leetcode.com", "9001 com"] Example 2: Input: ["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"] Output: ["901 mail.com", "50 yahoo.com", "900 google.mail.com", "5 wiki.org","5 org", "1 intel.mail.com", "951 com"] ''' def update_subdomain_counter(sc, s, c): if s in sc: sc[s] += int(c) else: sc[s] = int(c) def subdomain_visits(cpdomains): subdomain_counter = {} for cpdomain in cpdomains: code, subdomain = cpdomain.split(' ') update_subdomain_counter(subdomain_counter, subdomain, code) while subdomain.find(".") != -1: subdomain = subdomain.split('.', 1)[1] update_subdomain_counter(subdomain_counter, subdomain, code) return [str(counter) + " " + subdomain for subdomain, counter in subdomain_counter.items()] print(subdomain_visits(["9001 discuss.leetcode.com"])) print(subdomain_visits(["900 google.mail.com", "50 yahoo.com", "1 intel.mail.com", "5 wiki.org"])) ================================================ FILE: coding_interviews/leetcode/easy/substrings-of-size-three-with-distinct-characters/substrings-of-size-three-with-distinct-characters.js ================================================ function isGoodString(string) { let [char1, char2, char3] = string; return char1 !== char2 && char1 !== char3 && char2 !== char3; } function countGoodSubstrings(string) { let goodSubstringsCounter = 0; for (let index = 0; index < string.length - 2; index++) { const substring = string.slice(index, index + 3); if (isGoodString(substring)) { goodSubstringsCounter++; } } return goodSubstringsCounter; } ================================================ FILE: coding_interviews/leetcode/easy/subtract_product_and_sum/subtract_product_and_sum.py ================================================ # https://leetcode.com/problems/subtract-the-product-and-sum-of-digits-of-an-integer ''' Given an integer number n, return the difference between the product of its digits and the sum of its digits. Input: n = 234 Output: 15 Input: n = 4421 Output: 21 ''' def subtract_product_and_sum(num): multiplications = 1 additions = 0 for digit in str(num): multiplications *= int(digit) additions += int(digit) return multiplications - additions data_tests = [ (234, 15), (4421, 21) ] for num, expected in data_tests: result = subtract_product_and_sum(num) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/easy/subtree-of-another-tree/subtree-of-another-tree.js ================================================ function isSame(root, subRoot) { if (!root && !subRoot) return true; if (!root || !subRoot || root.val !== subRoot.val) return false; return isSame(root.left, subRoot.left) && isSame(root.right, subRoot.right); } function isSubtree(root, subRoot) { return root ? isSame(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot) : false; } ================================================ FILE: coding_interviews/leetcode/easy/sum-multiples/sum-multiples.js ================================================ function sumOfMultiples(n) { let sum = 0; for (let num = 1; num <= n; num++) { if (num % 7 === 0 || num % 5 === 0 || num % 3 === 0) { sum += num; } } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/sum-of-all-subset-xor-totals/sum-of-all-subset-xor-totals.js ================================================ function getAllSubsets(subset, nums, output, index) { if (index == nums.length) { subset.push(output); return; } getAllSubsets(subset, nums, [...output], index + 1); output.push(nums[index]); getAllSubsets(subset, nums, [...output], index + 1); } function calculateTotalXOR(nums) { let totalXOR = nums[0]; for (let i = 1; i < nums.length; i++) { totalXOR = totalXOR ^ nums[i]; } return totalXOR; } function subsetXORSum(nums) { let total = 0; let subset = []; getAllSubsets(subset, nums, [], 0); for (let list of subset) { if (list.length) total += calculateTotalXOR(list); } return total; } console.log(subsetXORSum([1, 2, 3])); ================================================ FILE: coding_interviews/leetcode/easy/sum-of-digits-in-base-k/sum-of-digits-in-base-k.js ================================================ function fromDecimalToK(n, k) { const baseKN = []; while (n) { baseKN.push(n % k); n = Math.floor(n / k); } return baseKN; } function sumBase(n, k) { return fromDecimalToK(n, k).reduce((num, sum) => sum + num, 0); } ================================================ FILE: coding_interviews/leetcode/easy/sum-of-digits-of-string-after-convert/sum-of-digits-of-string-after-convert.js ================================================ function toNum(char) { return char.charCodeAt() - 96; } function getNumbers(s) { let numbers = []; for (let char of s) { numbers.push(toNum(char)); } return numbers; } function sum(charNums) { return charNums.reduce( (sumOfNums, charNum) => sumOfNums + Number(charNum), 0 ); } function getLucky(s, k) { let numbers = getNumbers(s); let digits = numbers.join('').split(''); for (let index = 1; index <= k; index++) { digits = sum(digits).toString().split(''); } return Number(digits.join('')); } ================================================ FILE: coding_interviews/leetcode/easy/sum-of-left-leaves/sum-of-left-leaves.js ================================================ function sumOfLeftLeaves(root, isLeft = false) { if (!root) return 0; if (!root.left && !root.right && isLeft) return root.val; return sumOfLeftLeaves(root.left, true) + sumOfLeftLeaves(root.right, false); } ================================================ FILE: coding_interviews/leetcode/easy/sum-of-squares-of-special-elements/sum-of-squares-of-special-elements.js ================================================ // https://leetcode.com/problems/sum-of-squares-of-special-elements function sumOfSquares(nums) { let sum = 0; for (let i = 1; i <= nums.length; i++) { if (nums.length % i === 0) { sum += nums[i - 1] * nums[i - 1]; } } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/sum-of-values-at-indices-with-k-set-bits/sum-of-values-at-indices-with-k-set-bits.js ================================================ function toBinary(num) { if (num === 0) return '0'; let binary = []; while (num > 0) { binary.unshift(num % 2); num = Math.floor(num / 2); } return binary.join(''); } function checkSetBits(binary, k) { let countSetBits = 0; for (let digit of binary) { if (digit === '1') countSetBits++; } return countSetBits === k; } function sumIndicesWithKSetBits(nums, k) { let sum = 0; for (let index = 0; index < nums.length; index++) { let binary = toBinary(index); console.log(index, binary); let matchesKSetBits = checkSetBits(binary, k); if (matchesKSetBits) { sum += nums[index]; } } return sum; } ================================================ FILE: coding_interviews/leetcode/easy/sum_leaf_binary_numbers/sum_leaf_binary_numbers.py ================================================ # https://leetcode.com/problems/sum-of-root-to-leaf-binary-numbers total_binary_sum = 0 def sum_root_to_leaf(root): if root is None: return helper(root, str(root.val)) return total_binary_sum def helper(node, path): if node.left: helper(node.left, path + str(node.left.val)) if node.right: helper(node.right, path + str(node.right.val)) if node.right is None and node.left is None: total_binary_sum += int(path, 2) ================================================ FILE: coding_interviews/leetcode/easy/sum_of_all_odd_length_subarrays/sum_of_all_odd_length_subarrays.py ================================================ # https://leetcode.com/problems/sum-of-all-odd-length-subarrays ''' Time complexity: O(O*A*S) or O(N^3) to simplify, where O = number of odd numbers, A = length of arr, and S = sum of the subarrays Space complexity: O(1) ''' def sum_odd_length_subarrays(arr): odd, sum_of_subarrays = 1, 0 while (odd <= len(arr)): for index in range(0, len(arr) - odd + 1): sum_of_subarrays += sum(arr[index:index+odd]) odd += 2 return sum_of_subarrays ''' Time complexity: O(N) Space complexity: O(1) ''' def sum_odd_length_subarrays_optimized(A): sum_of_subarrays, length_of_A = 0, len(A) for index, num in enumerate(A): sum_of_subarrays += ((index + 1) * (length_of_A - index) + 1) // 2 * num return sum_odd_length_subarrays ================================================ FILE: coding_interviews/leetcode/easy/sum_of_unique_elements/sum_of_unique_elements.py ================================================ # https://leetcode.com/problems/sum-of-unique-elements def sum_of_unique(nums): mapper = {} for num in nums: if num in mapper: mapper[num] += 1 else: mapper[num] = 1 sum_of_unique_nums = 0 for key in mapper: if mapper[key] == 1: sum_of_unique_nums += key return sum_of_unique_nums ================================================ FILE: coding_interviews/leetcode/easy/sum_zero/sum_zero.py ================================================ def sum_zero(n): zero_sum_array = [] counter = 1 if n % 2 != 0: zero_sum_array.append(0) n -= 1 while n: zero_sum_array.append(counter) zero_sum_array.append(-counter) counter += 1 n -= 2 return zero_sum_array ================================================ FILE: coding_interviews/leetcode/easy/symmetric-tree/symmetric-tree.js ================================================ function symmetricNodes(node1, node2) { if ((!node1 && node2) || (node1 && !node2)) { return false; } if (!node1 && !node2) { return true; } return ( node1.val === node2.val && symmetricNodes(node1.left, node2.right) && symmetricNodes(node1.right, node2.left) ); } function isSymmetric(root) { if (!root) { return true; } return symmetricNodes(root.left, root.right); } ================================================ FILE: coding_interviews/leetcode/easy/take-gifts-from-the-richest-pile/take-gifts-from-the-richest-pile.js ================================================ function pickGifts(gifts, k) { while (k--) { let maxIndex = -Infinity; let max = -Infinity; for (let index = 0; index < gifts.length; index++) { if (gifts[index] > max) { maxIndex = index; max = gifts[index]; } } gifts[maxIndex] = Math.floor(Math.sqrt(gifts[maxIndex])); } return gifts.reduce((sum, gift) => sum + gift, 0); } ================================================ FILE: coding_interviews/leetcode/easy/three-consecutive-odds/three-consecutive-odds.js ================================================ function threeConsecutiveOdds(nums) { let counter = 0; for (let num of nums) { if (num % 2 === 0) counter = 0; else counter++; if (counter >= 3) return true; } return false; } ================================================ FILE: coding_interviews/leetcode/easy/time-needed-to-buy-tickets/time-needed-to-buy-tickets.js ================================================ function timeRequiredToBuy(tickets, k) { let count = 0; let pointer = 0; while (tickets[k]) { if (tickets[pointer]) { tickets[pointer]--; count++; } pointer = (pointer + 1) % tickets.length; } return count; } ================================================ FILE: coding_interviews/leetcode/easy/to_lower_case/to_lower_case.py ================================================ # https://leetcode.com/problems/to-lower-case/ ''' Implement function ToLowerCase() that has a string parameter str, and returns the same string in lowercase. Example 1: Input: "Hello" Output: "hello" Example 2: Input: "here" Output: "here" Example 3: Input: "LOVELY" Output: "lovely" ''' def lower_case_char(char): if ord(char) >= 65 and ord(char) <= 90: return chr(ord(char) + 32) return char def lower_case(str): list_of_chars = [] for char in str: list_of_chars.append(lower_case_char(char)) return ''.join(list_of_chars) data_tests = [ ('Hello', 'hello'), ('here', 'here'), ('LOVELY', 'lovely'), ('al&phaBET', 'al&phabet') ] for string, expected in data_tests: result = lower_case(string) print(result, expected == result) ================================================ FILE: coding_interviews/leetcode/easy/toeplitz-matrix/toeplitz-matrix.js ================================================ function isDiagonalToeplitz(matrix, value, row, col) { if (row >= matrix.length || col >= matrix[row].length) return true; if (value !== matrix[row][col]) return false; return isDiagonalToeplitz(matrix, matrix[row][col], row + 1, col + 1); } function isToeplitzMatrix(matrix) { for (let row = 0; row < matrix.length - 1; row++) { for (let col = 0; col < matrix[row].length - 1; col++) { if (!isDiagonalToeplitz(matrix, matrix[row][col], row + 1, col + 1)) return false; } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/transpose-matrix/transpose-matrix.js ================================================ function transpose(matrix) { let newMatrix = []; for (let col = 0; col < matrix[0].length; col++) { let newRow = []; for (let row = 0; row < matrix.length; row++) { newRow.push(matrix[row][col]); } newMatrix.push(newRow); } return newMatrix; } ================================================ FILE: coding_interviews/leetcode/easy/truncate_sentence/truncate_sentence.py ================================================ # https://leetcode.com/problems/truncate-sentence def truncate_sentence(s, k): start_index, end_index, words = 0, 0, [] for index, char in enumerate(s): end_index = index if char == ' ': words.append(s[start_index:end_index]) start_index = index + 1 words.append(s[start_index:]) truncated_words = [] for word in words[:k]: truncated_words.append(word) return ' '.join(truncated_words) def truncate_sentence(s, k): start_index, end_index, words = 0, 0, [] for index, char in enumerate(s): end_index = index if char == ' ': words.append(s[start_index:end_index]) start_index = index + 1 words.append(s[start_index:]) return ' '.join(words[:k]) def truncate_sentence(s, k): return ' '.join(s.split(' ')[0:k]) ================================================ FILE: coding_interviews/leetcode/easy/two-furthest-houses-with-different-colors/two-furthest-houses-with-different-colors.js ================================================ function maxDistance(colors) { let startPointer = 0; let endPointer = colors.length - 1; let maximumDistance = -Infinity; while (endPointer > startPointer) { if (colors[startPointer] !== colors[endPointer]) { maximumDistance = endPointer - startPointer; break; } endPointer--; } endPointer = colors.length - 1; while (startPointer < endPointer) { if ( colors[startPointer] !== colors[endPointer] && endPointer - startPointer > maximumDistance ) { maximumDistance = endPointer - startPointer; break; } startPointer++; } return maximumDistance; } ================================================ FILE: coding_interviews/leetcode/easy/two-out-of-three/two-out-of-three.js ================================================ function buildHashmap(nums) { let hashmap = new Map(); for (let num of nums) { hashmap.set(num, true); } return hashmap; } function checkAndAddNumbers(result, hashmap1, hashmap2, hashmap3) { hashmap1.forEach((_, num) => { if (hashmap2.has(num) || hashmap3.has(num)) { result.add(num); } }); } function twoOutOfThree(nums1, nums2, nums3) { let hashmap1 = buildHashmap(nums1); let hashmap2 = buildHashmap(nums2); let hashmap3 = buildHashmap(nums3); let result = new Set(); checkAndAddNumbers(result, hashmap1, hashmap2, hashmap3); checkAndAddNumbers(result, hashmap2, hashmap1, hashmap3); checkAndAddNumbers(result, hashmap3, hashmap2, hashmap1); return [...result]; } ================================================ FILE: coding_interviews/leetcode/easy/two-sum/two-sum.js ================================================ function twoSum(nums, target) { let numbersMap = {}; for (let [index, num] of nums.entries()) { numbersMap[num] = index; } for (let [index, num] of nums.entries()) { let remainder = target - num; let remainderIndex = numbersMap[remainder]; if (remainderIndex && index !== remainderIndex) { return [index, remainderIndex]; } } } ================================================ FILE: coding_interviews/leetcode/easy/two-sum-iv-input-is-a-bst/two-sum-iv-input-is-a-bst.js ================================================ function dfs(node, hashmap, values) { if (!node) { return node; } hashmap[node.val] = true; values.push(node.val); dfs(node.left, hashmap, values); dfs(node.right, hashmap, values); } function findTarget(root, k) { let hashmap = {}; let values = []; dfs(root, hashmap, values); for (let value of values) { if (hashmap[k - value] && k - value !== value) { return true; } } return false; } // second try with better memory usage function dfs2(node, target, hashmap) { if (!node) { return false; } if (hashmap[target - node.val]) { return true; } hashmap[node.val] = true; return dfs2(node.left, target, hashmap) || dfs2(node.right, target, hashmap); } function findTarget2(root, k) { return dfs2(root, k, {}); } ================================================ FILE: coding_interviews/leetcode/easy/two_sum.py ================================================ # https://leetcode.com/problems/two-sum/description/ def two_sum(nums, target): for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i, j] ================================================ FILE: coding_interviews/leetcode/easy/uncommon-words-from-two-sentences/uncommon-words-from-two-sentences.js ================================================ function buildCounter(sentence) { let counter = new Map(); for (let word of sentence) { if (counter.has(word)) counter.set(word, counter.get(word) + 1); else counter.set(word, 1); } return counter; } function getOnceWords(counter) { const onceWords = []; for (let [word, count] of counter) { if (count === 1) onceWords.push(word); } return onceWords; } function getUncommonWords(onceWords, map) { return onceWords.filter((onceWord) => !map.has(onceWord)); } function uncommonFromSentences(s1, s2) { const list1 = s1.split(' '); const list2 = s2.split(' '); const counter1 = buildCounter(list1); const counter2 = buildCounter(list2); const onceWords1 = getOnceWords(counter1); const onceWords2 = getOnceWords(counter2); return [ ...getUncommonWords(onceWords1, counter2), ...getUncommonWords(onceWords2, counter1), ]; } ================================================ FILE: coding_interviews/leetcode/easy/unique-number-of-occurrences/unique-number-of-occurrences.js ================================================ function uniqueOccurrences(arr) { const hashmap = new Map(); for (let num of arr) { if (hashmap.has(num)) { hashmap.set(num, hashmap.get(num) + 1); } else { hashmap.set(num, 1); } } const counts = []; hashmap.forEach((count, num) => { counts.push(count); }); return counts.length === new Set(counts).size; } ================================================ FILE: coding_interviews/leetcode/easy/unique_morse_code_words.py ================================================ # https://leetcode.com/problems/unique-morse-code-words/description/ # "gin" -> "--...-." # "zen" -> "--...-." # "gig" -> "--...--." # "msg" -> "--...--." def unique_morse_representations(words): morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] alphabet = 'abcdefghijklmnopqrstuvwxyz' morse_code_mapper = {} for index, letter in enumerate(alphabet): morse_code_mapper[letter] = morse[index] unique_codes = set() for word in words: code = '' for letter in word: code += morse_code_mapper[letter] unique_codes.add(code) return len(unique_codes) print(unique_morse_representations(["gin", "zen", "gig", "msg"]) == 2) ================================================ FILE: coding_interviews/leetcode/easy/unique_number_of_occurrences/unique_number_of_occurrences.py ================================================ # https://leetcode.com/problems/unique-number-of-occurrences def unique_occurrences(arr): num_to_occurrences = {} for num in arr: if num in num_to_occurrences: num_to_occurrences[num] += 1 else: num_to_occurrences[num] = 1 return len(num_to_occurrences) == len(set(num_to_occurrences.values())) from collections import Counter def unique_occurrences_2(arr): num_to_occurrences = Counter(arr) return len(num_to_occurrences) == len(set(num_to_occurrences.values())) ================================================ FILE: coding_interviews/leetcode/easy/univalued-binary-tree/univalued-binary-tree.js ================================================ function isUnivalTree(root) { if (!root) return true; const leftResult = isUnivalTree(root.left); const rightResult = isUnivalTree(root.right); let result = true; result = root.left ? root.val === root.left.val : result; result = root.right ? result && root.val === root.right.val : result; return result && leftResult && rightResult; } function isUnivalTree(root, value = root.val) { if (!root) return true; return ( root.val === value && isUnivalTree(root.left, value) && isUnivalTree(root.right, value) ); } ================================================ FILE: coding_interviews/leetcode/easy/valid-anagram/valid-anagram.js ================================================ function isAnagram(s, t) { if (s.length !== t.length) { return false; } let charCount = {}; for (let index = 0; index < s.length; index++) { let char = s[index]; if (charCount[char]) { charCount[char]++; } else { charCount[char] = 1; } } for (let char of t) { if (charCount[char]) { charCount[char]--; } else { return false; } } return true; } ================================================ FILE: coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome-2.js ================================================ function isPalindrome(s) { let string = s.toLowerCase().replace(/[^a-z0-9]/gi, ''); let start = 0; let end = string.length - 1; while (start <= end) { if (string[start] !== string[end]) { return false; } start++; end--; } return true; } ================================================ FILE: coding_interviews/leetcode/easy/valid-palindrome/valid-palindrome.js ================================================ const alphanumeric = 'abcdefghijklmnopqrstuvwxyz0123456789'; function downcase(string) { return string.toLowerCase(); } function keepAlphanumeric(string) { let alphanumericOnlyString = []; for (let char of string) { if (alphanumeric.includes(char)) { alphanumericOnlyString.push(char); } } return alphanumericOnlyString.join(''); } function isValidPalindrome(string) { let start = 0; let end = string.length - 1; while (start <= end) { if (string[start] !== string[end]) { return false; } start++; end--; } return true; } function isPalindrome(string) { return isValidPalindrome(keepAlphanumeric(downcase(string))); } ================================================ FILE: coding_interviews/leetcode/easy/valid-palindrome/valid_palindrome.py ================================================ ''' Given a string, determine whether its palindrome if you are allowed to delete at most one character Example "aba" - True "abca" - True "abccadsfa" - False "" - True "abca" 0 => "bca" "abca" 1 => "aca" ''' # Brute force def is_palindrome(string): return string == string[::-1] def build_new_string_variation(string, index): return string[:index] + string[index+1:] def valid_palindrome(string): if string == '': return True if is_palindrome(string): return True for index in range(len(string)): new_string = build_new_string_variation(string, index) if is_palindrome(new_string): return True return False data = [ ("aba", True), ("abca", True), ("abccadsfa", False), ("", True) ] for string, expected in data: result = valid_palindrome(string) print(result == expected) # Greedy Solution: find if it is not palindrome def valid_palindrome_2(string): if string == '': return True if is_palindrome(string): return True for i in range(len(string) // 2): last_current_index = len(string) - 1 - i if string[i] != string[last_current_index]: string_shifted_to_left = string[i:last_current_index] string_shifted_to_right = string[i + 1:last_current_index + 1] return is_palindrome(string_shifted_to_left) or is_palindrome(string_shifted_to_right) return True data = [ ("aba", True), ("abc", False), ("abca", True), ("abccadsfa", False), ("", True) ] for string, expected in data: result = valid_palindrome_2(string) print(result == expected) ================================================ FILE: coding_interviews/leetcode/easy/valid-parentheses/valid-parentheses.js ================================================ function matches(openBracket, closingBracket) { return ( { '}': '{', ']': '[', ')': '(', }[closingBracket] === openBracket ); } function isValid(s) { if (s.length === 1) { return false; } const stack = []; for (let char of s) { if (['(', '{', '['].includes(char)) { stack.push(char); } else { let top = stack.pop(); if (!matches(top, char)) { return false; } } } return stack.length === 0; } ================================================ FILE: coding_interviews/leetcode/easy/water-bottles/water-bottles.js ================================================ function numWaterBottles(numBottles, numExchange) { let drinkNum = numBottles; while (numBottles >= numExchange) { let remainingBottles = numBottles % numExchange; let newBottles = Math.floor(numBottles / numExchange); drinkNum += newBottles; numBottles = remainingBottles + newBottles; } return drinkNum; } ================================================ FILE: coding_interviews/leetcode/easy/weakest_rows/weakest_rows.py ================================================ # https://leetcode.com/problems/the-k-weakest-rows-in-a-matrix def k_weakest_rows(mat, k): sum_index_list = [[sum(row), index] for index, row in enumerate(mat)] return [sum_index[1] for sum_index in sorted(sum_index_list)][:k] ================================================ FILE: coding_interviews/leetcode/easy/xor-operation-in-an-array/xor-operation-in-an-array.js ================================================ function xorOperation(n, start) { let result = start; let number = start; for (let num = 1; num < n; num++) { number += 2; result ^= number; } return result; } ================================================ FILE: coding_interviews/leetcode/medium/3sum/3sum-tle.js ================================================ function sortTriplet(num1, num2, num3) { return [num1, num2, num3].sort((n1, n2) => n1 - n2); } function getSortedTripletString(num1, num2, num3) { let triplet = sortTriplet(num1, num2, num3); return `${triplet[0]}*${triplet[1]}*${triplet[2]}`; } function threeSum(nums) { if (nums.length < 3) { return []; } let triplets = []; let numberCount = {}; let usedTriplets = {}; let usedPairs = {}; for (let num of nums) { if (numberCount[num]) { numberCount[num]++; } else { numberCount[num] = 1; } } for (let i = 0; i < nums.length - 1; i++) { for (let j = i + 1; j < nums.length; j++) { let num1 = nums[i]; let num2 = nums[j]; let pairSum = num1 + num2; let missingTriplet = pairSum * -1; let sortedPairString = `${Math.min(num1, num2)}*${Math.max(num1, num2)}`; if (usedPairs[sortedPairString]) { continue; } let sortedTripletString = getSortedTripletString( num1, num2, missingTriplet ); if (usedTriplets[sortedTripletString]) { continue; } if ( (missingTriplet === num1 && missingTriplet === num2 && numberCount[missingTriplet] && numberCount[missingTriplet] >= 3) || (((missingTriplet === num1 && missingTriplet !== num2) || (missingTriplet !== num1 && missingTriplet === num2)) && numberCount[missingTriplet] && numberCount[missingTriplet] >= 2) || (missingTriplet !== num1 && missingTriplet !== num2 && numberCount[missingTriplet]) ) { triplets.push([num1, num2, missingTriplet]); usedTriplets[sortedTripletString] = true; usedPairs[sortedPairString] = true; continue; } } } return triplets; } ================================================ FILE: coding_interviews/leetcode/medium/add_two_numbers/add_two_numbers.py ================================================ # https://leetcode.com/problems/add-two-numbers/description/ ''' (1, 2, 3) + (2, 3, 4) = (3, 5, 7) (1, 2, 3) + (2, 9, 4) = (3, 1, 8) ''' class ListNode(object): def __init__(self, x): self.val = x self.next = None def add_two_numbers(l1, l2): carry = False result_list = r_list = ListNode(0) while l1 or l2 or carry: if l1 and l2: value = l1.val + l2.val l1 = l1.next l2 = l2.next elif l1: value = l1.val l1 = l1.next elif l2: value = l2.val l2 = l2.next else: value = 0 if carry: value += 1 carry = False if value >= 10: value -= 10 carry = True r_list.next = ListNode(value) r_list = r_list.next return result_list.next # Test 1: l1 = ListNode(1) l1.next = ListNode(2) l = l1.next l.next = ListNode(3) l2 = ListNode(2) l2.next = ListNode(9) l = l2.next l.next = ListNode(4) result_list = add_two_numbers(l1, l2) while result_list: print result_list.val result_list = result_list.next print "--------------------" # Test 2: l1 = ListNode(5) l2 = ListNode(5) result_list = add_two_numbers(l1, l2) while result_list: print result_list.val result_list = result_list.next ================================================ FILE: coding_interviews/leetcode/medium/all_elements_in_two_binary_search_trees/all_elements_in_two_binary_search_trees.py ================================================ # https://leetcode.com/problems/all-elements-in-two-binary-search-trees def get_all_elements(root1, root2): values = [] get_sorted_list(root1, values) get_sorted_list(root2, values) return sorted(values) def get_sorted_list(node, values): if node.left: get_sorted_list(node.left, values) values.append(node.val) if node.right: get_sorted_list(node.right, values) # --------------------------------------------------------------------- def get_sorted_elements_from(node): if not node: return [] elements = [] if node.left: elements = get_sorted_elements_from(node.left) elements.append(node.val) if node.right: elements += get_sorted_elements_from(node.right) return elements def get_all_elements(root1, root2): sorted_tree_1 = get_sorted_elements_from(root1) sorted_tree_2 = get_sorted_elements_from(root2) index_1, index_2 = 0, 0 result = [] while index_1 < len(sorted_tree_1) and index_2 < len(sorted_tree_2): value1 = sorted_tree_1[index_1] value2 = sorted_tree_2[index_2] if value1 <= value2: result.append(value1) index_1 += 1 else: result.append(value2) index_2 += 1 if index_1 < len(sorted_tree_1): result += sorted_tree_1[index_1:] if index_2 < len(sorted_tree_2): result += sorted_tree_2[index_2:] return result # --------------------------------------------------------------------- def get_sorted_elements_from(node, elements): if not node: return [] if node.left: get_sorted_elements_from(node.left, elements) elements.append(node.val) if node.right: get_sorted_elements_from(node.right, elements) def get_all_elements(root1, root2): sorted_tree_1 = [] get_sorted_elements_from(root1, sorted_tree_1) sorted_tree_2 = [] get_sorted_elements_from(root2, sorted_tree_2) index_1, index_2 = 0, 0 result = [] while index_1 < len(sorted_tree_1) and index_2 < len(sorted_tree_2): value1 = sorted_tree_1[index_1] value2 = sorted_tree_2[index_2] if value1 <= value2: result.append(value1) index_1 += 1 else: result.append(value2) index_2 += 1 if index_1 < len(sorted_tree_1): result += sorted_tree_1[index_1:] if index_2 < len(sorted_tree_2): result += sorted_tree_2[index_2:] return result ================================================ FILE: coding_interviews/leetcode/medium/arithmetic-subarrays/arithmetic-subarrays.py ================================================ # https://leetcode.com/problems/arithmetic-subarrays def check_arithmetic_subarrays(nums, l, r): answer = [] for index in range(len(l)): l_value = l[index] r_value = r[index] nums_range = sorted(nums[l_value:r_value+1]) is_arithmetic = True diff = nums_range[1] - nums_range[0] for i in range(2, len(nums_range)): if diff != nums_range[i] - nums_range[i-1]: is_arithmetic = False break answer.append(is_arithmetic) return answer ================================================ FILE: coding_interviews/leetcode/medium/balance-a-binary-search-tree/balance-a-binary-search-tree.js ================================================ function inorder(root, nodes) { if (root.left) inorder(root.left, nodes); nodes.push(root.val); if (root.right) inorder(root.right, nodes); } function toBST(start, end, nodes) { if (start > end) return null; const middle = Math.floor((start + end) / 2); const bst = new TreeNode(nodes[middle]); bst.left = toBST(start, middle - 1, nodes); bst.right = toBST(middle + 1, end, nodes); return bst; } function balanceBST(root) { const nodes = []; inorder(root, nodes); return toBST(0, nodes.length - 1, nodes); } ================================================ FILE: coding_interviews/leetcode/medium/binary-tree-inorder-traversal/binary-tree-inorder-traversal.py ================================================ # https://leetcode.com/problems/binary-tree-inorder-traversal class Solution: def __init__(self): self.inorder_list = [] def inorder_traversal(self, root): if root: self.inorder_traversal(root.left) self.inorder_list.append(root.val) self.inorder_traversal(root.right) return self.inorder_list ================================================ FILE: coding_interviews/leetcode/medium/binary-tree-level-order-traversal/binary-tree-level-order-traversal.js ================================================ function levelOrder(root) { if (!root) { return []; } let queue = [root]; let levelOrderTree = []; while (queue.length) { let levelNodes = []; let levels = queue.length; for (let level = 0; level < levels; level++) { let node = queue.shift(); if (node.left) { queue.push(node.left); } if (node.right) { queue.push(node.right); } levelNodes.push(node.val); } levelOrderTree.push(levelNodes); } return levelOrderTree; } ================================================ FILE: coding_interviews/leetcode/medium/bst_from_pre_order_traversal/bst_from_pre_order_traversal.py ================================================ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bst_from_preorder(preorder): root = TreeNode(preorder[0]) for value in preorder[1:]: helper(root, value) return root def helper(node, value): if value < node.val and node.left: helper(node.left, value) elif value < node.val: node.left = TreeNode(value) if value > node.val and node.right: helper(node.right, value) elif value > node.val: node.right = TreeNode(value) return node ================================================ FILE: coding_interviews/leetcode/medium/bst_to_greatest/bst_to_greatest.py ================================================ def sum_and_list(node, total, values): left_total = 0 right_total = 0 left_values = [] right_values = [] if node.left: [left_total, left_values] = sum_and_list(node.left, total, values) if node.right: [right_total, right_values] = sum_and_list(node.right, total, values) return [ total + left_total + node.val + right_total, values + left_values + [node.val] + right_values ] def modify_helper(node, mapper): if node.left: modify_helper(node.left, mapper) if node.right: modify_helper(node.right, mapper) node.val = mapper[node.val] return node def bst_to_gst(root): [total, values] = sum_and_list(root, 0, []) smaller_total = 0 mapper = {} for value in values: mapper[value] = total - smaller_total smaller_total += value return modify_helper(root, mapper) value = 0 def bst_to_gst(node): if node.right: bst_to_gst(node.right) node.val = node.val + value value = node.val if node.left: bst_to_gst(node.left) return node ================================================ FILE: coding_interviews/leetcode/medium/clone-graph/clone-graph.js ================================================ /* Cloning a graph using a Breadth-First Search — build a queue of all nodes in the graph — build a hashmap of all cloned nodes — if it's on the map: it's counted as visited & add to the neighbors' list — else create from scratch */ function cloneGraph(node) { if (!node) return; let clonedGraph = new Node(node.val); let queue = [node]; let createdNodes = { 1: clonedGraph, }; while (queue.length) { let currentNode = queue.shift(); let clonedNode = createdNodes[currentNode.val]; for (let neighbor of currentNode.neighbors) { if (createdNodes[neighbor.val]) { clonedNode.neighbors.push(createdNodes[neighbor.val]); } else { let createdNode = new Node(neighbor.val); createdNodes[neighbor.val] = createdNode; clonedNode.neighbors.push(createdNode); queue.push(neighbor); } } } return clonedGraph; } ================================================ FILE: coding_interviews/leetcode/medium/cloned_binary_tree/cloned_binary_tree.py ================================================ # https://leetcode.com/problems/find-a-corresponding-node-of-a-binary-tree-in-a-clone-of-that-tree/ def get_target_copy(original, cloned, target): if cloned.val == target.val: return cloned if cloned.left: result = get_target_copy(original.left, cloned.left, target) if result: return result if cloned.right: result = get_target_copy(original.right, cloned.right, target) if result: return result ================================================ FILE: coding_interviews/leetcode/medium/count-nodes-equal-to-average-of-subtree/count-nodes-equal-to-average-of-subtree.js ================================================ function calculateAverage(totalValue, nodesCount) { return Math.floor(totalValue / nodesCount); } function averageHelper(node, count) { if (!node) { return { totalValue: 0, nodesCount: 0, equalToAverageCount: 0 }; } const left = averageHelper(node.left, 1); const right = averageHelper(node.right, 1); const totalValue = node.val + left.totalValue + right.totalValue; const nodesCount = count + left.nodesCount + right.nodesCount; const average = calculateAverage(totalValue, nodesCount); const equalToAverageCount = (average === node.val ? 1 : 0) + left.equalToAverageCount + right.equalToAverageCount; return { totalValue, nodesCount, equalToAverageCount, }; } function averageOfSubtree(root) { let totalValue = root.val; let nodesCount = 1; const left = averageHelper(root.left, nodesCount); const right = averageHelper(root.right, nodesCount); const average = calculateAverage( totalValue + left.totalValue + right.totalValue, nodesCount + left.nodesCount + right.nodesCount ); return ( (average === root.val ? 1 : 0) + left.equalToAverageCount + right.equalToAverageCount ); } ================================================ FILE: coding_interviews/leetcode/medium/count-number-of-distinct-integers-after-reverse-operations/count-number-of-distinct-integers-after-reverse-operations-numbers.js ================================================ // https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations function reverseDigits(num) { let digits = 0; while (num > 0) { digits = digits * 10 + (num % 10); num = Math.floor(num / 10); } return digits; } function countDistinctIntegers(nums) { let set = new Set(); let N = nums.length; for (let index = 0; index < N; index++) { let num = nums[index]; set.add(num); let reversedDigitsNum = reverseDigits(num); set.add(reversedDigitsNum); } return set.size; } ================================================ FILE: coding_interviews/leetcode/medium/count-number-of-distinct-integers-after-reverse-operations/count-number-of-distinct-integers-after-reverse-operations.js ================================================ // https://leetcode.com/problems/count-number-of-distinct-integers-after-reverse-operations function reverseDigits(num) { let digits = []; while (num > 0) { digits.push((num % 10).toString()); num = Math.floor(num / 10); } return Number(digits.join('')); } function countDistinctIntegers(nums) { let set = new Set(); let N = nums.length; for (let index = 0; index < N; index++) { let num = nums[index]; set.add(num); let reversedDigitsNum = reverseDigits(num); set.add(reversedDigitsNum); } return set.size; } ================================================ FILE: coding_interviews/leetcode/medium/count-sorted-vowel-strings/count-sorted-vowel-strings.js ================================================ function countVowelStrings(n) { let a = 1, e = 1, i = 1, o = 1, u = 1; for (let counter = 1; counter < n; counter++) { o += u; i += o; e += i; a += e; } return a + e + i + o + u; } ================================================ FILE: coding_interviews/leetcode/medium/count-sub-islands/count-sub-islands-tle.js ================================================ /** - getting all islands in grid2 - store the rows and columns of each island - this can be stored in a list - e.g. [[[3,0]], [[4,1]], [2,1]] - iterate through the list of islands of grid2 - if all rows and cols from an island of grid2 match the cells in the grid1 - increment the number of sub-islands - return number of sub islands */ function isInsideTheGrid(grid, row, col) { return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length; } function dfs(grid, row, col) { if (!isInsideTheGrid(grid, row, col)) { return []; } if (grid[row][col]) { grid[row][col] = 0; return [ [row, col], ...dfs(grid, row - 1, col), ...dfs(grid, row + 1, col), ...dfs(grid, row, col - 1), ...dfs(grid, row, col + 1), ]; } return []; } function countSubIslands(grid1, grid2) { let islands = []; for (let row = 0; row < grid2.length; row++) { for (let col = 0; col < grid2[row].length; col++) { let cell = grid2[row][col]; if (cell) { grid2[row][col] = 0; let island = [ [row, col], ...dfs(grid2, row - 1, col), ...dfs(grid2, row + 1, col), ...dfs(grid2, row, col - 1), ...dfs(grid2, row, col + 1), ]; islands.push(island); } } } let numberOfSubIslands = 0; for (let island of islands) { let isSubIsland = true; for (let [row, col] of island) { if (grid1[row][col] === 0) { isSubIsland = false; break; } } if (isSubIsland) { numberOfSubIslands++; } } return numberOfSubIslands; } ================================================ FILE: coding_interviews/leetcode/medium/count-sub-islands/count-sub-islands.js ================================================ function dfs(grid1, grid2, row, col) { if ( row < 0 || row >= grid2.length || col < 0 || col >= grid2[0].length || grid2[row][col] == 0 ) { return 1; } grid2[row][col] = 0; let numberOfSubIslands = 1; numberOfSubIslands &= dfs(grid1, grid2, row - 1, col); numberOfSubIslands &= dfs(grid1, grid2, row + 1, col); numberOfSubIslands &= dfs(grid1, grid2, row, col - 1); numberOfSubIslands &= dfs(grid1, grid2, row, col + 1); return numberOfSubIslands & grid1[row][col]; } function countSubIslands(grid1, grid2) { let numberOfSubIslands = 0; for (let row = 0; row < grid2.length; row++) { for (let col = 0; col < grid2[row].length; col++) { if (grid2[row][col]) { numberOfSubIslands += dfs(grid1, grid2, row, col); } } } return numberOfSubIslands; } ================================================ FILE: coding_interviews/leetcode/medium/count_points/count_points.py ================================================ # https://leetcode.com/problems/queries-on-number-of-points-inside-a-circle def is_point_within_circuference(qx, qy, qr, px, py): return qr ** 2 >= abs(qx - px) ** 2 + abs(qy - py) ** 2 def count_points(points, queries): answer = [] for [qx, qy, qr] in queries: count = 0 for [px, py] in points: if is_point_within_circuference(qx, qy, qr, px, py): count += 1 answer.append(count) return answer ================================================ FILE: coding_interviews/leetcode/medium/counter_number_of_teams/counter_number_of_teams.py ================================================ def num_teams(rating): counter = 0 for i in range(len(rating) - 2): for j in range(i + 1, len(rating) - 1): for k in range(j + 1, len(rating)): if (rating[i] < rating[j] and rating[j] < rating[k]) or ( rating[i] > rating[j] and rating[j] > rating[k]): counter += 1 return counter def num_teams(rating): asc = desc = 0 for index, value in enumerate(rating): llc = rgc = lgc = rlc = 0 for left in rating[:index]: if left > value: lgc += 1 if left < value: llc += 1 for right in rating[index + 1:]: if right > value: rgc += 1 if right < value: rlc += 1 asc += llc * rgc desc += lgc * rlc return asc + desc ================================================ FILE: coding_interviews/leetcode/medium/deck_revealed_increasing/deck_revealed_increasing.py ================================================ # https://leetcode.com/problems/reveal-cards-in-increasing-order import queue def deck_revealed_increasing(deck): q = queue.Queue() sorted_deck = sorted(deck) for index in range(len(deck)): q.put(index) result = [0] * len(deck) index = 0 while not q.empty(): result[q.get()] = sorted_deck[index] index += 1 if not q.empty(): q.put(q.get()) return result ================================================ FILE: coding_interviews/leetcode/medium/decode-string/decode-string.js ================================================ const isNum = (char) => !isNaN(Number(char)); export function decodeString(encodedString) { const stack = []; let index = 0; while (index < encodedString.length) { const char = encodedString[index]; if (isNum(char)) { const number = []; while (isNum(encodedString[index])) { number.push(encodedString[index]); index++; } stack.push(Number(number.join(''))); continue; } if (char === ']') { let str = ''; while (stack[stack.length - 1] !== '[') { str = stack.pop() + str; } stack.pop(); stack.push(str.repeat(stack.pop())); index++; continue; } stack.push(char); index++; } return stack.join(''); } ================================================ FILE: coding_interviews/leetcode/medium/decode-string/tests/decode-string.test.js ================================================ import { describe, it, expect } from 'vitest'; import { decodeString } from '../decode-string'; describe('decodeString', () => { it('', () => { expect(decodeString('3[a]2[bc]')).toEqual('aaabcbc'); }); it('', () => { expect(decodeString('2[abc]3[cd]ef')).toEqual('abcabccdcdcdef'); }); it('', () => { expect(decodeString('3[a2[c]]')).toEqual('accaccacc'); }); it('', () => { expect(decodeString('100[leetcode]')).toEqual( 'leetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcodeleetcode' ); }); }); ================================================ FILE: coding_interviews/leetcode/medium/deepest_leaves_sum/deepest_leaves_sum.py ================================================ # https://leetcode.com/problems/deepest-leaves-sum ''' Given a binary tree, return the sum of values of its deepest leaves. Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15 ''' def sum_deepest_leaves(root): mapper = helper(root, {}, 1) deepest_level = 1 for level in mapper: if level > deepest_level: deepest_level = level deepest_level_nodes_values = mapper[deepest_level] nodes_values_sum = 0 for node_value in deepest_level_nodes_values: nodes_values_sum += node_value return nodes_values_sum def helper(node, mapper, level): if level in mapper: mapper[level] = mapper[level] + [node.val] else: mapper[level] = [node.val] if node.left: mapper = helper(node.left, mapper, level + 1) if node.right: mapper = helper(node.right, mapper, level + 1) return mapper ================================================ FILE: coding_interviews/leetcode/medium/delete-node-in-a-linked-list/better-delete-node-in-a-linked-list.js ================================================ // https://leetcode.com/problems/delete-node-in-a-linked-list /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } * @param {ListNode} node * @return {void} Do not return anything, modify node in-place instead. */ function deleteNode(node) { node.val = node.next.val; node.next = node.next.next; } ================================================ FILE: coding_interviews/leetcode/medium/delete-node-in-a-linked-list/delete-node-in-a-linked-list.js ================================================ // https://leetcode.com/problems/delete-node-in-a-linked-list /** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } * @param {ListNode} node * @return {void} Do not return anything, modify node in-place instead. */ function deleteNode(node) { if (node.next && !node.next.next) { node.val = node.next.val; node.next = null; return; } node.val = node.next.val; deleteNode(node.next); } ================================================ FILE: coding_interviews/leetcode/medium/design-a-stack-with-increment-operation/design-a-stack-with-increment-operation.js ================================================ export const CustomStack = function (maxSize) { this.maxSize = maxSize; this.items = []; }; CustomStack.prototype.push = function (x) { if (this.items.length < this.maxSize) { this.items.push(x); } }; CustomStack.prototype.pop = function () { return this.items.length > 0 ? this.items.pop() : -1; }; CustomStack.prototype.increment = function (k, val) { for (let i = 0; i < k; i++) { if (i <= this.items.length - 1) this.items[i] += val; } }; ================================================ FILE: coding_interviews/leetcode/medium/design-a-stack-with-increment-operation/tests/design-a-stack-with-increment-operation.test.js ================================================ import { describe, expect, it } from 'vitest'; import { CustomStack } from '../design-a-stack-with-increment-operation'; describe('CustomStack', () => { it('', () => { const customStack = new CustomStack(3); customStack.push(1); customStack.push(2); expect(customStack.pop()).toEqual(2); customStack.push(2); customStack.push(3); customStack.push(4); customStack.increment(5, 100); customStack.increment(2, 100); expect(customStack.pop()).toEqual(103); expect(customStack.pop()).toEqual(202); expect(customStack.pop()).toEqual(201); expect(customStack.pop()).toEqual(-1); }); }); ================================================ FILE: coding_interviews/leetcode/medium/design-add-and-search-words-data-structure/design-add-and-search-words-data-structure.js ================================================ function isTheSame(word, wordFromDict) { if (word.length !== wordFromDict.length) return false; for (let index = 0; index < word.length; index++) { let wordChar = word[index]; let wordFromDictChar = wordFromDict[index]; if (wordChar === '.') { continue; } if (wordChar !== wordFromDictChar) { return false; } } return true; } const WordDictionary = function () { this.hashmap = {}; }; WordDictionary.prototype.addWord = function (word) { if (!this.hashmap[word]) { this.hashmap[word] = true; } }; WordDictionary.prototype.search = function (word) { if (this.hashmap[word]) { return this.hashmap[word]; } let words = Object.keys(this.hashmap); for (let wordFromDict of words) { if (isTheSame(word, wordFromDict)) { return true; } } return false; }; ================================================ FILE: coding_interviews/leetcode/medium/difference-between-ones-and-zeros-in-row-and-column/difference-between-ones-and-zeros-in-row-and-column.js ================================================ function traverseGridRow(grid, row) { let diff = 0; for (let col = 0; col < grid[row].length; col++) { let cell = grid[row][col]; if (cell) { diff++; } else { diff--; } } return diff; } function traverseGridCol(grid, col) { let diff = 0; for (let row = 0; row < grid.length; row++) { let cell = grid[row][col]; if (cell) { diff++; } else { diff--; } } return diff; } function onesMinusZeros(grid) { let rows = []; let cols = []; let diffGrid = []; for (let row = 0; row < grid.length; row++) { let diffRow = []; for (let col = 0; col < grid[row].length; col++) { let rowDiff; let colDiff; if (row < rows.length) { rowDiff = rows[row]; } else { rowDiff = traverseGridRow(grid, row); rows.push(rowDiff); } if (col < cols.length) { colDiff = cols[col]; } else { colDiff = traverseGridCol(grid, col); cols.push(colDiff); } diffRow.push(rowDiff + colDiff); } diffGrid.push(diffRow); } return diffGrid; } ================================================ FILE: coding_interviews/leetcode/medium/encode_and_decode_tinyurl/encode_and_decode_tinyurl.py ================================================ # https://leetcode.com/problems/encode-and-decode-tinyurl class Codec: count = 0 tiny_to_url = {} url_to_tiny = {} tiny_url_prefix = 'http://tinyurl.com/' def encode(self, longUrl: str) -> str: if longUrl in self.url_to_tiny: return self.url_to_tiny[longUrl] tiny_url = self.tiny_url_prefix + str(self.count) self.url_to_tiny[longUrl] = tiny_url self.tiny_to_url[tiny_url] = longUrl self.count += 1 return tiny_url def decode(self, shortUrl: str) -> str: return self.tiny_to_url[shortUrl] ================================================ FILE: coding_interviews/leetcode/medium/execution-of-all-suffix-instructions-staying-in-a-grid/execution-of-all-suffix-instructions-staying-in-a-grid.js ================================================ // https://leetcode.com/problems/execution-of-all-suffix-instructions-staying-in-a-grid function isOffGrid(row, col, n) { return row < 0 || row >= n || col < 0 || col >= n; } function executeInstructions(n, startPos, s) { let answer = []; for (let index = 0; index < s.length; index++) { let instructionIndex = index; let instruction = s[instructionIndex]; let row = startPos[0]; let col = startPos[1]; let numOfInstructions = 0; if (instruction === 'R') col++; if (instruction === 'L') col--; if (instruction === 'U') row--; if (instruction === 'D') row++; while (instructionIndex < s.length && !isOffGrid(row, col, n)) { instructionIndex++; instruction = s[instructionIndex]; if (instruction === 'R') col++; if (instruction === 'L') col--; if (instruction === 'U') row--; if (instruction === 'D') row++; numOfInstructions++; } answer.push(numOfInstructions); } return answer; } ================================================ FILE: coding_interviews/leetcode/medium/find-the-original-array-of-prefix-xor/README.md ================================================ # Find The Original Array of Prefix Xor [Problem link](https://leetcode.com/problems/find-the-original-array-of-prefix-xor) - If you want `5 ^ ? = 2`, you can do a reverse xor using `5 ^ 2 = ?`, which in this case `? = 7` - If you want to do consecutive XOR operations like `5 ^ 7 ^ 2 ^ 3 ^ 2`, you can replace that with the previous `pref` item - e.g. `5 ^ 7 ^ ? = 0.`, you want to find `?` - so you need to do `5 ^ 7 ^ 0 = ?` but at that point, if you don't store the previous result, you don't have `5 ^ 7` - but you can get this calculation from the previous `pref` item because it can replace `5 ^ 7`, in this case, it is `2` - Runtime complexity: O(N), where N is prev.length ================================================ FILE: coding_interviews/leetcode/medium/find-the-original-array-of-prefix-xor/find-the-original-array-of-prefix-xor.js ================================================ function findArray(pref) { let output = [pref[0]]; for (let index = 1; index < pref.length; index++) { output.push(pref[index - 1] ^ pref[index]); } return output; } ================================================ FILE: coding_interviews/leetcode/medium/find-the-winner-of-the-circular-game/find-the-winner-of-the-circular-game.js ================================================ // https://leetcode.com/problems/find-the-winner-of-the-circular-game function toArray(n) { let list = []; for (let num = 1; num <= n; num++) { list.push(num); } return list; } function findTheWinner(n, k) { let list = toArray(n); let index = 0; while (list.length > 1) { index = (index + k - 1) % list.length; list.splice(index, 1); } return list[0]; } ================================================ FILE: coding_interviews/leetcode/medium/find-the-winner-of-the-circular-game/queue-find-the-winner-of-the-circular-game.js ================================================ // https://leetcode.com/problems/find-the-winner-of-the-circular-game function buildQueue(n) { let queue = []; for (let num = 1; num <= n; num++) { queue.push(num); } return queue; } function findTheWinner(n, k) { let queue = buildQueue(n); while (queue.length > 1) { let count = 1; while (count < k) { queue.push(queue.shift()); count++; } queue.shift(); } return queue[0]; } ================================================ FILE: coding_interviews/leetcode/medium/find-triangular-sum-of-an-array/find-triangular-sum-of-an-array.js ================================================ function calculate(num1, num2) { return (num1 + num2) % 10; } export function triangularSum(nums) { let numsCopy = [...nums]; let newNums = []; let N = nums.length; for (let i = 0; i < N - 1; i++) { newNums = []; for (let index = 0; index < numsCopy.length - 1; index++) { newNums.push(calculate(numsCopy[index], numsCopy[index + 1])); } numsCopy = newNums; } return numsCopy; } ================================================ FILE: coding_interviews/leetcode/medium/find-triangular-sum-of-an-array/tests/find-triangular-sum-of-an-array.test.js ================================================ import { describe, expect, it } from 'vitest'; import { triangularSum } from '../find-triangular-sum-of-an-array'; describe('triangularSum', () => { it('', () => { expect(triangularSum([1, 2, 3, 4, 5])).toEqual([8]); }); it('', () => { expect(triangularSum([5])).toEqual([5]); }); }); ================================================ FILE: coding_interviews/leetcode/medium/find-valid-matrix-given-row-and-column-sums/find-valid-matrix-given-row-and-column-sums.js ================================================ function buildMatrix(rows, cols) { const matrix = []; for (let row = 0; row < rows; row++) { let matrixRow = []; for (let col = 0; col < cols; col++) { matrixRow.push(0); } matrix.push(matrixRow); } return matrix; } function restoreMatrix(rowSum, colSum) { const matrix = buildMatrix(rowSum.length, colSum.length); for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[0].length; col++) { const min = Math.min(rowSum[row], colSum[col]); matrix[row][col] = min; rowSum[row] -= min; colSum[col] -= min; } } return matrix; } ================================================ FILE: coding_interviews/leetcode/medium/find_and_replace_pattern/find_and_replace_pattern.py ================================================ # https://leetcode.com/problems/find-and-replace-pattern def find_and_replace_pattern(words, pattern): matchers = [] for word in words: mapper = {} match = True used_pattern_letters = set() for index in range(len(word)): word_letter = word[index] pattern_letter = pattern[index] if word_letter in mapper and mapper[word_letter] != pattern_letter or (pattern_letter in used_pattern_letters and word_letter not in mapper): match = False break if word_letter not in mapper: used_pattern_letters.add(pattern_letter) mapper[word_letter] = pattern_letter if match: matchers.append(word) return matchers ================================================ FILE: coding_interviews/leetcode/medium/finding_pairs_with_a_certain_sum/finding_pairs_with_a_certain_sum.py ================================================ # https://leetcode.com/problems/finding-pairs-with-a-certain-sum class FindSumPairs: def __init__(self, nums1, nums2): self.nums1 = nums1 self.nums2 = nums2 self.nums2_freq = Counter(nums2) def add(self, index, val): self.nums2_freq[self.nums2[index]] -= 1 self.nums2[index] += val self.nums2_freq[self.nums2[index]] += 1 def count(self, total): count = 0 for num in self.nums1: if (total - num) in self.nums2_freq: count += self.nums2_freq[total - num] return count ================================================ FILE: coding_interviews/leetcode/medium/finding_the_users_active_minutes/finding_the_users_active_minutes.py ================================================ # https://leetcode.com/problems/finding-the-users-active-minutes def build_unique_actions_by_id(logs): unique_actions_by_id = {} for [id, minute] in logs: if id in unique_actions_by_id: unique_actions_by_id[id].add(minute) else: unique_actions_by_id[id] = set({minute}) return unique_actions_by_id def build_count_by_actions_number(unique_actions_by_id): count = {} for _, actions in unique_actions_by_id.items(): if len(actions) in count: count[len(actions)] += 1 else: count[len(actions)] = 1 return count def build_answer(count_by_actions_number, k): answer = [] for num in range(1, k + 1): if num in count_by_actions_number: answer.append(count_by_actions_number[num]) else: answer.append(0) return answer def finding_users_active_minutes(logs, k): unique_actions_by_id = build_unique_actions_by_id(logs) count_by_actions_number = build_count_by_actions_number(unique_actions_by_id) return build_answer(count_by_actions_number, k) # ------------------------------------------------------------------------------- def finding_users_active_minutes(logs, k): d = defaultdict(set) for id, minute in logs: d[id].add(minute) answer = [0] * k for _, actions in d.items(): count = len(actions) answer[count - 1] += 1 return answer ================================================ FILE: coding_interviews/leetcode/medium/fraction_to_decimal/fraction_to_decimal.py ================================================ def fraction_to_decimal(numerator, denominator): if numerator == 0: return '0' if numerator % denominator == 0: return str(numerator // denominator) result = '' if ('-' in str(numerator)) ^ ('-' in str(denominator)): result += '-' numerator = abs(numerator) denominator = abs(denominator) number = str(numerator // denominator) result += number result += '.' mapper = {} remainder = numerator % denominator while True: if remainder == 0: break if remainder in mapper: result = result[:mapper[remainder]] + \ '(' + result[mapper[remainder]:] + ')' break mapper[remainder] = len(result) remainder *= 10 result += str(remainder // denominator) remainder %= denominator return result data_test = [ (1, 2, "0.5"), (2, 1, "2"), (2, 3, "0.(6)"), (4, 333, "0.(012)"), (1, 4, "0.25"), (1, 6, "0.1(6)"), (-1, 6, "-0.1(6)"), (1, -6, "-0.1(6)"), (-50, 8, "-6.25"), (1, 214748364, "0.00(000000465661289042462740251655654056577585848337359161441621040707904997124914069194026549138227660723878669455195477065427143370461252966751355553982241280310754777158628319049732085502639731402098131932683780538602845887105337854867197032523144157689601770377165713821223802198558308923834223016478952081795603341592860749337303449725)") ] for numerator, denominator, expected in data_test: result = fraction_to_decimal(numerator, denominator) print(result, result == expected) ================================================ FILE: coding_interviews/leetcode/medium/group-anagrams/group-anagrams.js ================================================ function sort(string) { return [...string].sort((c1, c2) => c1.localeCompare(c2)).join(''); } function groupAnagrams(strs) { let hashmap = {}; for (let string of strs) { let sortedString = sort(string); if (hashmap[sortedString]) { hashmap[sortedString].push(string); } else { hashmap[sortedString] = [string]; } } return Object.values(hashmap); } ================================================ FILE: coding_interviews/leetcode/medium/group_the_people/group_the_people.py ================================================ # https://leetcode.com/problems/group-the-people-given-the-group-size-they-belong-to/ def group_the_people(groupSizes): grouped_by_size = {} for index in range(len(groupSizes)): size = groupSizes[index] if size in grouped_by_size: grouped_by_size[size] += [index] else: grouped_by_size[size] = [index] grouped_by_ids = [] for size, indices in grouped_by_size.items(): for index in range(0, len(indices), size): grouped_by_ids.append(indices[index:index+size]) return grouped_by_ids ================================================ FILE: coding_interviews/leetcode/medium/insert-greatest-common-divisors-in-linked-list/insert-greatest-common-divisors-in-linked-list.js ================================================ /** * https://leetcode.com/problems/insert-greatest-common-divisors-in-linked-list * * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ function calculateGCD(x, y) { x = Math.abs(x); y = Math.abs(y); while (y) { var t = y; y = x % y; x = t; } return x; } function insertGreatestCommonDivisors(head) { if (!head.next) return head; let curr = head; let next = head.next; while (next) { let newNode = new ListNode(calculateGCD(curr.val, next.val), next); curr.next = newNode; curr = next; next = next.next; } return head; } ================================================ FILE: coding_interviews/leetcode/medium/insert-into-a-binary-search-tree/insert-into-a-binary-search-tree.js ================================================ function insertIntoBST(root, val) { if (!root) { return new TreeNode(val); } if (val < root.val) { root.left = insertIntoBST(root.left, val); } if (val > root.val) { root.right = insertIntoBST(root.right, val); } return root; } ================================================ FILE: coding_interviews/leetcode/medium/insert_bst/insert_bst.py ================================================ class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def insert_into_BST(root, val): if root is None: return TreeNode(val) if val < root.val: root.left = insert_into_BST(root.left, val) if val > root.val: root.right = insert_into_BST(root.right, val) return root ================================================ FILE: coding_interviews/leetcode/medium/keep_city_skyline/keep_city_skyline.py ================================================ # https://leetcode.com/problems/max-increase-to-keep-city-skyline/description/ # input: grid = [[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]] # output: 35 def build_top_or_bottom(grid): top_or_bottom = [] for i in range(len(grid[0])): highest_building = 0 for j in range(len(grid)): if grid[j][i] > highest_building: highest_building = grid[j][i] top_or_bottom.append(highest_building) return top_or_bottom def build_left_or_right(grid): left_or_right = [] for line in grid: highest_building = 0 for building_height in line: if building_height > highest_building: highest_building = building_height left_or_right.append(highest_building) return left_or_right def max_increase_keeping_skyline(grid): top_or_bottom = build_top_or_bottom(grid) left_or_right = build_left_or_right(grid) increased_number = 0 for i in range(len(grid)): for j in range(len(grid[i])): if left_or_right[i] < top_or_bottom[j]: increased_number += (left_or_right[i] - grid[i][j]) else: increased_number += (top_or_bottom[j] - grid[i][j]) return increased_number print(max_increase_keeping_skyline([[3,0,8,4],[2,4,5,7],[9,2,6,3],[0,3,1,0]])) ================================================ FILE: coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-1.js ================================================ function traverse(node, list) { return node ? [ ...list, ...traverse(node.left, list), node.val, ...traverse(node.right, list), ] : []; } function kthSmallest(root, k) { return traverse(root, [])[k - 1]; } ================================================ FILE: coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst-2.js ================================================ let counter; let nodeValue; function traverseAndGetKthSmallest(node, k) { if (!node) return; traverseAndGetKthSmallest(node.left, k); counter++; if (counter === k) { nodeValue = node.val; } traverseAndGetKthSmallest(node.right, k); } function kthSmallest(root, k) { counter = 0; nodeValue = -1; traverseAndGetKthSmallest(root, k); return nodeValue; } ================================================ FILE: coding_interviews/leetcode/medium/kth-smallest-element-in-a-bst/kth-smallest-element-in-a-bst.js ================================================ // Solution 1 // additional memory usage: array function traverse(node, list) { return node ? [ ...list, ...traverse(node.left, list), node.val, ...traverse(node.right, list), ] : []; } function kthSmallest(root, k) { return traverse(root, [])[k - 1]; } // =========================== // =========================== // Solution 2 // Less memory let counter; let nodeValue; function traverseAndGetKthSmallest(node, k) { if (!node) return; traverseAndGetKthSmallest(node.left, k); counter++; if (counter === k) { nodeValue = node.val; } traverseAndGetKthSmallest(node.right, k); } function kthSmallest(root, k) { counter = 0; nodeValue = -1; traverseAndGetKthSmallest(root, k); return nodeValue; } ================================================ FILE: coding_interviews/leetcode/medium/letter_tile_possibilities/letter_tile_possibilities.py ================================================ # https://leetcode.com/problems/letter-tile-possibilities def num_tile_possibilities(tiles): res = set() def dfs(path, tile): if path not in res: if path: res.add(path) for i in range(len(tile)): dfs(path + tile[i], tile[:i] + tile[i+1:]) dfs('', tiles) return len(res) ================================================ FILE: coding_interviews/leetcode/medium/longest-substring-without-repeating-characters/longest-substring-without-repeating-characters.js ================================================ /** abcadccb => abc / bcad / cad / adc / dc / c / cb => 4 "abcadccb" ^ ^ localCount = 0 -> 1 -> 2 -> 1 -> 2 -> 3; maxCount = 0 -> 1 -> 2 -> 3; set = ['b', 'c'] -> ['c', 'd', 'a'] -> ['c', 'd', 'a', 'b'] */ function lengthOfLongestSubstring(s) { let leftPointer = 0; let maxCount = 0; let charToIndex = {}; for (let rightPointer = 0; rightPointer < s.length; rightPointer++) { let num = s[rightPointer]; let index = charToIndex[num]; if (index == undefined) { maxCount = Math.max(maxCount, rightPointer - leftPointer + 1); } else { if (index >= leftPointer) { leftPointer = index + 1; } else { maxCount = Math.max(maxCount, rightPointer - leftPointer + 1); } } charToIndex[num] = rightPointer; } return maxCount; } ================================================ FILE: coding_interviews/leetcode/medium/max-area-of-island/max-area-of-island.js ================================================ function isOffTheGrid(grid, row, col) { let gridRows = grid.length; let gridCols = grid[0].length; return row < 0 || row >= gridRows || col < 0 || col >= gridCols; } function dfs(grid, row, col, maximumLocalIslandArea = 0) { if (isOffTheGrid(grid, row, col) || grid[row][col] === 0) { return 0; } grid[row][col] = 0; // visited return ( 1 + dfs(grid, row - 1, col, maximumLocalIslandArea) + // top dfs(grid, row + 1, col, maximumLocalIslandArea) + // bottom dfs(grid, row, col + 1, maximumLocalIslandArea) + // right dfs(grid, row, col - 1, maximumLocalIslandArea) // left ); } function maxAreaOfIsland(grid) { let maximumIslandArea = 0; for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length; col++) { let maximumLocalIslandArea = dfs(grid, row, col); maximumIslandArea = Math.max(maximumIslandArea, maximumLocalIslandArea); } } return maximumIslandArea; } ================================================ FILE: coding_interviews/leetcode/medium/max_coins/max_coins.py ================================================ # https://leetcode.com/problems/maximum-number-of-coins-you-can-get def max_coins(piles): piles = sorted(piles) bob = 0 me = len(piles) - 2 alice = len(piles) - 1 counter = 0 while me > bob: counter += piles[me] bob += 1 me -= 2 alice -= 2 return counter ================================================ FILE: coding_interviews/leetcode/medium/maximum-sum-of-an-hourglass/maximum-sum-of-an-hourglass.js ================================================ // https://leetcode.com/problems/maximum-sum-of-an-hourglass function maxRowSum(grid, row, col) { return ( grid[row][col] + grid[row][col + 1] + grid[row][col + 2] + grid[row + 1][col + 1] + grid[row + 2][col] + grid[row + 2][col + 1] + grid[row + 2][col + 2] ); } function maxSum(grid) { let maxSumOfAnHourglass = 0; for (let row = 0; row + 2 < grid.length; row++) { for (let col = 0; col + 2 < grid[row].length; col++) { maxSumOfAnHourglass = Math.max( maxSumOfAnHourglass, maxRowSum(grid, row, col) ); } } return maxSumOfAnHourglass; } ================================================ FILE: coding_interviews/leetcode/medium/maximum_binary_tree/maximum_binary_tree.py ================================================ ''' https://leetcode.com/problems/maximum-binary-tree/description/ Input: [3,2,1,6,0,5] Output: return the tree root node representing the following tree: 6 / \ 3 5 \ / 2 0 \ 1 ''' class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None def construct_maximum_binary_tree(nums): if not nums: return None root_node = TreeNode(max(nums)) root_node.left = construct_maximum_binary_tree(nums[0:nums.index(max(nums))]) root_node.right = construct_maximum_binary_tree(nums[nums.index(max(nums))+1:]) return root_node ================================================ FILE: coding_interviews/leetcode/medium/median_tree/median_tree.py ================================================ class Node: def __init__(self, value, left, right): self.value = value self.left = left self.right = right def sum_and_count_nodes(node, sum_of_values, count): if node is None: return sum_of_values, count sum_of_values, count = sum_and_count_nodes(node.left, sum_of_values + node.value, count + 1) sum_of_values, count = sum_and_count_nodes(node.right, sum_of_values + node.value, count + 1) return sum_of_values, count def median(tree): sum_of_values, count = sum_and_count_nodes(tree, 0, 0) if count == 0: return 0 return sum_of_values / count left = Node(1, None, None) right = Node(2, None, None) root = Node(3, left, right) result = median(root) print(result) ================================================ FILE: coding_interviews/leetcode/medium/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js ================================================ export class ListNode { constructor(val, next) { this.val = val === undefined ? 0 : val; this.next = next === undefined ? null : next; } } export function mergeNodes(head) { let nonZeroHead; let node; let nextNode; let currentNode = head.next; let valueSum = 0; let gotFirstNode = false; while (currentNode) { valueSum += currentNode.val; if (currentNode.val === 0) { nextNode = new ListNode(valueSum); valueSum = 0; if (gotFirstNode) { node.next = nextNode; node = node.next; } else { node = nextNode; nonZeroHead = nextNode; gotFirstNode = true; } } currentNode = currentNode.next; } return nonZeroHead; } ================================================ FILE: coding_interviews/leetcode/medium/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js ================================================ import { describe, it, expect } from 'vitest'; import { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros'; function buildList(nums, initValue = 0) { let head = new ListNode(initValue); let node = head; let nextNode; for (let i = 1; i < nums.length; i++) { nextNode = new ListNode(nums[i]); node.next = nextNode; node = node.next; } return head; } describe('mergeNodes', () => { it('removes zeros and merges nodes', () => { const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]); const result = buildList([4, 11], 4); expect(mergeNodes(head)).toEqual(result); }); it('removes zeros and merges nodes', () => { const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]); const result = buildList([1, 3, 4], 1); expect(mergeNodes(head)).toEqual(result); }); }); ================================================ FILE: coding_interviews/leetcode/medium/min-cost-climbing-stairs/min-cost-climbing-stairs.js ================================================ // https://leetcode.com/problems/min-cost-climbing-stairs // https://leetcode.com/problems/min-cost-climbing-stairs/solutions/476388/4-ways-step-by-step-from-recursion-top-down-dp-bottom-up-dp-fine-tuning function getMinCost(stairs, index, dp) { if (index < 0) return 0; if (index === 0 || index === 1) return stairs[index]; if (dp[index]) return dp[index]; dp[index] = stairs[index] + Math.min( getMinCost(stairs, index - 1, dp), getMinCost(stairs, index - 2, dp) ); return dp[index]; } function minCostClimbingStairs(cost) { let dp = []; let minCostFirst = getMinCost(cost, cost.length - 1, dp); let minCostSecond = getMinCost(cost, cost.length - 2, dp); return Math.min(minCostFirst, minCostSecond); } ================================================ FILE: coding_interviews/leetcode/medium/min_operations/min_operations.py ================================================ def min_operations(n): operations = 0 for index in range(n // 2): operations += n - (2 * index + 1) return operations ================================================ FILE: coding_interviews/leetcode/medium/min_pair_sum/min_pair_sum.py ================================================ # https://leetcode.com/problems/minimize-maximum-pair-sum-in-array def min_pair_sum(nums): sorted_nums = sorted(nums) maximum_pair_sum = float('-Inf') for i in range(len(nums) // 2): pair_sum = sorted_nums[i] + sorted_nums[len(sorted_nums) - i - 1] maximum_pair_sum = max(maximum_pair_sum, pair_sum) return maximum_pair_sum ================================================ FILE: coding_interviews/leetcode/medium/min_partitions/min_partitions.py ================================================ # https://leetcode.com/problems/partitioning-into-minimum-number-of-deci-binary-numbers def min_partitions(n): count = '0' for digit_char in n: if digit_char > count: count = digit_char return int(count) def min_partitions(n): return int(max(n)) ================================================ FILE: coding_interviews/leetcode/medium/minimum-add-to-make-parentheses-valid/minimum-add-to-make-parentheses-valid.js ================================================ /* "(" => 1 ")" => 1 "()" => 0 "(()" => 1 "())" => 1 "(((" => 3 ")))" => 3 ")(" => 2 => "()(" => "()()" "()))((" => 4 */ function minAddToMakeValid(s) { let closeParenthesisCount = 0; let openParenthesisStack = []; for (let stringIndex = 0; stringIndex < s.length; stringIndex++) { const char = s[stringIndex]; if (char === '(') { openParenthesisStack.push(char); } else { if (openParenthesisStack.length) { openParenthesisStack.pop(); } else { closeParenthesisCount++; } } } return closeParenthesisCount + openParenthesisStack.length; } ================================================ FILE: coding_interviews/leetcode/medium/minimum-amount-of-time-to-collect-garbage/minimum-amount-of-time-to-collect-garbage.js ================================================ function measure(garbage, travel, garbageType) { let minutes = 0; let lastGarbageItem = -1; for (let [index, garbageItems] of garbage.entries()) { let itemCount = 0; for (let item of garbageItems) { if (item === garbageType) { lastGarbageItem = index; itemCount++; } } minutes += itemCount; } for (let index = 0; index < lastGarbageItem; index++) { minutes += travel[index]; } return minutes; } function garbageCollection(garbage, travel) { let minutes = 0; minutes += measure(garbage, travel, 'G'); minutes += measure(garbage, travel, 'M'); minutes += measure(garbage, travel, 'P'); return minutes; } ================================================ FILE: coding_interviews/leetcode/medium/minimum-cost-of-buying-candies-with-discount/minimum-cost-of-buying-candies-with-discount.js ================================================ // https://leetcode.com/problems/minimum-cost-of-buying-candies-with-discount function sum(cost) { let sumOfAllCost = 0; for (let c of cost) { sumOfAllCost += c; } return sumOfAllCost; } function minimumCost(cost) { if (cost.length <= 2) return sum(cost); cost.sort((a, b) => a - b); let allCost = 0; let index; for (index = cost.length - 1; index > 1; index -= 3) { if (cost[index] <= cost[index - 2]) { allCost += cost[index - 1] + cost[index - 2]; } else { allCost += cost[index] + cost[index - 1]; } } allCost += sum(cost.slice(0, index + 1)); return allCost; } ================================================ FILE: coding_interviews/leetcode/medium/minimum-number-of-steps-to-make-two-strings-anagram/README.md ================================================ # Minimum Number of Steps to Make Two Strings Anagram [Problem link](https://leetcode.com/problems/minimum-number-of-steps-to-make-two-strings-anagram) - Using the hash map data structure - Runtime complexity: O(N), where N is the length of `s` and `t` - Counting and comparing characters require hash maps to get the count based on each character - key: characters - value: count of each character ================================================ FILE: coding_interviews/leetcode/medium/minimum-number-of-steps-to-make-two-strings-anagram/minimum-number-of-steps-to-make-two-strings-anagram.js ================================================ function buildMap(string) { let map = new Map(); for (let char of string) { if (map.has(char)) map.set(char, map.get(char) + 1); else map.set(char, 1); } return map; } function minSteps(s, t) { let sMap = buildMap(s); let tMap = buildMap(t); let minimumSteps = 0; for (let [char, count] of sMap.entries()) { if (!tMap.has(char)) { minimumSteps += count; } else if (count > tMap.get(char)) { minimumSteps += count - tMap.get(char); } } return minimumSteps; } ================================================ FILE: coding_interviews/leetcode/medium/minimum_number_of_operations_to_move_all_balls_to_each_box/minimum_number_of_operations_to_move_all_balls_to_each_box.py ================================================ # https://leetcode.com/problems/minimum-number-of-operations-to-move-all-balls-to-each-box/ def min_operations(boxes): answer = [] for index in range(len(boxes)): counter = 0 for box_index in range(len(boxes)): if index != box_index and boxes[box_index] == '1': counter += abs(index - box_index) answer.append(counter) return answer def sum_moves(answer, boxes, boxes_indices): moves, number_of_balls_seen = 0, 0 for index in boxes_indices: answer[index] += moves if boxes[index] == '1': number_of_balls_seen += 1 moves += number_of_balls_seen return answer def min_operations(boxes): length_boxes = len(boxes) answer, moves, number_of_balls_seen = [0] * length_boxes, 0, 0 answer = sum_moves(answer, boxes, range(length_boxes)) return sum_moves(answer, boxes, reversed(range(length_boxes))) ================================================ FILE: coding_interviews/leetcode/medium/number-of-closed-islands/number-of-closed-islands.js ================================================ /** - is it in the border: no closed island - length == 1, 2: no closed island - visited data structure: map - iterate: [1,1] -> [n-1,n-1] - is it 0 - go to top, bottom, left, right with a dfs fn - is it 0: go to top, bottom, left, right with recursive call to the dfs fn */ function generateVisitedKey(row, col) { return `${row}-${col}`; } function isInsideTheGrid(grid, row, col) { return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length; } function dfs(grid, row, col, visited) { let key = generateVisitedKey(row, col); if (!isInsideTheGrid(grid, row, col)) { return false; } if (grid[row][col] === 1 || visited[key]) { return true; } if (grid[row][col] === 0 && !visited[key]) { visited[key] = true; let top = dfs(grid, row - 1, col, visited); let bottom = dfs(grid, row + 1, col, visited); let left = dfs(grid, row, col - 1, visited); let right = dfs(grid, row, col + 1, visited); return top && bottom && left && right; } } function closedIsland(grid) { if (grid.length <= 2 || grid[0].length <= 2) { return 0; } let visited = {}; let closedIslandsNumber = 0; for (let row = 1; row < grid.length - 1; row++) { for (let col = 1; col < grid[row].length - 1; col++) { let cell = grid[row][col]; let key = generateVisitedKey(row, col); if (cell === 0 && !visited[key]) { visited[key] = true; let top = dfs(grid, row - 1, col, visited); let bottom = dfs(grid, row + 1, col, visited); let left = dfs(grid, row, col - 1, visited); let right = dfs(grid, row, col + 1, visited); let isClosedIsland = top && bottom && left && right; if (isClosedIsland) { closedIslandsNumber++; } } } } return closedIslandsNumber; } ================================================ FILE: coding_interviews/leetcode/medium/number-of-enclaves/number-of-enclaves.js ================================================ /** - 0 => true - dfs => (top, bottom, left, right) - off the grid => false */ function getVisitedKey(row, col) { return `${row}-${col}`; } function isOffTheGrid(grid, row, col) { return row < 0 || col < 0 || row >= grid.length || col >= grid[0].length; } function dfs(grid, row, col, visited) { if (isOffTheGrid(grid, row, col)) { return -1; } if (grid[row][col] === 0) { return 0; } let key = getVisitedKey(row, col); if (visited[key]) { return 0; } visited[key] = true; let top = dfs(grid, row - 1, col, visited); let bottom = dfs(grid, row + 1, col, visited); let left = dfs(grid, row, col - 1, visited); let right = dfs(grid, row, col + 1, visited); return top === -1 || bottom === -1 || left === -1 || right === -1 ? -1 : 1 + top + bottom + left + right; } function numEnclaves(grid) { let numberOfLands = 0; let visited = {}; for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length; col++) { let cell = grid[row][col]; let key = getVisitedKey(row, col); if (cell && !visited[key]) { visited[key] = true; let top = dfs(grid, row - 1, col, visited); let bottom = dfs(grid, row + 1, col, visited); let left = dfs(grid, row, col - 1, visited); let right = dfs(grid, row, col + 1, visited); numberOfLands += top === -1 || bottom === -1 || left === -1 || right === -1 ? 0 : 1 + top + bottom + left + right; } } } return numberOfLands; } ================================================ FILE: coding_interviews/leetcode/medium/number-of-islands/number-of-islands.js ================================================ function isInsideTheGrid(grid, row, col) { return row >= 0 && row < grid.length && col >= 0 && col < grid[0].length; } function dfs(grid, row, col) { if (isInsideTheGrid(grid, row, col) && grid[row][col] === '1') { grid[row][col] = 0; // marked as visited dfs(grid, row - 1, col); // top dfs(grid, row + 1, col); // bottom dfs(grid, row, col - 1); // left dfs(grid, row, col + 1); // right } } function numIslands(grid) { let numberOfIslands = 0; for (let row = 0; row < grid.length; row++) { for (let col = 0; col < grid[row].length; col++) { if (grid[row][col] === '1') { numberOfIslands++; grid[row][col] = 0; // marked as visited dfs(grid, row - 1, col); // top dfs(grid, row + 1, col); // bottom dfs(grid, row, col - 1); // left dfs(grid, row, col + 1); // right } } } return numberOfIslands; } ================================================ FILE: coding_interviews/leetcode/medium/number-of-laser-beams-in-a-bank/number-of-laser-beams-in-a-bank.js ================================================ /* Anti-theft security devices are activated inside a bank. You are given a 0-indexed binary string array bank representing the floor plan of the bank, which is an m x n 2D matrix. bank[i] represents the ith row, consisting of '0's and '1's. '0' means the cell is empty, while'1' means the cell has a security device. There is one laser beam between any two security devices if both conditions are met: The two devices are located on two different rows: r1 and r2, where r1 < r2. - For each row i where r1 < i < r2, there are no security devices in the ith row. - Laser beams are independent, i.e., one beam does not interfere nor join with another. Return the total number of laser beams in the bank. */ export function numberOfBeams(bank) { let lasersCount = 0; const securityDevices = []; for (let row = 0; row < bank.length; row++) { let numberOfSecurityDevices = 0; for (let col = 0; col < bank[row].length; col++) { numberOfSecurityDevices += Number(bank[row][col]); } if (numberOfSecurityDevices) { securityDevices.push(numberOfSecurityDevices); } } for (let i = 0; i < securityDevices.length - 1; i++) { lasersCount += securityDevices[i] * securityDevices[i + 1]; } return lasersCount; } ================================================ FILE: coding_interviews/leetcode/medium/number-of-laser-beams-in-a-bank/tests/number-of-laser-beams-in-a-bank.test.js ================================================ import { describe, expect, it } from 'vitest'; import { numberOfBeams } from '../number-of-laser-beams-in-a-bank'; describe('numberOfBeams', () => { it('', () => { expect(numberOfBeams(['011001', '000000', '010100', '001000'])).toEqual(8); }); it('', () => { expect(numberOfBeams(['000', '111', '000'])).toEqual(0); }); }); ================================================ FILE: coding_interviews/leetcode/medium/optimal-partition-of-string/optimal-partition-of-string.js ================================================ // https://leetcode.com/problems/optimal-partition-of-string function partitionString(s) { let partition = []; let substring = ''; let substringMap = new Map(); for (let index = 0; index < s.length; index++) { if (substringMap.has(s[index])) { partition.push(substring); substring = s[index]; substringMap = new Map([[s[index], 1]]); } else { substring += s[index]; substringMap.set(s[index], 1); } if (index === s.length - 1) { partition.push(substring); } } return partition.length; } ================================================ FILE: coding_interviews/leetcode/medium/optimal-partition-of-string/optimized-optimal-partition-of-string.js ================================================ // https://leetcode.com/problems/optimal-partition-of-string function partitionString(s) { let substringMap = new Map([[s[0], 1]]); let count = 1; for (let index = 1; index < s.length; index++) { if (substringMap.has(s[index])) { substringMap = new Map([[s[index], 1]]); count++; } else { substringMap.set(s[index], 1); } } return count; } ================================================ FILE: coding_interviews/leetcode/medium/pair-sum/pair-sum.js ================================================ /* In a linked list of size n, where n is even, the ith node (0-indexed) of the linked list is known as the twin of the (n-1-i)th node, if 0 <= i <= (n / 2) - 1. For example, if n = 4, then node 0 is the twin of node 3, and node 1 is the twin of node 2. These are the only nodes with twins for n = 4. The twin sum is defined as the sum of a node and its twin. Given the head of a linked list with even length, return the maximum twin sum of the linked list. Input: head = [5,4,2,1] Output: 6 Input: head = [4,2,2,3] Output: 7 Input: head = [1,100000] Output: 100001 */ export function pairSum(list) { let maximumTwin = 0; for (let i = 0; i < Math.floor(list.length / 2); i++) { maximumTwin = Math.max(maximumTwin, list[i] + list[list.length - 1 - i]); } return maximumTwin; } export function pairSumLinkedList(head) { const list = []; while (head) { list.push(head.val); head = head.next; } return pairSum(list); } ================================================ FILE: coding_interviews/leetcode/medium/pair-sum/tests/pair-sum.test.js ================================================ import { describe, expect, it } from 'vitest'; import { pairSum } from '../pair-sum'; describe('pairSum', () => { it('', () => { expect(pairSum([5, 4, 2, 1])).toEqual(6); }); it('', () => { expect(pairSum([4, 2, 2, 3])).toEqual(7); }); it('', () => { expect(pairSum([1, 100000])).toEqual(100001); }); }); ================================================ FILE: coding_interviews/leetcode/medium/partition-array-according-to-given-pivot/partition-array-according-to-given-pivot.js ================================================ /* You are given a 0-indexed integer array nums and an integer pivot. Rearrange nums such that the following conditions are satisfied: Every element less than pivot appears before every element greater than pivot. Every element equal to pivot appears in between the elements less than and greater than pivot. The relative order of the elements less than pivot and the elements greater than pivot is maintained. More formally, consider every pi, pj where pi is the new position of the ith element and pj is the new position of the jth element. For elements less than pivot, if i < j and nums[i] < pivot and nums[j] < pivot, then pi < pj. Similarly for elements greater than pivot, if i < j and nums[i] > pivot and nums[j] > pivot, then pi < pj. Return nums after the rearrangement. */ export function pivotArray(nums, pivot) { const lessThanPivot = []; const equalToPivot = []; const greaterThanPivot = []; nums.forEach((num) => { if (num === pivot) { equalToPivot.push(num); } if (num < pivot) { lessThanPivot.push(num); } if (num > pivot) { greaterThanPivot.push(num); } }); return [...lessThanPivot, ...equalToPivot, ...greaterThanPivot]; } ================================================ FILE: coding_interviews/leetcode/medium/partition-array-according-to-given-pivot/tests/partition-array-according-to-given-pivot.test.js ================================================ import { describe, expect, it } from 'vitest'; import { pivotArray } from '../partition-array-according-to-given-pivot'; describe('pivotArray', () => { it('', () => { expect(pivotArray([9, 12, 5, 10, 14, 3, 10], 10)).toEqual([ 9, 5, 3, 10, 10, 12, 14, ]); }); it('', () => { expect(pivotArray([-3, 4, 3, 2], 2)).toEqual([-3, 2, 4, 3]); }); }); ================================================ FILE: coding_interviews/leetcode/medium/permutation-in-string/permutation-in-string-sliding-window.js ================================================ function buildCharCount(string) { let charCount = {}; for (let char of string) { if (charCount[char]) { charCount[char]++; } else { charCount[char] = 1; } } return charCount; } function isPermutation(possiblePermutation, string) { let charCount = buildCharCount(string); for (let char of possiblePermutation) { if (charCount[char]) { charCount[char]--; } else { return false; } } return true; } function checkInclusion(s1, s2) { for (let pointer1 = 0; pointer1 <= s2.length - s1.length; pointer1++) { let pointer2 = pointer1 + s1.length; let possiblePermutation = s2.substring(pointer1, pointer2); if (isPermutation(possiblePermutation, s1)) { return true; } } return false; } ================================================ FILE: coding_interviews/leetcode/medium/permutation-in-string/permutation-in-string.js ================================================ function buildCharCount(string) { let charCount = {}; for (let char of string) { if (charCount[char]) { charCount[char]++; } else { charCount[char] = 1; } } return charCount; } function isPermutation(possiblePermutation, string) { let charCount = buildCharCount(string); for (let char of possiblePermutation) { if (charCount[char]) { charCount[char]--; } else { return false; } } return true; } function checkInclusion(s1, s2) { let char = s1[0]; let charIndices = []; for (let index = 0; index < s2.length; index++) { if (s2[index] === char) { charIndices.push(index); } } let possiblePermutations = []; for (let index of charIndices) { for (let pointer = 1; pointer <= s1.length; pointer++) { let startIndex = index - s1.length + pointer; let endIndex = index + pointer; let substring = s2.substring(startIndex, endIndex); if (substring.length === s1.length) { possiblePermutations.push(substring); } } } for (let possiblePermutation of possiblePermutations) { if (isPermutation(possiblePermutation, s1)) { return true; } } return false; } ================================================ FILE: coding_interviews/leetcode/medium/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node-simpler.js ================================================ function dfs(node, next) { if (!node) return; node.next = next; dfs(node.left, node.right); dfs(node.right, next && next.left); } function connect(root) { dfs(root, null); return root; } ================================================ FILE: coding_interviews/leetcode/medium/populating-next-right-pointers-in-each-node/populating-next-right-pointers-in-each-node.js ================================================ function connectHelperRight(node) { if (!node) { return; } connectHelper(node.left, node.right); connectHelperRight(node.right); } function connectHelper(node, next) { if (!node || !next) { return; } node.next = next; connectHelper(node.left, node.right); connectHelper(node.right, next.left); } function connect(root) { if (!root) { return root; } connectHelper(root.left, root.right); connectHelperRight(root.right); return root; } ================================================ FILE: coding_interviews/leetcode/medium/process_queries/process_queries.py ================================================ def process_queries(queries, m): result = [] list_m = list(range(1, m + 1)) for index in range(len(queries)): for index_m in range(len(list_m)): if queries[index] == list_m[index_m]: result.append(index_m) list_m = [list_m[index_m] ] + list_m[:index_m] + list_m[index_m + 1:] break return result ================================================ FILE: coding_interviews/leetcode/medium/product-of-array-except-self/product-of-array-except-self.js ================================================ function productExceptSelf(nums) { let zeros = 0; let answer = []; let product = 1; for (let num of nums) { if (num) product *= num; else zeros++; } for (let num of nums) { if (num) { answer.push(zeros ? 0 : product / num); } else { answer.push(zeros > 1 ? 0 : product); } } return answer; } ================================================ FILE: coding_interviews/leetcode/medium/rearrange-array-elements-by-sign/rearrange-array-elements-by-sign.js ================================================ /* You are given a 0-indexed integer array nums of even length consisting of an equal number of positive and negative integers. You should rearrange the elements of nums such that the modified array follows the given conditions: Every consecutive pair of integers have opposite signs. For all integers with the same sign, the order in which they were present in nums is preserved. The rearranged array begins with a positive integer. Return the modified array after rearranging the elements to satisfy the aforementioned conditions. Example 1: Input: nums = [3,1,-2,-5,2,-4] Output: [3,-2,1,-5,2,-4] Explanation: The positive integers in nums are [3,1,2]. The negative integers are [-2,-5,-4]. The only possible way to rearrange them such that they satisfy all conditions is [3,-2,1,-5,2,-4]. Other ways such as [1,-2,2,-5,3,-4], [3,1,2,-2,-5,-4], [-2,3,-5,1,-4,2] are incorrect because they do not satisfy one or more conditions. Example 2: Input: nums = [-1,1] Output: [1,-1] Explanation: 1 is the only positive integer and -1 the only negative integer in nums. So nums is rearranged to [1,-1]. */ function isPositive(num) { return num > 0; } export function rearrangeArray(nums) { const negative = []; const positive = []; nums.forEach((num) => { if (isPositive(num)) { positive.push(num); } else { negative.push(num); } }); const rearrangeArray = []; for (let i = 0; i < negative.length; i++) { rearrangeArray.push(positive[i]); rearrangeArray.push(negative[i]); } return rearrangeArray; } ================================================ FILE: coding_interviews/leetcode/medium/rearrange-array-elements-by-sign/tests/rearrange-array-elements-by-sign.test.js ================================================ import { describe, expect, it } from 'vitest'; import { rearrangeArray } from '../rearrange-array-elements-by-sign'; describe('rearrangeArray', () => { it('', () => { expect(rearrangeArray([3, 1, -2, -5, 2, -4])).toEqual([ 3, -2, 1, -5, 2, -4, ]); }); it('', () => { expect(rearrangeArray([-1, 1])).toEqual([1, -1]); }); }); ================================================ FILE: coding_interviews/leetcode/medium/reduce_array_size_to_the_half/reduce_array_size_to_the_half.py ================================================ # https://leetcode.com/problems/reduce-array-size-to-the-half ''' Time Complexity: O(NlogN) Space Complexity: O(N) ''' def min_set_size(arr): num_to_count, counts, min_size, current_length = {}, [], 0, len(arr) for num in arr: if num in num_to_count: num_to_count[num] += 1 else: num_to_count[num] = 1 for num in num_to_count: counts.append(num_to_count[num]) counts = reversed(sorted(counts)) if len(arr) % 2 == 0: cut = len(arr) / 2 else: cut = len(arr + 1) / 2 for count in counts: min_size += 1 current_length -= count if current_length <= cut: return min_size return min_size ================================================ FILE: coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list-fast-slow.js ================================================ function removeNthFromEnd(head, n) { fast = head; slow = head; while (n) { fast = fast.next; n--; } if (!fast) { return head.next; } while (fast.next) { fast = fast.next; slow = slow.next; } slow.next = slow.next.next; return head; } ================================================ FILE: coding_interviews/leetcode/medium/remove-nth-node-from-end-of-list/remove-nth-node-from-end-of-list.js ================================================ /** * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ function countNodes(head) { let count = 0; while (head) { count++; head = head.next; } return count; } function removeNthFromEnd(head, n) { let count = countNodes(head); let nth = count - n; let node = head; if (nth === 0) { head = head.next; return head; } while (node) { if (nth === 1) { node.next = node.next.next; } nth--; node = node.next; } return head; } ================================================ FILE: coding_interviews/leetcode/medium/rotate-array/rotate-array-optimized.js ================================================ function reverseInPlace(nums, start, end) { while (start < end) { let temporaryStart = nums[start]; nums[start] = nums[end]; nums[end] = temporaryStart; start++; end--; } } function rotate(nums, k) { if (k <= 0) { return; } let start = 0; let end = nums.length - 1; let limit = k % nums.length; reverseInPlace(nums, start, end - limit); reverseInPlace(nums, end - limit + 1, end); reverseInPlace(nums, start, end); } ================================================ FILE: coding_interviews/leetcode/medium/rotate-array/rotate-array.js ================================================ function rotate(nums, k) { let count = 0; while (count < k) { const num = nums.pop(); nums.unshift(num); count++; } } ================================================ FILE: coding_interviews/leetcode/medium/rotate-image/rotate-image.js ================================================ function setupMatrix(matrix) { const newMatrix = []; for (let row = 0; row < matrix.length; row++) { const newRow = []; for (let col = 0; col < matrix[row].length; col++) { newRow.push(matrix[row][col]); } newMatrix.push(newRow); } return newMatrix; } function rotateBorder(newMatrix, matrix, minRow, minCol, maxRow, maxCol) { if (minRow >= maxRow && minCol >= maxCol) { return; } // top let row = minRow; for (let col = minCol; col <= maxCol; col++) { const value = newMatrix[minRow][col]; matrix[row][maxCol] = value; row++; } // right let col = maxCol; for (let row = minRow; row <= maxRow; row++) { const value = newMatrix[row][maxCol]; matrix[maxRow][col] = value; col--; } // bottom row = minRow; for (let col = minCol; col <= maxCol; col++) { const value = newMatrix[maxRow][col]; matrix[row][minCol] = value; row++; } // left col = maxCol; for (let row = minRow; row <= maxRow; row++) { const value = newMatrix[row][minCol]; matrix[minRow][col] = value; col--; } rotateBorder( newMatrix, matrix, minRow + 1, minCol + 1, maxRow - 1, maxCol - 1 ); } function rotate(matrix) { const newMatrix = setupMatrix(matrix); const minRow = 0; const minCol = 0; const maxRow = matrix.length - 1; const maxCol = matrix[0].length - 1; rotateBorder(newMatrix, matrix, minRow, minCol, maxRow, maxCol); } ================================================ FILE: coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.js ================================================ function getMiddle(start, end) { return Math.floor((start + end) / 2); } function binarySearch(list, target) { let start = 0; let end = list.length - 1; let middle = getMiddle(start, end); while (start <= end) { if (list[middle] === target) { return true; } else if (list[middle] > target) { end = middle - 1; middle = getMiddle(start, end); } else { start = middle + 1; middle = getMiddle(start, end); } } return false; } function searchMatrix(matrix, target) { let targetRow; for (let rowIndex = 0; rowIndex < matrix.length; rowIndex++) { let rowFirstNum = matrix[rowIndex][0]; let rowLastNum = matrix[rowIndex][matrix[rowIndex].length - 1]; if (target >= rowFirstNum && target <= rowLastNum) { targetRow = rowIndex; } } return matrix[targetRow] ? binarySearch(matrix[targetRow], target) : false; } ================================================ FILE: coding_interviews/leetcode/medium/search-a-2d-matrix/search-a-2d-matrix.py ================================================ # https://leetcode.com/problems/search-a-2d-matrix ''' Runtime Complexity: O(logNM) Space Complexity: O(1) ''' def search_matrix(matrix, target): rows, columns = len(matrix), len(matrix[0]) start, end = 0, rows * columns - 1 while start <= end: middle = (start + end) // 2 number = matrix[middle // columns][middle % columns] if number == target: return True if target < number: end = middle - 1 else: start = middle + 1 return False ================================================ FILE: coding_interviews/leetcode/medium/search-a-2d-matrix-ii/search-a-2d-matrix-ii.py ================================================ # https://leetcode.com/problems/search-a-2d-matrix-ii ''' Runtime Complexity: O(NlogM), where N is the number of rows and M is the number of columns Space Complexity: O(1) ''' def search_matrix(matrix, target): for row in matrix: if target_in_row(row, target): return True return False def target_in_row(array, target): start, end = 0, len(array) - 1 while start <= end: middle = (start + end) // 2 number = array[middle] if number == target: return True if number > target: end = middle - 1 else: start = middle + 1 return False ================================================ FILE: coding_interviews/leetcode/medium/set-matrix-zeroes/set-matrix-zeroes.js ================================================ function updateRow(matrix, row, visited) { for (let col = 0; col < matrix[row].length; col++) { if (matrix[row][col]) { matrix[row][col] = 0; visited[`${row}-${col}`] = true; } } } function updateCol(matrix, col, visited) { for (let row = 0; row < matrix.length; row++) { if (matrix[row][col]) { matrix[row][col] = 0; visited[`${row}-${col}`] = true; } } } function setZeroes(matrix) { let visited = {}; for (let row = 0; row < matrix.length; row++) { for (let col = 0; col < matrix[row].length; col++) { let cell = matrix[row][col]; if (cell === 0 && !visited[`${row}-${col}`]) { if (!visited[`row-${row}`]) { updateRow(matrix, row, visited); } if (!visited[`col-${col}`]) { updateCol(matrix, col, visited); } visited[`row-${row}`] = true; visited[`col-${col}`] = true; } } } } ================================================ FILE: coding_interviews/leetcode/medium/sort-the-students-by-their-kth-score/sort-the-students-by-their-kth-score.js ================================================ function sortTheStudents(score, k) { let column = []; let sortedScores = []; for (let row = 0; row < score.length; row++) { column.push([row, score[row][k]]); } column.sort((pair1, pair2) => pair2[1] - pair1[1]); for (let [row] of column) { sortedScores.push(score[row]); } return sortedScores; } ================================================ FILE: coding_interviews/leetcode/medium/sort_the_matrix_diagonally/sort_the_matrix_diagonally.py ================================================ def diagonal_sort(mat): for column in range(len(mat[0]) - 1): diagonal_list = [] col = column for row in range(len(mat)): diagonal_list.append(mat[row][col]) col += 1 if col >= len(mat[0]): break diagonal_list = sorted(diagonal_list) col = column for row in range(len(mat)): mat[row][col] = diagonal_list[row] col += 1 if col >= len(mat[0]): break for row in range(1, len(mat)): diagonal_list = [] r = row for column in range(len(mat[0])): diagonal_list.append(mat[r][column]) r += 1 if r >= len(mat): break diagonal_list = sorted(diagonal_list) r = row for column in range(len(mat[0])): mat[r][column] = diagonal_list[column] r += 1 if r >= len(mat): break return mat ================================================ FILE: coding_interviews/leetcode/medium/string-compression/string-compression-copy.js ================================================ // https://leetcode.com/problems/string-compression function compress(chars) { let counter = 1; let result = []; for (let index = 0; index < chars.length - 1; index++) { if (chars[index] === chars[index + 1]) counter++; else { result.push(chars[index]); if (counter > 1) result.push(...counter.toString()); counter = 1; } if (index + 1 === chars.length - 1) { result.push(chars[index + 1]); if (counter > 1) result.push(...counter.toString()); } } return result.length; } ================================================ FILE: coding_interviews/leetcode/medium/string-compression/string-compression.js ================================================ // https://leetcode.com/problems/string-compression function compress(chars) { let index = 0, p1 = 0; while (p1 < chars.length) { let p2 = p1; while (p2 < chars.length && chars[p1] === chars[p2]) { p2++; } let count = p2 - p1; chars[index++] = chars[p1]; if (count > 1) { let countString = count.toString(); for (let char of countString) { chars[index++] = char; } } p1 = p2; } while (chars.length > index) { chars.pop(); } return chars.length; } ================================================ FILE: coding_interviews/leetcode/medium/subrectangle_queries/subrectangle_queries.py ================================================ # https://leetcode.com/problems/subrectangle-queries class SubrectangleQueries: def __init__(self, rectangle): self.rectangle = rectangle def updateSubrectangle(self, row1, col1, row2, col2, newValue): for row in range(row1, row2 + 1): for col in range(col1, col2 + 1): self.rectangle[row][col] = newValue def getValue(self, row, col): return self.rectangle[row][col] ================================================ FILE: coding_interviews/leetcode/medium/sum_of_nodes/sum_of_nodes.py ================================================ # https://leetcode.com/problems/sum-of-nodes-with-even-valued-grandparent ''' Given a binary tree, return the sum of values of nodes with even-valued grandparent. (A grandparent of a node is the parent of its parent, if it exists.) If there are no nodes with an even-valued grandparent, return 0. ''' def sum_even_grandparent(node): left = 0 right = 0 if node.left and node.left.left and node.val % 2 == 0: left += node.left.left.val if node.left and node.left.right and node.val % 2 == 0: left += node.left.right.val if node.left: left += sum_even_grandparent(node.left) if node.right and node.right.left and node.val % 2 == 0: right += node.right.left.val if node.right and node.right.right and node.val % 2 == 0: right += node.right.right.val if node.right: right += sum_even_grandparent(node.right) return right + left def sum_even_grandparent_2(node): return helper(node, 1, 1) def helper(node, parent, grandparent): if node is None: return 0 return helper(node.left, node.val, parent) \ + helper(node.right, node.val, parent) \ + (node.val if grandparent % 2 == 0 else 0) ================================================ FILE: coding_interviews/leetcode/medium/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted-2.js ================================================ function twoSum(numbers, target) { let start = 0; let end = numbers.length - 1; let result = []; while (start < end) { let sum = numbers[start] + numbers[end]; if (sum === target) { result.push(start + 1); result.push(end + 1); break; } if (sum > target) end--; else start++; } return result; } ================================================ FILE: coding_interviews/leetcode/medium/two-sum-ii-input-array-is-sorted/two-sum-ii-input-array-is-sorted.js ================================================ function twoSum(numbers, target) { let numberMap = {}; for (let index = 0; index < numbers.length; index++) { let number = numbers[index]; numberMap[number] = index + 1; } let index1; let index2; for (let index = 0; index < numbers.length; index++) { let remainder = target - numbers[index]; let remaindersIndex = numberMap[remainder]; if (remaindersIndex) { index1 = index + 1; index2 = remaindersIndex; return [index1, index2]; } } } ================================================ FILE: coding_interviews/leetcode/medium/valid-sudoku/valid-sudoku.js ================================================ function isValidRow(board, row) { let allNumbersInRow = new Set(); let countOfNumbersInRow = 0; for (let index = 0; index <= 8; index++) { let num = board[row][index]; if (num !== '.') { allNumbersInRow.add(num); countOfNumbersInRow++; } } return allNumbersInRow.size === countOfNumbersInRow; } function isValidCol(board, col) { let allNumbersInCol = new Set(); let countOfNumbersInCol = 0; for (let index = 0; index <= 8; index++) { let num = board[index][col]; if (num !== '.') { allNumbersInCol.add(num); countOfNumbersInCol++; } } return allNumbersInCol.size === countOfNumbersInCol; } function isValidSquare(board, row, col) { let allNumbersInSquare = new Set(); let countOfNumbersInSquare = 0; for (let rowIndex = row; rowIndex <= row + 2; rowIndex++) { for (let colIndex = col; colIndex <= col + 2; colIndex++) { let num = board[rowIndex][colIndex]; if (num !== '.') { allNumbersInSquare.add(num); countOfNumbersInSquare++; } } } return allNumbersInSquare.size === countOfNumbersInSquare; } function isValidSudoku(board) { let isValid = true; for (let row = 0; row <= 8; row++) { isValid = isValid && isValidRow(board, row); } for (let col = 0; col <= 8; col++) { isValid = isValid && isValidCol(board, col); } for (let col = 0; col <= 6; col += 3) { for (let row = 0; row <= 6; row += 3) { isValid = isValid && isValidSquare(board, row, col); } } return isValid; } ================================================ FILE: coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-2.js ================================================ function isValidBST(node, min = -Infinity, max = Infinity) { if (!node) return true; if (node.val <= min || node.val >= max) return false; return ( isValidBST(node.left, min, node.val) && isValidBST(node.right, node.val, max) ); } ================================================ FILE: coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree-almost-right.js ================================================ function isValidLeft(node, left) { return node.val > left.val; } function isValidRight(node, right) { return node.val < right.val; } function isValid(node, left, right) { return isValidLeft(node, left) && isValidRight(node, right); } function compareNodeAndChildren(node, left, right) { if (left && right) { return ( isValid(node, left, right) && compareNodeAndChildren(left, left.left, left.right) && compareNodeAndChildren(right, right.left, right.right) ); } if (left) { return ( isValidLeft(node, left) && compareNodeAndChildren(left, left.left, left.right) ); } if (right) { return ( isValidRight(node, right) && compareNodeAndChildren(right, right.left, right.right) ); } return true; } function isValidBST(root) { return compareNodeAndChildren(root, root.left, root.right); } ================================================ FILE: coding_interviews/leetcode/medium/validate-binary-search-tree/validate-binary-search-tree.js ================================================ function toList(node, treeList) { if (!node) { return; } treeList.push(node.val); toList(node.left, treeList); toList(node.right, treeList); } function dfs(node, value) { if (!node) { return new TreeNode(value); } if (value < node.val) { node.left = dfs(node.left, value); } else if (value > node.val) { node.right = dfs(node.right, value); } return node; } function buildTree(treeList) { let root = new TreeNode(treeList[0]); for (let value of treeList.slice(1)) { dfs(root, value); } return root; } function compareTrees(node1, node2) { if (!node1 && !node2) { return true; } if ((node1 && !node2) || (!node1 && node2)) { return false; } return ( node1.val === node2.val && compareTrees(node1.left, node2.left) && compareTrees(node1.right, node2.right) ); } function isValidBST(root) { let treeList = []; toList(root, treeList); let newTree = buildTree(treeList); return compareTrees(root, newTree); } ================================================ FILE: coding_interviews/leetcode/medium/watering-plants/tests/watering-plants.test.js ================================================ import { describe, expect, it } from 'vitest'; import { wateringPlants } from '../watering-plants'; describe('wateringPlants', () => { it('', () => { expect(wateringPlants([2, 2, 3, 3], 5)).toEqual(14); }); it('', () => { expect(wateringPlants([1, 1, 1, 4, 2, 3], 4)).toEqual(30); }); it('', () => { expect(wateringPlants([7, 7, 7, 7, 7, 7, 7], 8)).toEqual(49); }); it('', () => { expect(wateringPlants([2, 1], 2)).toEqual(4); }); it('', () => { expect(wateringPlants([3, 2, 4, 2, 1], 6)).toEqual(17); }); }); ================================================ FILE: coding_interviews/leetcode/medium/watering-plants/watering-plants.js ================================================ /* You want to water n plants in your garden with a watering can. The plants are arranged in a row and are labeled from 0 to n - 1 from left to right where the ith plant is located at x = i. There is a river at x = -1 that you can refill your watering can at. Each plant needs a specific amount of water. You will water the plants in the following way: Water the plants in order from left to right. After watering the current plant, if you do not have enough water to completely water the next plant, return to the river to fully refill the watering can. You cannot refill the watering can early. You are initially at the river (i.e., x = -1). It takes one step to move one unit on the x-axis. Given a 0-indexed integer array plants of n integers, where plants[i] is the amount of water the ith plant needs, and an integer capacity representing the watering can capacity, return the number of steps needed to water all the plants. Example 1: Input: plants = [2,2,3,3], capacity = 5 Output: 14 Example 2: Input: plants = [1,1,1,4,2,3], capacity = 4 Output: 30 Example 3: Input: plants = [7,7,7,7,7,7,7], capacity = 8 Output: 49 */ // [2, 2, 3, 3] // capacity: 5 -> 3 -> 1 // steps: 1 -> 2 -> 4 export function wateringPlants(plants, capacity) { let steps = 0; const CAPACITY = capacity; for (let i = 0; i < plants.length; i++) { steps++; capacity -= plants[i]; if (i < plants.length - 1 && capacity < plants[i + 1]) { steps += i + 1; steps += i + 1; capacity = CAPACITY; } } return steps; } ================================================ FILE: coding_interviews/python/string.py ================================================ # length of a string len('a string') # 8 # concatenate strings s1 = 'string 1' s2 = 'string 2' s3 = s1 + s2 # 'string 1string 2' # indexing s1 = 'string 1' s1[3] # 'i' # slicing s1 = 'string 1' s1[:3] # 'str' s1[2:] # 'ring 1' # striping a string s = ' a string ' s.strip() # 'a string' # string in string s1 = 'string 1' s2 = 'string' s3 = 'other' s2 in s1 # True s3 in s1 # False ================================================ FILE: coding_interviews/top-problems/are-anagrams.js ================================================ // Time Complexity: O(N) where N is the size of the string // more precisely, it should be O(N1) + O(N2) where N1 = length of string1 and N2 = length of string2 // Space Complexity: O(N) where N is the size of the string function hasDifferentLengths(string1, string2) { return string1.length !== string2.length; } function buildCharsCount(string) { let charactersCounter = {}; for (let char of string) { if (charactersCounter[char]) { charactersCounter[char]++; } else { charactersCounter[char] = 1; } } return charactersCounter; } export function areAnagrams(string1, string2) { if (hasDifferentLengths(string1, string2)) return false; let charactersCounter1 = buildCharsCount(string1); let charactersCounter2 = buildCharsCount(string2); for (let char of Object.keys(charactersCounter1)) { if (charactersCounter1[char] !== charactersCounter2[char]) { return false; } } return true; } ================================================ FILE: coding_interviews/top-problems/first-and-last-index.js ================================================ /* Given a sorted array of integers `arr` and an integer target, find the index of the first and last position of target in `arr`. In target can't be found in `arr`, return [-1, -1] */ // Runtime: O(N) // Space: O(1) export function firstAndLastIndex(list, target) { let first = -1; let last = -1; for (let index = 0; index < list.length; index++) { if (list[index] === target) { first = index; break; } } for (let index = list.length; index >= 0; index--) { if (list[index] === target) { last = index; break; } } return [first, last]; } // Runtime: O(logN) // Space: O(1) function getMiddle(start, end) { return Math.floor((start + end) / 2); } function findIndex(list, target, type) { let start = 0; let end = list.length - 1; let middle = getMiddle(start, end); let index = -1; while (start <= end) { if (target > list[middle]) { start = middle + 1; middle = getMiddle(start, end); } if (target < list[middle]) { end = middle - 1; middle = getMiddle(start, end); } if (target === list[middle]) { index = middle; if (type === 'findFirst') { end = middle - 1; } if (type === 'findLast') { start = middle + 1; } middle = getMiddle(start, end); } } return index; } function findFirstIndex(list, target) { return findIndex(list, target, 'findFirst'); } function findLastIndex(list, target) { return findIndex(list, target, 'findLast'); } export function firstAndLastIndexBinarySearch(list, target) { return [findFirstIndex(list, target), findLastIndex(list, target)]; } ================================================ FILE: coding_interviews/top-problems/kth-largest.js ================================================ // Given an array of integers `arr` and an integer `k`, find the kth largest element // Runtime: O(NlogN) // Space: O(1) export function kthLargest(list, k) { return list.sort((num1, num2) => num1 - num2)[list.length - k]; } ================================================ FILE: coding_interviews/top-problems/min-sliding-window.js ================================================ function buildCharsCounter(s) { let charsCounter = {}; for (let char of s) { if (charsCounter[char]) { charsCounter[char]++; } else { charsCounter[char] = 1; } } return charsCounter; } function compare(s1, s2) { let chars1 = buildCharsCounter(s1); let chars2 = buildCharsCounter(s2); for (let [char, counter] of Object.entries(chars1)) { if (chars2[char] == undefined || chars2[char] > counter) { return false; } } return true; } function minSlidingWindow(s, t) { for (let i = 0; i < s.length - t.length; i++) { for (let j = i + t.length; j < s.length; j++) { const substring = s.slice(i, j); } } } minSlidingWindow('adcfebeceabebadfcdfcbfcbead', 'abca'); ================================================ FILE: coding_interviews/top-problems/tests/are-anagrams.test.js ================================================ import { describe, expect, it } from 'vitest'; import { areAnagrams } from '../are-anagrams'; describe('areAnagrams', () => { it('', () => { expect(areAnagrams('', '')).toBeTruthy(); }); it('', () => { expect(areAnagrams('a', 'a')).toBeTruthy(); }); it('', () => { expect(areAnagrams('bla', 'alb')).toBeTruthy(); }); it('', () => { expect(areAnagrams('hahahehe', 'hehehaha')).toBeTruthy(); }); it('', () => { expect(areAnagrams('a', 'b')).toBeFalsy(); }); it('', () => { expect(areAnagrams('aa', 'a')).toBeFalsy(); }); it('', () => { expect(areAnagrams('bla', 'elb')).toBeFalsy(); }); it('', () => { expect(areAnagrams(' ', ' ')).toBeFalsy(); }); }); ================================================ FILE: coding_interviews/top-problems/tests/first-and-last-index.test.js ================================================ import { describe, expect, it } from 'vitest'; import { firstAndLastIndex, firstAndLastIndexBinarySearch, } from '../first-and-last-index'; describe('firstAndLastIndex', () => { it('', () => { expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 5)).toEqual([ 5, 7, ]); }); it('', () => { expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 4)).toEqual([ 4, 4, ]); }); it('', () => { expect(firstAndLastIndex([1, 1, 2, 3, 4, 5, 5, 5, 6, 8, 9], 7)).toEqual([ -1, -1, ]); }); }); describe('firstAndLastIndexBinarySearch', () => { it('', () => { expect( firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 5) ).toEqual([5, 7]); }); it('', () => { expect( firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 7, 8, 9], 4) ).toEqual([4, 4]); }); it('', () => { expect( firstAndLastIndexBinarySearch([1, 1, 2, 3, 4, 5, 5, 5, 6, 8, 9], 7) ).toEqual([-1, -1]); }); }); ================================================ FILE: coding_interviews/top-problems/tests/kth-largest.test.js ================================================ import { describe, expect, it } from 'vitest'; import { kthLargest } from '../kth-largest'; describe('kthLargest', () => { it('', () => { expect(kthLargest([4, 2, 9, 7, 5, 6, 7, 1, 3], 4)).toEqual(6); }); }); ================================================ FILE: college/graph/atoms.py ================================================ import networkx as nx import matplotlib.pyplot as plt def plot_graph(graph, pos, title): plt.figure(figsize=(6, 6)) nx.draw(graph, pos, with_labels=True, node_color='lightblue', node_size=2000, font_size=12, font_weight='bold', edge_color='gray') plt.title(title) plt.show() # H₂O # Adiciona vértices e conectas os átomos com arestas # Define as posições de cada átomo # Plota o grafo de água water = nx.Graph() water.add_nodes_from(['O', 'H1', 'H2']) water.add_edges_from([('O', 'H1'), ('O', 'H2')]) water_pos = {'O': (0, 0), 'H1': (-1, -1), 'H2': (1, -1)} plot_graph(water, water_pos, '(H2O)') # CO₂ # Adiciona vértices e conectas os átomos com arestas # Define as posições de cada átomo # Plota o grafo de CO₂ co2 = nx.Graph() co2.add_nodes_from(['C', 'O1', 'O2']) co2.add_edges_from([('C', 'O1'), ('C', 'O2')]) co2_pos = {'C': (0, 0), 'O1': (-1, 0), 'O2': (1, 0)} plot_graph(co2, co2_pos, '(CO2)') ================================================ FILE: college/web/css/estilos.css ================================================ body { background-color: #f7f9ac; } h1 { color: green; text-align: center; } p.corpoDoTexto { color: blue; } p.corpoDoTexto2 { color: red; } ================================================ FILE: college/web/css/index.html ================================================ CSS

Título título título

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

================================================ FILE: college/web/index.html ================================================ Título da página

Título Principal - H1

Sub-título H2

Sub-título H3

Sub-título H4

Sub-título H5
Sub-título H6

Testando o parágrafo

================================================ FILE: college/web/js.js ================================================ Math.max(1, 2); // 2 Math.min(1, 2); // 1 Math.pow(2, 2); // 4 Math.sqrt(4); // 2 ================================================ FILE: college/web/loop.js ================================================ let matrix = []; for (let row = 1; row <= 4; row++) { let nums = []; let num = row + 1; for (let col = 1; col <= 5; col++) { nums.push(num); num += row + 1; } matrix.push(nums); } console.log(matrix); ================================================ FILE: competitive-programming/4clojure/problem01.clj ================================================ ; http://www.4clojure.com/problem/1 (= true true) ================================================ FILE: competitive-programming/4clojure/problem02.clj ================================================ ; http://www.4clojure.com/problem/2 (= (- 10 (* 2 3)) 4) ================================================ FILE: competitive-programming/4clojure/problem03.clj ================================================ ; http://www.4clojure.com/problem/3#prob-title (= "HELLO WORLD" (.toUpperCase "hello world")) ================================================ FILE: competitive-programming/4clojure/problem04.clj ================================================ ;; http://www.4clojure.com/problem/4 (= (list :a :b :c) '(:a :b :c)) ================================================ FILE: competitive-programming/4clojure/problem05.clj ================================================ ;; http://www.4clojure.com/problem/5#prob-title (= '(1 2 3 4) (conj '(2 3 4) 1)) (= '(1 2 3 4) (conj '(3 4) 2 1)) ================================================ FILE: competitive-programming/4clojure/problem06.clj ================================================ ;; http://www.4clojure.com/problem/6 (= [:a :b :c] (list :a :b :c) (vec '(:a :b :c)) (vector :a :b :c)) ================================================ FILE: competitive-programming/4clojure/problem07.clj ================================================ ;; http://www.4clojure.com/problem/7 (= [1 2 3 4] (conj [1 2 3] 4)) (= [1 2 3 4] (conj [1 2] 3 4)) ================================================ FILE: competitive-programming/4clojure/problem19.clj ================================================ ; http://www.4clojure.com/problem/19 ; Solution 1 (fn [coll] (loop [item (first coll) coll coll] (if (empty? (rest coll)) item (recur (first (rest coll)) (rest coll))))) ; Solution 2 (fn [coll] (first (reverse coll))) ; Solution 3 #(first (reverse %)) ; Solution 4 (comp first reverse) ; Solution 5 (fn [coll] (-> coll reverse first)) ; Solution 6 (fn [coll] (loop [[item & remaining] coll] (if (empty? remaining) item (recur remaining)))) ================================================ FILE: competitive-programming/4clojure/problem20.clj ================================================ ; http://www.4clojure.com/problem/20 (comp second reverse) ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/armstrong.cpp ================================================ #include #include #include #include #include using namespace std; int main() { long int n; scanf("%li", &n); vector vetor; while (n != 0) { int total = 0, temp = n, teste, result=0; while (temp != 0) { teste = temp % 10; vetor.push_back(teste); temp = temp / 10; } for (int i = 2; i < 10; i++) { total = 0; for (int j = 0; j < vetor.size(); j++) { total += pow(vetor[j], i); } if (total == n) { result = i; break; } } if (result) cout << result << endl; else cout << "N" << endl; scanf("%li", &n); vetor.clear(); } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/calculadora.cpp ================================================ #include #include using namespace std; int main() { int ip1[4]; int ip2[4]; int mas[4]; while (scanf("%i.%i.%i.%i %i.%i.%i.%i %i.%i.%i.%i", &ip1[0],&ip1[1],&ip1[2],&ip1[3],&ip2[0],&ip2[1],&ip2[2],&ip2[3],&mas[0],&mas[1],&mas[2],&mas[3]) != -1) { int r = 1; int i = 0; for (i = 0; i < 4; i++) { if ((ip1[i] & mas[i]) != (ip2[i] & mas[i])) r = 0; } if (r) cout << "S" << endl; else cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/cartoes.cpp ================================================ #include #include using namespace std; int is_alberto_turn(int counter) { if (counter % 2 == 0) return 1; return 0; } int main() { int n, temp; vector v, vetor_a; cin >> n; for (int i = 0; i < n; i++) { cin >> temp; v.push_back(temp); } for (int i = 0; i < n; i++) { if (is_alberto_turn(i)) { if (v[0] > v.back()) { vetor_a.push_back(v[0]); v.erase(v.begin()); } else { vetor_a.push_back(v.back()); v.pop_back(); } } else if (v.size() > 1) { if (v[0] > v.back()) v.erase(v.begin()); else v.pop_back(); } } int total = 0; for (int i = 0; i < n; i++) total += vetor_a[i]; cout << total << endl; return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/concurso.cpp ================================================ #include #include #include using namespace std; int main() { int n, l, c, result; string conto; while (scanf("%d %d %d", &n, &l, &c) != EOF) { cin.ignore(); getline(cin, conto); if (conto.size() == (l * c)) result = 1; else result = (conto.size() / (l * c)) + 1; cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/coral.cpp ================================================ #include #include #include #include #include using namespace std; bool is_integer(float k) { return std::floor(k) == k; } bool all_equal(vector &vetorzin) { sort(vetorzin.begin(), vetorzin.end()); return (vetorzin[0] == vetorzin.back()); } int main() { int n, temp; float total=0; vector v; cin >> n; for (int i = 0; i < n; i++) { cin >> temp; total += temp; v.push_back(temp); } if (is_integer(total / n)) cout << -1 << endl; else { if (all_equal(v)) cout << 1 << endl; else { // algorithm to know how many times } } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/elevador.cpp ================================================ #include #include #include #include #include using namespace std; bool has_four(string number) { for (int i = 0; i < number.length(); i++) if (number[i] == '4') return true; return false; } bool has_thirteen(string number) { for (int i = 0; i < number.length()-1; i++) if (number[i] == '1' && number[i+1] == '3') return true; return false; } int main () { int n, total=0; while (scanf("%d", &n) != EOF) { ostringstream converter; converter << n; string number = converter.str(); for (int i = 0; i < n; i++) { if (has_four(number) || has_thirteen(number)) total++; cout << total << endl; } cout << n + total << endl; total = 0; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/estacionamento.cpp ================================================ #include #include using namespace std; int main() { int v, p, result=0; cin >> v >> p; while (v + p != 0) { vector v1; vector< vector > v2; while (p--) { int he, me, hs, ms, found=0; cin >> he >> me >> hs >> ms; v1.push_back(he); v1.push_back(me); v1.push_back(hs); v1.push_back(ms); if (v > 0) { v2.push_back(v1); v--; } else { for (int i = 0; i < v2.size(); i++) { if (v1[0] > v2[i][2] || (v1[0] == v2[i][2] && v1[1] > v2[i][3])) { v2.push_back(v1); found = 1; break; } } if (!found) result++; } v1.clear(); } cout << result << endl; cin >> v >> p; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/extenso.cpp ================================================ #include #include #include #include using namespace std; // stringstream ss; // string num1; // ss << n1[0]; // ss >> num1; void split(string &n1, string &n2, string number) { int dot_index = number.find("."); n1 = number.substr(0, dot_index); n2 = number.substr(dot_index+1, number.size()-1); } string transformNumberToCents(string cents) { string result=""; string ar[] = { "DEZ", "ONZE", "DOZE", "TREZE", "QUATORZE", "QUINZE", "DEZESSEIS", "DEZESSETE", "DEZOITO", "DEZENOVE" }; string um_a_nove[] = { "UM", "DOIS", "TRES", "QUATRO", "CINCO", "SEIS", "SETE", "OITO", "NOVE" }; vector values(ar, ar + sizeof(ar)/sizeof(ar[0])); vector sec_values(um_a_nove, um_a_nove + sizeof(um_a_nove)/sizeof(um_a_nove[0])); stringstream ss; string num1; ss << cents[0]; ss >> num1; int cent_unit = stoi(num1); if (cents[0] == '0') result += sec_values[cent_unit-1]; else if (cents[0] == '1') result += values[cent_unit]; else if (cents[0] == '2') result += "VINTE E " + sec_values[cent_unit-1]; else if (cents[0] == '3') result += "TRINTA E " + sec_values[cent_unit-1]; else if (cents[0] == '4') result += "QUARENTA E " + sec_values[cent_unit-1]; else if (cents[0] == '5') result += "CINQUENTA E " + sec_values[cent_unit-1]; else if (cents[0] == '6') result += "SESSENTA E " + sec_values[cent_unit-1]; else if (cents[0] == '7') result += "SETENTA E " + sec_values[cent_unit-1]; else if (cents[0] == '8') result += "OITENTA E " + sec_values[cent_unit-1]; else if (cents[0] == '9') result += "NOVENTA E " + sec_values[cent_unit-1]; return result; } string transformNumberToReal(string reais) { string result=""; string um_a_nove[] = { "UM", "DOIS", "TRES", "QUATRO", "CINCO", "SEIS", "SETE", "OITO", "NOVE" }; vector sec_values(um_a_nove, um_a_nove + sizeof(um_a_nove)/sizeof(um_a_nove[0])); string ar[] = { "DEZ", "ONZE", "DOZE", "TREZE", "QUATORZE", "QUINZE", "DEZESSEIS", "DEZESSETE", "DEZOITO", "DEZENOVE" }; vector values(ar, ar + sizeof(ar)/sizeof(ar[0])); string dez_a_noventa[] = { "VINTE", "TRINTA", "QUARENTA", "CINQUENTA", "SESSENTA", "SETENTA", "OITENTA", "NOVENTA" }; vector dicker(dez_a_noventa, dez_a_noventa + sizeof(dez_a_noventa)/sizeof(dez_a_noventa[0])); string cem_a_novecentos[] = { "CENTO", "DUZENTOS", "TREZENTOS", "QUATROCENTOS", "QUINHENTOS", "SEICENTOS", "SETECENTOS", "OITOCENTOS", "NOVECENTOS" }; vector hundred(cem_a_novecentos, cem_a_novecentos + sizeof(cem_a_novecentos)/sizeof(cem_a_novecentos[0])); if (reais.size() == 1) { result += sec_values[stoi(reais)-1]; } else if (reais.size() == 2) { stringstream ss; string n1, n2; ss << reais[0]; ss >> n1; ss << reais[1]; ss >> n2; if (reais[0] == '1') { result += values[stoi(n2)]; } else { result += dicker[stoi(n1)-1] + " E " + sec_values[stoi(n2)-1]; } } else if (reais.size() == 3) { stringstream ss; string n1, n2, n3; ss << reais[0]; ss >> n1; ss << reais[1]; ss >> n2; ss << reais[2]; ss >> n3; result += hundred[stoi(n1)-1] + " E " + dicker[stoi(n2)-1] + " E " + sec_values[stoi(n3)-1]; } else if (reais.size() == 4){ stringstream ss; string n1, n2, n3, n4; ss << reais[0]; ss >> n1; ss << reais[1]; ss >> n2; ss << reais[2]; ss >> n3; ss << reais[3]; ss >> n4; result += sec_values[stoi(n1)-1] + " MIL E " + hundred[stoi(n2)-1] + " E " + dicker[stoi(n3)-1] + " E " + sec_values[stoi(n4)-1]; } else if (reais.size() == 5) { stringstream ss; string n1, n2, n3, n4, n5; ss << reais[0]; ss >> n1; ss << reais[1]; ss >> n2; ss << reais[2]; ss >> n3; ss << reais[3]; ss >> n4; ss << reais[4]; ss >> n5; if (reais[0] == '1') { result += values[stoi(n2)] + " MIL E " + hundred[stoi(n3)-1] + " E " + dicker[stoi(n4)-1] + " E " + sec_values[stoi(n5)-1]; } else { result += dicker[stoi(n1)-1] + " E " + sec_values[stoi(n2)-1]; + " MIL E " + hundred[stoi(n3)-1] + " E " + dicker[stoi(n4)-1] + " E " + sec_values[stoi(n5)-1]; } } else if (reais.size() == 6) { stringstream ss; string n1, n2, n3, n4, n5, n6; ss << reais[0]; ss >> n1; ss << reais[1]; ss >> n2; ss << reais[2]; ss >> n3; ss << reais[3]; ss >> n4; ss << reais[4]; ss >> n5; ss << reais[5]; ss >> n6; result += hundred[stoi(n1)-1] + " E " + dicker[stoi(n2)-1] + " E " + sec_values[stoi(n3)-1] + " MIL E" + hundred[stoi(n4)-1] + " E " + dicker[stoi(n5)-1] + " E " + sec_values[stoi(n6)-1]; } else { result += "UM MILHAO"; } return result; } int main() { string number; cin >> number; while(number != "0.00") { string n1, n2, result=""; split(n1, n2, number); n1 = transformNumberToReal(n1); n2 = transformNumberToCents(n2); if (n1 == "0") { if (n2 == "01") result += n2 + " CENTAVO"; else result += n2 + " CENTAVOS"; } else if (n1 == "1") { if (n2 == "00") result += n1 + " REAL"; else if (n2 == "01") result += n1 + " REAL E " + n2 + " CENTAVO"; else result += n1 + " REAL E " + n2 + " CENTAVOS"; } else { if (n2 == "00") result += n1 + " REAIS"; else if (n2 == "01") result += n1 + " REAIS E " + n2 + " CENTAVO"; else result += n1 + " REAIS E " + n2 + " CENTAVOS"; } cout << result; cin >> number; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/goldbach.cpp ================================================ #include #include #include using namespace std; int verifica_primo(int n) { int total_divisivel = 0; if (n == 2) { return 1; } if ((n % 2) == 0) return 0; int s = sqrt(n); for (int i = 3; i <= s; i += 2) { if (n % i == 0){ return 0; } } return 1; } int main() { int n, n1, n2; scanf("%i", &n); while (n != 0) { if (n % 2 != 0) cout << "erro" << endl; else { for (int i = 2; i <= n; i++) { if (verifica_primo(i)) { n1 = i; if (verifica_primo(n-n1)) { n2 = n - n1; break; } } } cout << n1 << " " << n2 << endl; } scanf("%i", &n); } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/matriz_esparsa.cpp ================================================ #include using namespace std; int main() { int n, x, total, zeros, medium; cin >> n; while (n--) { cin >> x; total = x * x; zeros = total - (3 * x - 2); medium = total / 2; if (zeros > medium) cout << "S " << zeros << endl; else cout << "N " << zeros << endl; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/pascal.cpp ================================================ #include using namespace std; int triangulo_pascal(int n, int m) { if ((m == 0 || n == 0) || (m == 1 && n == 1) || (m == n)) return 1; return triangulo_pascal(n - 1, m) + triangulo_pascal(n - 1, m - 1); } int main() { int n, x, y; cin >> n; while (n--) { cin >> x; cin >> y; cout << triangulo_pascal(x, y) << endl; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/polinomio.cpp ================================================ #include #include #include #include #include using namespace std; int solvePartEquation(string part_equation, int value) { int result, inicio=0, constante, expo; int x = part_equation.find("x"); stringstream ss1; ss1 << part_equation.substr(0, x); ss1 >> constante; stringstream ss2; ss2 << part_equation.substr(x+1, part_equation.size()-x); ss2 >> expo; result = constante * (pow(value, expo)); return result; } int main() { int n, time=1, i_inicio=0, total; string temp; vector vetor_de_valores, vetor_de_variaveis, vetor_de_sinais; vector vetor_de_resultados; cin >> n; while (n--) { string equacao; int number_of_values; cin >> equacao; cin >> number_of_values; for (int i = 0; i < number_of_values; i++){ cin >> temp; vetor_de_valores.push_back(temp); } for (int i = 0; i < equacao.size(); i++) { if (equacao[i] == '+' || equacao[i] == '-') { vetor_de_variaveis.push_back(equacao.substr(i_inicio, i-i_inicio)); vetor_de_sinais.push_back(equacao.substr(i, 1)); i_inicio = i+1; } } for (int i = 0; i < vetor_de_valores.size(); i++) { int valor; stringstream ss; ss << vetor_de_valores[i]; ss >> valor; total = solvePartEquation(vetor_de_variaveis[0], valor); for (int j = 1; j < vetor_de_variaveis.size(); j++){ if (vetor_de_sinais[j-1] == "+") total += solvePartEquation(vetor_de_variaveis[j], valor); else total -= solvePartEquation(vetor_de_variaveis[j], valor); vetor_de_resultados.push_back(total); } } cout << "Caso " << time << ": "; for (int i = 0; vetor_de_resultados.size(); i++) cout << vetor_de_resultados[i] << " "; cout << endl; time++; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/quadrado.cpp ================================================ #include #include #include using namespace std; int main() { int n; vector v; cin >> n; while (n--) { int temp; for (int i = 0; i < 4; i++) { cin >> temp; v.push_back(temp); } sort(v); if (v[0] == v[1] && v[0] == v[2] && v[0] == v[3]) cout << "quadrado" << endl; else if (v[0] == v[1] && v[2] == v[3]) cout << "retangulo" << endl; else if (v[0] + v[1] + v[2] > v[3]) cout << "quadrilatero" << endl; else cout << "invalido" << endl; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2011/vagas.cpp ================================================ #include using namespace std; int main() { int c, total; cin >> c; while (c != -1) { total = (c - 6) / 5; cout << total << endl; cin >> c; } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2017_1/A.cpp ================================================ #include using namespace std; #define MAX_SIZE (1 << 20) int segtree[MAX_SIZE]; int lazy[MAX_SIZE]; void build_segtree(int A[], int node, int start, int end) { if (start == end) { segtree[node] = A[start]; } else { int middle = (start + end) / 2; build_segtree(A, node * 2, start, middle); build_segtree(A, node * 2 + 1, middle + 1, end); } } void propagate(int p, int start, int end) { if (lazy[p] != 0) { segtree[p] += lazy[p]; if (start != end) { lazy[p * 2] += lazy[p]; lazy[p * 2 + 1] += lazy[p]; } lazy[p] = 0; } } void lazy_update(int p, int start, int end, int left, int right, int inc) { propagate(p, start, end); if (start > end || end < left || start > right) return; // Totally out of range if (start >= left && end <= right) { // Totally in the range segtree[p] += inc; if (start != end) { // Not a leaf lazy[p * 2] += inc; lazy[p * 2 + 1] += inc; } return; } // Partially in the range int middle = (start + end) / 2; lazy_update(p * 2, start, middle, left, right, inc); lazy_update(p * 2 + 1, middle + 1, end, left, right, inc); } int lazy_query(int p, int start, int end, int left, int right) { if (start > end || left > end || right < start) return -1; propagate(p, start, end); if (start >= left && end <= right) return segtree[p]; int middle = (end + start) / 2; int left_f = lazy_query(p * 2, start, middle, left, right); int right_f = lazy_query(p * 2 + 1, middle + 1, end, left, right); } void print_all_leaves(int p, int start, int end) { if (start > end) return; propagate(p, start, end); if (start == end) cout << segtree[p] << endl; int middle = (start + end) / 2; print_all_leaves(p * 2, start, middle); print_all_leaves(p * 2 + 1, middle + 1, end); } int main() { int N, C, left, right, most_frequent; cin >> N >> C; int A[N]; for (int i = 0; i < N; i++) A[i] = 1; build_segtree(A, 1, 0, N - 1); while (C--) { cin >> left >> right; most_frequent = lazy_query(1, 0, N - 1, left, right); lazy_update(1, 0, N - 1, left, right, most_frequent); } //print_all_leaves(1, 0, N - 1); return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2017_2/D.cpp ================================================ #include using namespace std; bool is_prime(int N) { return true; } int main() { int N; cin >> N; if (is_prime(N)) { cout << 0 << endl; } else { } return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2017_2/F.cpp ================================================ #include #include #include using namespace std; int main() { int N, M, num; vector V; cin >> N >> M; while (N--) { cin >> num; V.push_back(num); } sort(V.begin(), V.end(), greater()); int result = M; for (int i = M; i < V.size(); i++) { if (V[i] == V[i-1]) result++; else break; } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2017_2/J.py ================================================ n = input() print n % 3 ================================================ FILE: competitive-programming/acm-icpc-br/regionals_2017_2/M.cpp ================================================ #include using namespace std; int main() { int N1, N2, N3; cin >> N1 >> N2 >> N3; int one = N2 * 2 + N3 * 4, two = N1 * 2 + N3 * 2, three = N1 * 4 + N2 * 2; if (one <= two && one <= three) cout << one << endl; else if (two <= three) cout << two << endl; else cout << three << endl; return 0; } ================================================ FILE: competitive-programming/codeforces/div2/black_square.cpp ================================================ // http://codeforces.com/problemset/problem/828/B #include #include #include using namespace std; int main() { int N, M, black = 0, smaller_black_x = 101, smaller_black_y = 101, bigger_black_x = -1, bigger_black_y = -1, result_square, bigger_side; vector matrix; string line; cin >> N >> M; cin.ignore(); for (int i = 0; i < N; i++) { getline(cin, line); matrix.push_back(line); } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (matrix[i][j] == 'B') { if (i < smaller_black_y) smaller_black_y = i; if (i > bigger_black_y) bigger_black_y = i; if (j < smaller_black_x) smaller_black_x = j; if (j > bigger_black_x) bigger_black_x = j; black++; } } } if (black == 0) { cout << 1 << endl; return 0; } bigger_side = max(bigger_black_x - smaller_black_x + 1, bigger_black_y - smaller_black_y + 1); if (bigger_side > N || bigger_side > M) cout << -1 << endl; else cout << bigger_side * bigger_side - black << endl; return 0; } ================================================ FILE: competitive-programming/codeforces/div2/karen_and_morning.cpp ================================================ // http://codeforces.com/contest/816/problem/A #include #include using namespace std; int to_digit(char c) { return c - '0'; } int main() { string hour; cin >> hour; int hour_decimal = to_digit(hour[0]), hour_unit = to_digit(hour[1]), minute_decimal = to_digit(hour[3]), minute_unit = to_digit(hour[4]), hour_int, minute; hour_int = hour_decimal * 10 + hour_unit; minute = minute_decimal * 10 + minute_unit; if (hour_int == minute_unit * 10 + minute_decimal) cout << 0 << endl; else if (hour_int == 1 && minute < 10) cout << 10 - minute << endl; else if ((hour_int == 0 ||hour_int == 1 || hour_int == 2 || hour_int == 3 || hour_int == 4 || hour_int == 5 || hour_int == 10 || hour_int == 11 || hour_int == 12 || hour_int == 13 || hour_int == 14 || hour_int == 15 || hour_int == 20 || hour_int == 21 || hour_int == 22 || hour_int == 23) && minute > 10) cout << 70 - minute << endl; else if ((hour_int == 0 ||hour_int == 1 || hour_int == 2 || hour_int == 3 || hour_int == 4 || hour_int == 10 || hour_int == 11 || hour_int == 12 || hour_int == 13 || hour_int == 14 || hour_int == 20 || hour_int == 21 || hour_int == 22 || hour_int == 23) && minute > 10) return 0; } ================================================ FILE: competitive-programming/codeforces/div2/keyboard_layouts.cpp ================================================ // http://codeforces.com/problemset/problem/831/B #include #include using namespace std; bool is_uppercase(char word) { string original_alphabet = "ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz"; return original_alphabet.find(word) < 26; } char build_new_word(char letter, string alpha1, string alpha2) { string original_alphabet = "ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz", numbers = "0123456789"; if (numbers.find(letter) >= 0 && numbers.find(letter) <= 9) return letter; else if (is_uppercase(letter)) { char l = original_alphabet[original_alphabet.find(letter) + 26]; int index = alpha1.find(l); char new_l = alpha2[index]; return original_alphabet[original_alphabet.find(new_l) - 26]; } return alpha2[alpha1.find(letter)]; } int main() { string alpha1, alpha2, word, result; cin >> alpha1 >> alpha2 >> word; for (int i = 0; i < word.size(); i++) { result += build_new_word(word[i], alpha1, alpha2); } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/codeforces/div2/the_child_and_the_homework.cpp ================================================ // http://codeforces.com/contest/437/problem/A #include using namespace std; string solve(string a, string b, string c, string d) { bool a_smaller = (a.size()-2 <= (b.size()-2) / 2) && (a.size()-2 <= (c.size()-2) / 2) && (a.size()-2 <= (d.size()-2) / 2), a_bigger = (a.size()-2 >= (b.size()-2) * 2) && (a.size()-2 >= (c.size()-2) * 2) && (a.size()-2 >= (d.size()-2) * 2), b_smaller = (b.size()-2 <= (a.size()-2) / 2) && (b.size()-2 <= (c.size()-2) / 2) && (b.size()-2 <= (d.size()-2) / 2), b_bigger = (b.size()-2 >= (a.size()-2) * 2) && (b.size()-2 >= (c.size()-2) * 2) && (b.size()-2 >= (d.size()-2) * 2), c_smaller = (c.size()-2 <= (a.size()-2) / 2) && (c.size()-2 <= (b.size()-2) / 2) && (c.size()-2 <= (d.size()-2) / 2), c_bigger = (c.size()-2 >= (a.size()-2) * 2) && (c.size()-2 >= (b.size()-2) * 2) && (c.size()-2 >= (d.size()-2) * 2), d_smaller = (d.size()-2 <= (a.size()-2) / 2) && (d.size()-2 <= (b.size()-2) / 2) && (d.size()-2 <= (c.size()-2) / 2), d_bigger = (d.size()-2 >= (b.size()-2) * 2) && (d.size()-2 >= (a.size()-2) * 2) && (d.size()-2 >= (c.size()-2) * 2); vector great_choices; if (a_bigger || a_smaller) great_choices.push_back("A"); if (b_bigger || b_smaller) great_choices.push_back("B"); if (c_bigger || c_smaller) great_choices.push_back("C"); if (d_bigger || d_smaller) great_choices.push_back("D"); if (great_choices.size() == 1) return great_choices[0]; return "C"; } int main() { string a, b, c, d; cin >> a >> b >> c >> d; cout << solve(a, b, c, d) << endl; return 0; } ================================================ FILE: competitive-programming/codeforces/div2/the_child_and_toy.cpp ================================================ // http://codeforces.com/contest/437/problem/C #include using namespace std; int min(int x, int y, int values[]) { return values[x-1] < values[y-1] ? values[x-1] : values[y-1]; } int main() { int n, m, x, y, value, min_energy = 0; cin >> n >> m; int values[n]; for (int i = 0; i < n; i++) { cin >> value; values[i] = value; } while (m--) { cin >> x >> y; min_energy += min(x, y, values); } cout << min_energy << endl; return 0; } ================================================ FILE: competitive-programming/codeforces/div2/valera_and_plates.cpp ================================================ // http://codeforces.com/problemset/problem/369/A #include using namespace std; int main() { int N, M, K, num, W = 0; cin >> N >> M >> K; while (N--) { cin >> num; if (num == 1) { if (M == 0) W++; else M--; } else { if (K == 0) { if (M == 0) W++; else M--; } else { K--; } } } cout << W << endl; return 0; } ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/.exercism/metadata.json ================================================ {"track":"clojure","exercise":"armstrong-numbers","id":"c708010a47824f9daeddb51af2f51b2f","url":"https://exercism.io/my/solutions/c708010a47824f9daeddb51af2f51b2f","handle":"LeandroTk","is_requester":true,"auto_approve":false} ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/.lein-failures ================================================ {} ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/.lein-repl-history ================================================ (defn int->digits [int] (map (comp #(- % 48) int) (str int))) (defn power-by-two [digits] (map #(* % (count digits)) digits)) (defn powered-sum [num] (->> num int->digits power-by-two (reduce +))) (defn armstrong? [num] (= (powered-sum num) num)) (armstrong? 123) (int->digits 123) quit ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/README.md ================================================ # Armstrong Numbers An [Armstrong number](https://en.wikipedia.org/wiki/Narcissistic_number) is a number that is the sum of its own digits each raised to the power of the number of digits. For example: - 9 is an Armstrong number, because `9 = 9^1 = 9` - 10 is *not* an Armstrong number, because `10 != 1^2 + 0^2 = 1` - 153 is an Armstrong number, because: `153 = 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153` - 154 is *not* an Armstrong number, because: `154 != 1^3 + 5^3 + 4^3 = 1 + 125 + 64 = 190` Write some code to determine whether a number is an Armstrong number. ## Source Wikipedia [https://en.wikipedia.org/wiki/Narcissistic_number](https://en.wikipedia.org/wiki/Narcissistic_number) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/project.clj ================================================ (defproject armstrong-numbers "0.1.0-SNAPSHOT" :description "armstrong-numbers exercise" :url "https://github.com/exercism/clojure/tree/master/exercises/armstrong-numbers" :dependencies [[org.clojure/clojure "1.10.0"]]) ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/src/armstrong_numbers.clj ================================================ (ns armstrong-numbers) (defn int->digits [num] (map (comp #(- % 48) int) (str num))) (defn power-by-two [digits digit] (reduce * (repeat (count digits) digit))) (defn power-all-by-two [digits] (map (partial power-by-two digits) digits)) (defn powered-sum [num] (->> num int->digits power-all-by-two (reduce +))) (defn armstrong? [num] (= (powered-sum num) num)) ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/target/classes/META-INF/maven/armstrong-numbers/armstrong-numbers/pom.properties ================================================ #Leiningen #Thu Jan 31 22:57:53 BRST 2019 groupId=armstrong-numbers artifactId=armstrong-numbers version=0.1.0-SNAPSHOT ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/target/stale/leiningen.core.classpath.extract-native-dependencies ================================================ [{:dependencies {org.clojure/clojure {:vsn "1.10.0", :native-prefix nil}, org.clojure/spec.alpha {:vsn "0.2.176", :native-prefix nil}, org.clojure/core.specs.alpha {:vsn "0.2.44", :native-prefix nil}, nrepl {:vsn "0.5.3", :native-prefix nil}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil}, clojure-complete {:vsn "0.2.5", :native-prefix nil}}, :native-path "target/native"} {:native-path "target/native", :dependencies {org.clojure/clojure {:vsn "1.10.0", :native-prefix nil, :native? false}, org.clojure/spec.alpha {:vsn "0.2.176", :native-prefix nil, :native? false}, org.clojure/core.specs.alpha {:vsn "0.2.44", :native-prefix nil, :native? false}, nrepl {:vsn "0.5.3", :native-prefix nil, :native? false}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil, :native? false}, clojure-complete {:vsn "0.2.5", :native-prefix nil, :native? false}}}] ================================================ FILE: competitive-programming/exercism/clojure/armstrong-numbers/test/armstrong_numbers_test.clj ================================================ (ns armstrong-numbers-test (:require [clojure.test :refer [deftest is testing]] [armstrong-numbers :refer [armstrong?]])) (deftest armstrong-number-5 (testing "Single digit numbers are Armstrong numbers" (is (armstrong? 5)))) (deftest not-armstrong-number-10 (testing "There are no 2 digit Armstrong numbers" (is (not (armstrong? 10))))) (deftest armstrong-number-153 (testing "Three digit number that is an Armstrong number" (is (armstrong? 153)))) (deftest not-armstrong-number-100 (testing "Three digit number that is not an Armstrong number" (is (not (armstrong? 100))))) (deftest armstrong-number-9474 (testing "Four digit number that is an Armstrong number" (is (armstrong? 9474)))) (deftest not-armstrong-number-9475 (testing "Four digit number that is not an Armstrong number" (is (not (armstrong? 9476))))) (deftest armstrong-number-9926315 (testing "Seven digit number that is an Armstrong number" (is (armstrong? 9926315)))) (deftest not-armstrong-number-9926314 (testing "Seven digit number that is not an Armstrong number" (is (not (armstrong? 9926314))))) (deftest armstrong-number-21897142587612075 (testing "Seventeen digit number that is an Armstrong number" (is (armstrong? 21897142587612075)))) ================================================ FILE: competitive-programming/exercism/clojure/hello-world/README.md ================================================ # Hello World The classical introductory exercise. Just say "Hello, World!". ["Hello, World!"](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) is the traditional first program for beginning programming in a new language or environment. The objectives are simple: - Write a function that returns the string "Hello, World!". - Run the test suite and make sure that it succeeds. - Submit your solution and check it at the website. If everything goes well, you will be ready to fetch your first real exercise. ### Project Structure Clojure exercises in exercism use [leiningen](http://leiningen.org/) to configure and run your code and use [leiningen standard directory structure](https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md#directory-layout). You will find a test file named `hello_world_test.clj` inside `test` directory. Write your code in `src/hello_world.clj`. It should use the namespace `hello-world` so that tests can pick it up. ### Running tests Run the tests using `lein test` command and make them pass: ``` $ lein test lein test hello-world-test Ran 1 tests containing 1 assertions. 0 failures, 0 errors. ``` Then submit the exercise using: ``` $ exercism submit src/hello_world.clj ``` For more detailed instructions and learning resources refer [exercism's clojure language page](http://exercism.io/languages/clojure). ## Source This is an exercise to introduce users to using Exercism [http://en.wikipedia.org/wiki/%22Hello,_world!%22_program](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. ================================================ FILE: competitive-programming/exercism/clojure/hello-world/project.clj ================================================ (defproject hello-world "0.1.0-SNAPSHOT" :description "hello-world exercise." :url "https://github.com/exercism/clojure/tree/master/exercises/hello-world" :dependencies [[org.clojure/clojure "1.9.0"]]) ================================================ FILE: competitive-programming/exercism/clojure/hello-world/src/hello-world.clj ================================================ (ns hello-world) (defn hello [] "Hello, World!") ================================================ FILE: competitive-programming/exercism/clojure/hello-world/test/hello-world-test.clj ================================================ (ns hello-world-test (:require [clojure.test :refer [deftest is]] hello-world)) (deftest hello-world-test (is (= "Hello, World!" (hello-world/hello)))) ================================================ FILE: competitive-programming/exercism/clojure/two-fer/.exercism/metadata.json ================================================ {"track":"clojure","exercise":"two-fer","id":"13de8e46adaa41d68299dc2b4a20ff1c","url":"https://exercism.io/my/solutions/13de8e46adaa41d68299dc2b4a20ff1c","handle":"LeandroTk","is_requester":true,"auto_approve":false} ================================================ FILE: competitive-programming/exercism/clojure/two-fer/.lein-failures ================================================ {} ================================================ FILE: competitive-programming/exercism/clojure/two-fer/.nrepl-port ================================================ 62204 ================================================ FILE: competitive-programming/exercism/clojure/two-fer/README.md ================================================ # Two Fer `Two-fer` or `2-fer` is short for two for one. One for you and one for me. Given a name, return a string with the message: ```text One for X, one for me. ``` Where X is the given name. However, if the name is missing, return the string: ```text One for you, one for me. ``` Here are some examples: |Name | String to return |:------:|:-----------------: |Alice | One for Alice, one for me. |Bob | One for Bob, one for me. | | One for you, one for me. |Zaphod | One for Zaphod, one for me. ## Source [https://github.com/exercism/problem-specifications/issues/757](https://github.com/exercism/problem-specifications/issues/757) ## Submitting Incomplete Solutions It's possible to submit an incomplete solution so you can see how others have completed the exercise. ================================================ FILE: competitive-programming/exercism/clojure/two-fer/project.clj ================================================ (defproject two-fer "0.1.0-SNAPSHOT" :description "two-fer exercise." :url "https://github.com/exercism/clojure/tree/master/exercises/two-fer" :dependencies [[org.clojure/clojure "1.8.0"]]) ================================================ FILE: competitive-programming/exercism/clojure/two-fer/src/two_fer.clj ================================================ (ns two-fer) (defn two-fer ([] "One for you, one for me.") ([name] (str "One for " name ", one for me."))) ================================================ FILE: competitive-programming/exercism/clojure/two-fer/target/classes/META-INF/maven/two-fer/two-fer/pom.properties ================================================ #Leiningen #Sun Feb 03 05:19:15 BRST 2019 groupId=two-fer artifactId=two-fer version=0.1.0-SNAPSHOT ================================================ FILE: competitive-programming/exercism/clojure/two-fer/target/repl-port ================================================ 62204 ================================================ FILE: competitive-programming/exercism/clojure/two-fer/target/stale/leiningen.core.classpath.extract-native-dependencies ================================================ [{:dependencies {org.clojure/clojure {:vsn "1.8.0", :native-prefix nil}, nrepl {:vsn "0.5.3", :native-prefix nil}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil}, clojure-complete {:vsn "0.2.5", :native-prefix nil}}, :native-path "target/native"} {:native-path "target/native", :dependencies {org.clojure/clojure {:vsn "1.8.0", :native-prefix nil, :native? false}, clojure-complete {:vsn "0.2.5", :native-prefix nil, :native? false}, nrepl {:vsn "0.5.3", :native-prefix nil, :native? false}, nrepl/bencode {:vsn "1.0.0", :native-prefix nil, :native? false}}}] ================================================ FILE: competitive-programming/exercism/clojure/two-fer/test/two_fer_test.clj ================================================ (ns two-fer-test (:require [clojure.test :refer [deftest is]] two-fer)) (deftest two-fer-test (is (= "One for you, one for me." (two-fer/two-fer)))) (deftest name-alice-test (is (= "One for Alice, one for me." (two-fer/two-fer "Alice")))) (deftest name-bob-test (is (= "One for Bob, one for me." (two-fer/two-fer "Bob")))) ================================================ FILE: competitive-programming/exercism/javascript/allergies.js ================================================ export class Allergies { constructor(score) { this.score = score; this.scores = [128, 64, 32, 16, 8, 4, 2, 1]; this.scoreToFoodMapper = { 1: 'eggs', 2: 'peanuts', 4: 'shellfish', 8: 'strawberries', 16: 'tomatoes', 32: 'chocolate', 64: 'pollen', 128: 'cats', }; } list() { this.listOfFoods = []; this.findMaxSmallerThanScore(this.score); return [...new Set(this.listOfFoods)]; } findMaxSmallerThanScore(score) { if (score === 0) return; const maxSmallerThanScore = this.scores.find( (currentScore) => currentScore <= score ); this.listOfFoods.unshift(this.scoreToFoodMapper[maxSmallerThanScore]); score -= maxSmallerThanScore; return this.findMaxSmallerThanScore(score); } allergicTo(food) { return this.list().includes(food); } } ================================================ FILE: competitive-programming/exercism/javascript/collatz-conjecture.js ================================================ export const steps = n => { if (n <= 0) throw "Only positive numbers are allowed"; let times = 0; while (n !== 1) { if (n % 2 === 0) { n /= 2; } else { n = n * 3 + 1; } times++; } return times; }; ================================================ FILE: competitive-programming/exercism/javascript/count-words.js ================================================ const SPECIAL_CHARACTERS = /[!@#\$%\^\&*\".,;:?<>~`(\){}[\]\\/\+=_-]/g; const SPACE_CHARACTERS = /\s+/g; function isEmptySpace(string) { return string !== ''; } function removeOpenQuote(word) { return word.startsWith("'") ? word.substring(1) : word; } function removeCloseQuote(word) { return word.endsWith("'") ? word.substring(0, word.length - 1) : word; } function removeQuotes(word) { return removeCloseQuote(removeOpenQuote(word)); } export const countWords = (phrase) => { const words = phrase .toLowerCase() .replaceAll(SPECIAL_CHARACTERS, ' ') .split(SPACE_CHARACTERS) .filter(isEmptySpace) .map(removeQuotes); const wordCounter = {}; for (const word of words) { wordCounter[word] = (wordCounter[word] || 0) + 1; } return wordCounter; }; ================================================ FILE: competitive-programming/exercism/javascript/etl.js ================================================ export const transform = (scoreToLetters) => { const obj = {}; Object.entries(scoreToLetters).forEach(([score, letters]) => { letters.forEach((letter) => { obj[letter.toLowerCase()] = Number(score); }); }); return obj; }; ================================================ FILE: competitive-programming/exercism/javascript/flatten-array.js ================================================ export const flatten = (list) => { const result = []; list.forEach((item) => { if (Array.isArray(item)) { result.push(...flatten(item)); } else if (item !== undefined && item !== null) { result.push(item); } }); return result; }; ================================================ FILE: competitive-programming/exercism/javascript/gigasecond.js ================================================ const year = date => date.getUTCFullYear(); const month = date => date.getUTCMonth(); const day = date => date.getUTCDate() + 11574; const hours = date => date.getUTCHours() + 1; const minutes = date => date.getUTCMinutes() + 46; const second = date => date.getUTCSeconds() + 40; export const gigasecond = date => new Date( Date.UTC( year(date), month(date), day(date), hours(date), minutes(date), second(date) ) ); ================================================ FILE: competitive-programming/exercism/javascript/hello-world.js ================================================ export const hello = () => "Hello, World!"; ================================================ FILE: competitive-programming/exercism/javascript/leap.js ================================================ // https://exercism.io/tracks/javascript/exercises/leap/solutions/0e7bcf1db4974d159ab9ebe9e961bcd1 export const isLeap = year => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; ================================================ FILE: competitive-programming/exercism/javascript/perfect-numbers.js ================================================ const getAllDivisibleNumbers = (number) => { const divisibleNumbers = []; for (let i = 1; i <= number / 2; i++) { if (number % i === 0) { divisibleNumbers.push(i); } } return divisibleNumbers; }; const sumAllNumbers = (numbers) => numbers.reduce((sum, number) => sum + number, 0); export const classify = (number) => { if (number <= 0) { throw new Error('Classification is only possible for natural numbers.'); } const divisibleNumbers = getAllDivisibleNumbers(number); const sumOfNumbers = sumAllNumbers(divisibleNumbers); console.log('divisibleNumbers', divisibleNumbers); console.log('sumOfNumbers', sumOfNumbers); if (sumOfNumbers === number) { return 'perfect'; } if (sumOfNumbers > number) { return 'abundant'; } if (sumOfNumbers < number) { return 'deficient'; } }; ================================================ FILE: competitive-programming/exercism/javascript/phone-number.js ================================================ const isDigit = (char) => '0' <= char && char <= '9'; const getDigits = (phoneNumber) => phoneNumber.split('').filter(isDigit).join(''); const verifyDigitsLength = (digits) => { if (digits.length < 10) { throw new Error('Incorrect number of digits'); } if (digits.length >= 12) { throw new Error('More than 11 digits'); } }; const verifyCountryCode = (digits) => { if (digits.length === 11 && digits[0] !== '1') { throw new Error('11 digits must start with 1'); } }; const verifyAreaCode = (digits) => { if (digits.length === 10 && digits[0] === '0') { throw new Error('Area code cannot start with zero'); } if (digits.length === 10 && digits[0] === '1') { throw new Error('Area code cannot start with one'); } if (digits.length === 11 && digits[1] === '0') { throw new Error('Area code cannot start with zero'); } if (digits.length === 11 && digits[1] === '1') { throw new Error('Area code cannot start with one'); } }; const verifyExchangeCode = (digits) => { if (digits.length === 10 && digits[3] === '0') { throw new Error('Exchange code cannot start with zero'); } if (digits.length === 10 && digits[3] === '1') { throw new Error('Exchange code cannot start with one'); } if (digits.length === 11 && digits[4] === '0') { throw new Error('Exchange code cannot start with zero'); } if (digits.length === 11 && digits[4] === '1') { throw new Error('Exchange code cannot start with one'); } }; const verifyAlphabetChars = (digits) => { const alphabetChars = digits.match(/[A-Za-z]/g); if (alphabetChars && alphabetChars.length) { throw new Error('Letters not permitted'); } }; const verifyPunctuationChars = (digits) => { const punctuationChars = digits.match(/[,\/#!$%\^&\*;:{}=\_`~]/g); if (punctuationChars && punctuationChars.length) { throw new Error('Punctuations not permitted'); } }; export const clean = (phoneNumber) => { const digits = getDigits(phoneNumber); verifyAlphabetChars(phoneNumber); verifyPunctuationChars(phoneNumber); verifyDigitsLength(digits); verifyCountryCode(digits); verifyAreaCode(digits); verifyExchangeCode(digits); return digits.length === 11 ? digits.substring(1) : digits; }; ================================================ FILE: competitive-programming/exercism/javascript/resistor-color.js ================================================ const colorCode = color => COLORS.indexOf(color); const COLORS = [ "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" ]; export { colorCode, COLORS }; ================================================ FILE: competitive-programming/exercism/javascript/resistor-colors.js ================================================ // https://exercism.io/my/solutions/0a95e6a8ebb94efeac42b2c6e065818b const COLORS = [ "black", "brown", "red", "orange", "yellow", "green", "blue", "violet", "grey", "white" ]; const reducer = (acc, resistanceValue) => acc + resistanceValue; const resistanceValuesString = (resistorsColors) => resistorsColors .map((color) => COLORS.indexOf(color)) .reduce(reducer, ""); export const value = (resistorsColors) => { return Number(resistanceValuesString(resistorsColors)); }; ================================================ FILE: competitive-programming/exercism/javascript/reverse-string.js ================================================ const lastChar = str => str[str.length - 1]; export const reverseString = str => { if (str.length <= 1) { return str; } return lastChar(str) + reverseString(str.substring(0, str.length - 1)); }; ================================================ FILE: competitive-programming/exercism/javascript/sublist.js ================================================ const COMPARISON = { EQUAL: 'EQUAL', SUBLIST: 'SUBLIST', SUPERLIST: 'SUPERLIST', UNEQUAL: 'UNEQUAL', }; export class List { constructor(numbers = []) { this.numbers = numbers; } compare(otherList) { const otherNumbers = otherList.numbers; const numbersLength = this.numbers.length; const otherLength = otherNumbers.length; if (numbersLength < otherLength) { return this.isSublist(otherNumbers) ? COMPARISON.SUBLIST : COMPARISON.UNEQUAL; } if (numbersLength > otherLength) { return this.isSuperList(this.numbers, otherNumbers) ? COMPARISON.SUPERLIST : COMPARISON.UNEQUAL; } return this.isIdentical(this.numbers, otherNumbers) ? COMPARISON.EQUAL : COMPARISON.UNEQUAL; } isIdentical(numbers, otherList) { if (numbers.length !== otherList.length) return false; for (let i = 0; i < numbers.length; i++) { if (numbers[i] !== otherList[i]) return false; } return true; } isSublist(otherNumbers) { const numbersLength = this.numbers.length; const otherLength = otherNumbers.length; for (let i = 0; i < otherLength - numbersLength + 1; i++) { if ( this.isIdentical(this.numbers, otherNumbers.slice(i, i + numbersLength)) ) { return true; } } return false; } isSuperList(numbers, otherNumbers) { const numbersLength = numbers.length; const otherLength = otherNumbers.length; for (let i = 0; i < numbersLength - otherLength + 1; i++) { if (this.isIdentical(numbers.slice(i, i + otherLength), otherNumbers)) { return true; } } return false; } } ================================================ FILE: competitive-programming/exercism/javascript/sum-of-multiples.js ================================================ export const sum = (multiples, limit) => { let sum = 0; let counted = {}; multiples.forEach((multiple) => { if (!multiple) return; let increment = multiple; while (increment < limit) { if (!counted[increment]) sum += increment; counted[increment] = true; increment += multiple; } }); return sum; }; ================================================ FILE: competitive-programming/exercism/javascript/triangle.js ================================================ export function Triangle(side1, side2, side3) { this.side1 = side1; this.side2 = side2; this.side3 = side3; } Triangle.prototype.isEquilateral = function() { return this.side1 == this.side2 && this.side1 == this.side3; }; Triangle.prototype.isIsosceles = function() { return ( this.side1 == this.side2 || this.side1 == this.side3 || this.side2 == this.side3 ); }; Triangle.prototype.anyNonPositiveSide = function() { return this.side1 <= 0 || this.side2 <= 0 || this.side3 <= 0; }; Triangle.prototype.isInequality = function() { return ( this.side1 > this.side2 + this.side3 || this.side2 > this.side1 + this.side3 || this.side3 > this.side2 + this.side1 ); }; Triangle.prototype.kind = function() { if (this.anyNonPositiveSide() || this.isInequality()) { throw "Not a triangle"; } else if (this.isEquilateral()) { return "equilateral"; } else if (this.isIsosceles()) { return "isosceles"; } else { return "scalene"; } }; ================================================ FILE: competitive-programming/exercism/javascript/two-fer.js ================================================ export const twoFer = (name = "you") => `One for ${name}, one for me.`; ================================================ FILE: competitive-programming/hacker-rank/algorithms/strings/palindrome_index.py ================================================ # https://www.hackerrank.com/challenges/palindrome-index import sys def is_palindrome(s): return s == s[::-1] def palindrome_index(s): for i in range(len(s)): if is_palindrome(s[i+1:len(s)-i]): return i if is_palindrome(s[i:len(s)-i-1]): return len(s)-i-1 q = int(raw_input().strip()) for num in range(q): s = raw_input().strip() result = palindrome_index(s) print(result) ================================================ FILE: competitive-programming/hacker-rank/algorithms/warmup/birthday_cake_candles.py ================================================ # https://www.hackerrank.com/challenges/birthday-cake-candles/problem def birthday_cake_candles(n, ar): sorted_ar = sorted(ar, reverse = True) tallest = sorted_ar[0] result = 0 for candle_height in sorted_ar: if tallest == candle_height: result += 1 return result print(birthday_cake_candles(int(raw_input()), map(int, raw_input().strip().split(' ')))) ================================================ FILE: competitive-programming/hacker-rank/algorithms/warmup/mini_max_sum.py ================================================ def mini_max_sum(arr): sorted_arr = sorted(arr) print sum(sorted_arr[0:4]), sum(sorted_arr[1:5]) if __name__ == "__main__": arr = map(int, raw_input().strip().split(' ')) mini_max_sum(arr) ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/angry_professor.cpp ================================================ #include using namespace std; int main() { int t, n, k, time, total_students_arrived_before_class=0; cin >> t; while (t--) { cin >> n >> k; for (int i = 0; i < n; i++) { cin >> time; if (time <= 0) total_students_arrived_before_class++; } if (total_students_arrived_before_class >= k) cout << "NO" << endl; else cout << "YES" << endl; total_students_arrived_before_class=0; } return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/arrays_introduction.cpp ================================================ // https://www.hackerrank.com/challenges/arrays-introduction?h_r=next-challenge&h_v=zen #include #include using namespace std; int main() { vector v; int n, x; cin >> n; while (n--) { cin >> x; v.push_back(x); } for (int i = v.size()-1; i >= 0; i--) cout << v[i] << " "; cout << endl; return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/diagonal_difference.cpp ================================================ #include #include using namespace std; int main() { vector< vector > matrix; vector v; int n, diag1=0, diag2=0, temp; cin >> n; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { cin >> temp; v.push_back(temp); } matrix.push_back(v); v.clear(); } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) diag1 += matrix[i][j]; if (j == n - 1 - i) diag2 += matrix[i][j]; } } int result = diag1 - diag2; if (result < 0) result *= -1; cout << result << endl; return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/input_and_output.cpp ================================================ // https://www.hackerrank.com/challenges/cpp-input-and-output #include #include #include #include #include using namespace std; int main() { int a, b, c; cin >> a >> b >> c; cout << a + b + c << endl; return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/library_fine.cpp ================================================ #include using namespace std; int main() { int day1, day2, month1, month2, year1, year2; cin >> day1 >> month1 >> year1; cin >> day2 >> month2 >> year2; if (year1 == year2) { if (month1 == month2) { if (day1 <= day2) cout << 0 << endl; else cout << 15 * (day1 - day2) << endl; } else if (month1 > month2) { cout << 500 * (month1 - month2) << endl; } else { cout << 0 << endl; } } else if (year1 > year2) { cout << 10000 * (year1 - year2) << endl; } else { cout << 0 << endl; } return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/plus_minus.cpp ================================================ #include using namespace std; int main() { int n, temp, num, zeros=0, positives=0, negatives=0; cin >> n; temp = n; while (temp--) { cin >> num; if (num > 0) positives++; else if (num < 0) negatives++; else zeros++; } double divisor = n; cout << positives / divisor << endl; cout << negatives / divisor << endl; cout << zeros / divisor << endl; return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/staircase.cpp ================================================ #include #include using namespace std; int main() { int n; string result=""; cin >> n; int total = n; while (n) { for (int i = 1; i < n; i++) result += " "; int num_symbol = total + 1 - n; for (int i = 0; i < num_symbol; i++) { result += "#"; } cout << result << endl; result.clear(); n--; } return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/time_conversion.cpp ================================================ #include #include using namespace std; int main() { string time; cin >> time; char letter = time[8]; if (letter == 'A'){ if (time.substr(0, 2) == "12") cout << "00" + time.substr(2, 6); else if (time.substr(0, 2) == "13") cout << "01" + time.substr(2, 6); else if (time.substr(0, 2) == "14") cout << "02" + time.substr(2, 6); else if (time.substr(0, 2) == "15") cout << "03" + time.substr(2, 6); else if (time.substr(0, 2) == "16") cout << "04" + time.substr(2, 6); else if (time.substr(0, 2) == "17") cout << "05" + time.substr(2, 6); else if (time.substr(0, 2) == "18") cout << "06" + time.substr(2, 6); else if (time.substr(0, 2) == "19") cout << "07" + time.substr(2, 6); else if (time.substr(0, 2) == "20") cout << "08" + time.substr(2, 6); else if (time.substr(0, 2) == "21") cout << "09" + time.substr(2, 6); else if (time.substr(0, 2) == "22") cout << "10" + time.substr(2, 6); else if (time.substr(0, 2) == "23") cout << "" + time.substr(2, 6); else cout << time.substr(0, 8); } else { if (time.substr(0, 2) == "00") cout << "24" + time.substr(2, 6); else if (time.substr(0, 2) == "01") cout << "13" + time.substr(2, 6); else if (time.substr(0, 2) == "02") cout << "14" + time.substr(2, 6); else if (time.substr(0, 2) == "03") cout << "15" + time.substr(2, 6); else if (time.substr(0, 2) == "04") cout << "16" + time.substr(2, 6); else if (time.substr(0, 2) == "05") cout << "17" + time.substr(2, 6); else if (time.substr(0, 2) == "06") cout << "18" + time.substr(2, 6); else if (time.substr(0, 2) == "07") cout << "19" + time.substr(2, 6); else if (time.substr(0, 2) == "08") cout << "20" + time.substr(2, 6); else if (time.substr(0, 2) == "09") cout << "21" + time.substr(2, 6); else if (time.substr(0, 2) == "10") cout << "22" + time.substr(2, 6); else if (time.substr(0, 2) == "11") cout << "23" + time.substr(2, 6); else cout << time.substr(0, 8); } return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/vector_erase.cpp ================================================ #include #include using namespace std; int main() { int time, temp, n; vector v; cin >> time; while (time--) { cin >> temp; v.push_back(temp); } int bla, begin, end; cin >> bla >> begin >> end; cout << end - begin + 1 << endl; v.erase(v.begin() + begin - 1, v.begin() + end); for (int i = 0; i < v.size(); i++) cout << v[i] << " "; return 0; } ================================================ FILE: competitive-programming/hacker-rank/cpp/introduction/vector_sort.cpp ================================================ #include #include #include using namespace std; int main() { vector v; int n, temp; cin >> n; while (n--) { cin >> temp; v.push_back(temp); } sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) cout << v[i] << " "; return 0; } ================================================ FILE: competitive-programming/hacker-rank/data_structures/trees/in_order_traversal.py ================================================ def in_order(node): if node.left: in_order(node.left) print node.data, if node.right: in_order(node.right) ================================================ FILE: competitive-programming/hacker-rank/data_structures/trees/post_order_traversal.py ================================================ def post_order(node): if node.left: post_order(node.left) if node.right: post_order(node.right) print(node.data) ================================================ FILE: competitive-programming/hacker-rank/data_structures/trees/pre_order_traversal.py ================================================ def pre_order(node): print(node.data) if node.left: pre_order(node.left) if node.right: pre_order(node.right) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/array_of_n_elements/array_of_n_elements.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-array-of-n-elements/problem (defn array-of-n-elements [n] (range n)) (array-of-n-elements 1) (array-of-n-elements 3) (array-of-n-elements 5) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/array_of_n_elements/array_of_n_elements_without_range.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-array-of-n-elements/problem (defn array-of-n-elements-without-range [n] (loop [n n list []] (if (pos? n) (recur (dec n) (conj list 0)) list))) (array-of-n-elements-without-range 1) (array-of-n-elements-without-range 3) (array-of-n-elements-without-range 5) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/basics/hello_world.clj ================================================ ;; Problem: https://www.hackerrank.com/challenges/fp-hello-world/problem?h_r=next-challenge&h_v=zen (print "Hello World") ================================================ FILE: competitive-programming/hacker-rank/functional-programming/basics/hello_world_n_times.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-hello-world-n-times/problem (defn greater-than-zero? [n] (> n 0)) (defn hello-word-n-times [n] (if (greater-than-zero? n) (do (println "Hello World") (hello-word-n-times (dec n))))) (hello-word-n-times 4) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/basics/solve_me_first.clj ================================================ ;; Problem: https://www.hackerrank.com/challenges/fp-solve-me-first/problem (defn solve-me-first [a b] (+ a b)) (def a (read-line)) (def b (read-line)) (println (solve-me-first (Integer/parseInt a) (Integer/parseInt b))) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/eval_ex/main.clj ================================================ ;; https://www.hackerrank.com/challenges/eval-ex/problem ;; Approach: ;; Use map to transform the list of 10 elements from x to (/ (exp x n) (factorial n)) ;; And reduce suming each element ;; For this approach, we can separate in 3 different functions ;; - exp: exponantial ;; - factorial ;; - expansion: function composed of exp and factorial passed to map ;; So we can test these 3 functions (ns eval-ex (:use [clojure.test])) (defn exp [x n] (reduce * (repeat n x))) (defn factorial [n] (reduce * (range 1 (inc n)))) (defn expansion [x] (fn [n] (/ (exp x n) (factorial n)))) (defn series-expansion [x] (read-string (format "%.4f" (reduce + (map (expansion x) (range 10)))))) ;; ----------------------------------------------------------- ;; Tests (deftest test-exp (testing "Exponantial function" (is (= 1 (exp 1 0))) (is (= 1 (exp 1 1))) (is (= 4 (exp 2 2))))) (deftest test-factorial (testing "Factorial function" (is (= 1 (factorial 0))) (is (= 1 (factorial 1))) (is (= 120 (factorial 5))))) (deftest test-expansion (testing "Expansion function" (is (= 1 ((expansion 10) 0))) (is (= 10 ((expansion 10) 1))) (is (= 50 ((expansion 10) 2))))) (deftest test-series-expansion (testing "Sample Input - Output" (is (= 2423600.1887 (series-expansion 20.0000))) (is (= 143.6895 (series-expansion 5.0000))) (is (= 1.6487 (series-expansion 0.5000))) (is (= 0.6065 (series-expansion -0.5000))))) (run-tests) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/filter_array/filter_array.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-filter-array/problem (defn filter-array [n lst] (filter #(> n %) lst)) (filter-array 25 [-41 46 -28 21 52 83 -29 84 27 40]) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/filter_positions_in_a_list/filter_positions_in_a_list.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-filter-positions-in-a-list/problem (defn filter-positions-in-a-list [lst] (take-nth 2 (rest lst))) (filter-positions-in-a-list []) (filter-positions-in-a-list [0 1 2]) (filter-positions-in-a-list [0 1 2 3 4 5 6 7 8 9]) (filter-positions-in-a-list [8 15 22 1 10 6 2 18 18 1]) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/list_length/list_length.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-list-length/problem?h_r=next-challenge&h_v=zen (defn list-length [lst] (loop [coll lst counter 0] (if (empty? coll) counter (recur (rest coll) (inc counter))))) (list-length [0 1 2 3 4 5 6 7 8 9]) (list-length [0 1 2 -1 4 -5 6 7 -8 9]) (list-length []) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/list_length/list_length_reduce.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-list-length/problem?h_r=next-challenge&h_v=zen (defn list-length [lst] (reduce + (map (constantly 1) lst))) (list-length [0 1 2 3 4 5 6 7 8 9]) (list-length [0 1 2 -1 4 -5 6 7 -8 9]) (list-length []) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/list_replication/list_replication.clj ================================================ ;; Problem: https://www.hackerrank.com/challenges/fp-list-replication/problem (defn list-replication [n list] (sort (flatten (repeat n list)))) (list-replication 3 [1 2 3]) (list-replication 2 [4 5]) (list-replication 1 [10 100]) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem ;; last function: returns the last element of a collection ;; count function: returns the length of a collection ;; take function: returns the first N taken elements of a collection ;; not-empty function: returns true if the collection is not empty. Otherwise, false (def example-list [19 22 3 28 26 17 18 4 28 0]) (defn reverse-a-list [list] (loop [original-list list reversed-list []] (if (not-empty original-list) (recur (take (dec (count original-list)) original-list) (conj reversed-list (last original-list))) reversed-list))) (reverse-a-list example-list) ;; Implementing an anonymous function (fn [lst] (loop [original-list lst reversed-list []] (if (not-empty original-list) (recur (take (dec (count original-list)) original-list) (conj reversed-list (last original-list))) reversed-list))) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list_into.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem ;; basically, the into function is a reduce + conj (def example-list [19 22 3 28 26 17 18 4 28 0]) (defn reverse-a-list [lst] (into '() lst)) (reverse-a-list example-list) ((fn [lst] (into '() lst)) example-list) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/reverse_a_list/reverse_a_list_reduce.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-reverse-a-list/problem (def example-list [19 22 3 28 26 17 18 4 28 0]) (defn reverse-a-list [lst] (reduce conj '() lst)) (reverse-a-list example-list) ;; Implementing an anonymous function ((fn [lst] (reduce conj '() lst)) example-list) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/sum_of_odd_elements/sum_of_odd_elements.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-sum-of-odd-elements/problem (defn sum-of-odd-elements [lst] (reduce + (filter (odd? n) lst))) (sum-of-odd-elements [3 2 4 6 5 7 8 0 1]) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-update-list/problem (defn to-absolute [n] (if (neg? n) (+ (* n -2) n) n)) (defn add-element-from-list-to-list [lst1 lst2] (conj lst2 (to-absolute (first lst1)))) (defn update-list [lst] (loop [original-list lst absolute-list []] (if (empty? original-list) absolute-list (recur (rest original-list) (add-element-from-list-to-list original-list absolute-list))))) (update-list []) (update-list [1 2 3 4 5]) (update-list [-1 -2 -3 -4 -5]) (update-list [1 -2 3 -4 5]) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list_anonymous.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-update-list/problem (fn [lst] (loop [original-list lst absolute-list []] (if (empty? original-list) absolute-list (recur (rest original-list) (conj absolute-list (if (< (first original-list) 0) (+ (* (first original-list) -2) (first original-list)) (first original-list))))))) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list_map.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-update-list/problem (defn to-absolute [n] (if (neg? n) (+ (* n -2) n) n)) (defn update-list-map [lst] (map to-absolute lst)) (update-list-map []) (update-list-map [1 2 3 4 5]) (update-list-map [-1 -2 -3 -4 -5]) (update-list-map [1 -2 3 -4 5]) ================================================ FILE: competitive-programming/hacker-rank/functional-programming/update_list/update_list_map_anonymous.clj ================================================ ;; https://www.hackerrank.com/challenges/fp-update-list/problem (fn [lst] (map (fn [n] (if (neg? n) (+ (* n -2) n) n)) lst)) ================================================ FILE: competitive-programming/hacker-rank/python/basic_data_types/finding_the_percentage.py ================================================ # https://www.hackerrank.com/challenges/finding-the-percentage/problem if __name__ == '__main__': n = int(raw_input()) student_marks = {} for _ in range(n): line = raw_input().split() name, scores = line[0], line[1:] scores = map(float, scores) student_marks[name] = scores print('%.2f' %(sum(student_marks[raw_input()]) / 3)) ================================================ FILE: competitive-programming/hacker-rank/python/basic_data_types/lists.py ================================================ if __name__ == '__main__': N = int(raw_input()) l = [] for i in range(N): u_input = raw_input().split(' ') if u_input[0] == 'insert': l.insert(int(u_input[1]), int(u_input[2])) elif u_input[0] == 'remove': l.remove(int(u_input[1])) elif u_input[0] == 'append': l.append(int(u_input[1])) elif u_input[0] == 'sort': l.sort() elif u_input[0] == 'pop': l.pop() elif u_input[0] == 'reverse': l.reverse() else: print(l) ================================================ FILE: competitive-programming/hacker-rank/python/basic_data_types/nested_list.py ================================================ # https://www.hackerrank.com/challenges/nested-list/problem marksheet = [[raw_input(), float(raw_input())] for _ in range(int(raw_input()))] second_lowest = sorted(list(set([score for name, score in marksheet])))[1] names = sorted([name for name, score in marksheet if score == second_lowest]) for name in names: print name ================================================ FILE: competitive-programming/hacker-rank/python/basic_data_types/runner_up_score.py ================================================ # [1,6,3,6,5,4] # [1,-1] # [6, 1] # [6, 3] # [6, 3] # [6, 5] # [6, 5] if __name__ == '__main__': n = int(raw_input()) arr = map(int, raw_input().split()) maximum = -999999999999999999999 runner_up = -999999999999999999999 for el in arr: if el > maximum: runner_up = maximum maximum = el elif el < maximum and el > runner_up: runner_up = el print(runner_up) ================================================ FILE: competitive-programming/hacker-rank/python/basic_data_types/tuple.py ================================================ # https://www.hackerrank.com/challenges/python-tuples/problem if __name__ == '__main__': n = int(raw_input()) integer_list = map(int, raw_input().split()) print(hash(tuple(integer_list))) ================================================ FILE: competitive-programming/hacker-rank/python/introduction/arithmetic_operators.py ================================================ if __name__ == '__main__': a = int(raw_input()) b = int(raw_input()) print(a + b) print(a - b) print(a * b) ================================================ FILE: competitive-programming/hacker-rank/python/introduction/division.py ================================================ from __future__ import division if __name__ == '__main__': a = int(raw_input()) b = int(raw_input()) print(a // b) print(a / b) ================================================ FILE: competitive-programming/hacker-rank/python/introduction/if_else.py ================================================ if __name__ == '__main__': n = int(raw_input()) if n % 2 != 0: print("Weird") else: if n >= 2 and n <= 5: print("Not Weird") elif n >= 6 and n <= 20: print("Weird") elif n > 20: print("Not Weird") ================================================ FILE: competitive-programming/hacker-rank/python/sets/intro_to_sets.py ================================================ # https://www.hackerrank.com/challenges/py-introduction-to-sets/problem def average(array): return sum(list(set(array))) / float(len(set(array))) ================================================ FILE: competitive-programming/hacker-rank/python/strings/find_a_string.py ================================================ # https://www.hackerrank.com/challenges/find-a-string/problem # ABCDCDC # CDC # 2 # ABCDCDCD # CD # 3 # ABCDCDC # AD # 0 def count_substring(string, sub_string): counter = 0 for index in range(0, len(string) - len(sub_string) + 1): if sub_string == string[index:index + len(sub_string)]: counter += 1 return counter print(count_substring('ABCDCDC', 'CDC')) print(count_substring('ABCDCDCD', 'CD')) print(count_substring('ABCDCDC', 'AD')) ================================================ FILE: competitive-programming/hacker-rank/python/strings/mutate_string.py ================================================ # https://www.hackerrank.com/challenges/python-mutations/problem # abracadabra # 5 k # abrackdabra def mutate_string(string, position, character): mutated_string = '' for i in range(len(string)): if i == position: mutated_string += character else: mutated_string += string[i] return mutated_string print(mutate_string('abracadabra', 5, 'k')) ================================================ FILE: competitive-programming/hacker-rank/python/strings/split_and_join.py ================================================ # https://www.hackerrank.com/challenges/python-string-split-and-join/problem # this is a string => this-is-a-string # 123 456 789 => 123-456-789 # ... ... ... => ...-...-... def split_and_join(line): new_line = '' for c in line: if c == ' ': new_line += '-' else: new_line += c return new_line print(split_and_join('this is a string')) print(split_and_join('123 456 789')) print(split_and_join('... ... ...')) print(split_and_join('... ... ... ')) ================================================ FILE: competitive-programming/hacker-rank/python/strings/string_validators.py ================================================ # https://www.hackerrank.com/challenges/string-validators/problem if __name__ == '__main__': s = raw_input() print(any(c.isalnum() for c in s)) print(any(c.isalpha() for c in s)) print(any(c.isdigit() for c in s)) print(any(c.islower() for c in s)) print(any(c.isupper() for c in s)) ================================================ FILE: competitive-programming/hacker-rank/python/strings/swap_case.py ================================================ # https://www.hackerrank.com/challenges/swap-case/problem # A - Z (65 - 90) # a - z (97 - 122) def swap_case(s): difference = 32 swapped_s = '' for i in s: if ord(i) < 65 or (ord(i) > 90 and ord(i) < 97) or ord(i) > 122: swapped_s += i elif ord(i) <= 90: swapped_s += chr(ord(i) + difference) else: swapped_s += chr(ord(i) - difference) return swapped_s print(swap_case('Www.HackerRank.com')) print(swap_case('Pythonist 2')) print(swap_case('HackerRank.com presents "Pythonist 2".')) ================================================ FILE: competitive-programming/hacker-rank/python/strings/text_wrap.py ================================================ # https://www.hackerrank.com/challenges/text-wrap/problem import textwrap def wrap(string, max_width): wrapped_text = '' for i in range(1, len(string) + 1): if i % max_width == 0: wrapped_text += string[i-1] print(wrapped_text) wrapped_text = '' else: wrapped_text += string[i-1] return wrapped_text print(wrap('ABCDEFGHIJKLIMNOQRSTUVWXYZ', 4)) ================================================ FILE: competitive-programming/hacker-rank/python/strings/whats_your_name.py ================================================ # https://www.hackerrank.com/challenges/whats-your-name/problem # Guido # Rossum # Hello Guido Rossum! You just delved into python. def print_full_name(a, b): print "Hello %s %s! You just delved into python." %(a, b) print_full_name('Guido', 'Rossum') ================================================ FILE: competitive-programming/interfatecs/1_2016/a.cpp ================================================ #include #include #include using namespace std; int main() { int marq, n, e; string s; while (cin >> marq) { cin >> n; cin.ignore(); getline(cin, s); string st = s + s; cin >> e; e = e % n; while(st.size() < marq) { st += s; } if (marq > n) cout << st.substr(e, n) << endl; else cout << st.substr(e, marq) << endl; } return 0; } ================================================ FILE: competitive-programming/interfatecs/1_2016/b.cpp ================================================ #include #include #include using namespace std; int main() { int n; while (cin >> n && n != -1) { cout << 31 % n << endl; } return 0; } ================================================ FILE: competitive-programming/interfatecs/1_2016/g.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int n; double bang; cin >> n; while (n--) { vector v; for (int i = 0; i < 12; i++) { cin >> bang; v.push_back(bang); } sort(v.begin(), v.end()); float total = 0; for (int i = 3; i < 12; i++) { total += v[i]; } float media = total / 9; if (media * 0.2 < 1.75) { cout << "REPROVADO" << endl; } else { double coisa = ((5.75 - (media * 0.2)) / 0.8) * 2; printf("%.1f\n", coisa); } } return 0; } ================================================ FILE: competitive-programming/interfatecs/1_2016/i.cpp ================================================ #include #include using namespace std; int main() { double br, ext, h, gastobr, gastoext, cam; cin >> br >> ext >> h >> gastobr >> gastoext >> cam; double bang = (br * h * (1 - gastobr / 100) * 1.01); bang += (br * h * (1 - gastobr / 100) * 1.01 * 1.01 * 1.01); bang += (br * h * (1 - gastobr / 100)* 1.01 * 1.01); double bang2 = 0; bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01); bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01* 1.01); bang2 += (ext * h * cam * (1 - gastoext / 100)* 1.01* 1.01* 1.01); printf("%.2fBR %.2fES\n", (bang), bang2); return 0; } ================================================ FILE: competitive-programming/interfatecs/1_2018/a.cpp ================================================ // A #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #define DEBUG #ifdef DEBUG #define debug(args...) { cerr << #args << ": "; dbg,args; cerr << endl; } struct debugger { template debugger& operator , (const T& v) { cerr << v << " "; return *this; } } dbg; #else #define debug(args...) #endif bool maior(const pair &a, const pair &b) { if (a.second == b.second) { return a.first < b.first; } else { return a.second > b.second; } } int main(void) { ios::sync_with_stdio(false); int N; vector quantidades(61, 0); vector< pair > pares; vector selecionados; cin >> N; for (int i = 0; i < N; i++) { for (int j = 0; j < 6; j++) { int s; cin >> s; quantidades[s] += 1; } } for (int i = 1; i <= 60; i++) { pares.push_back(make_pair(i, quantidades[i])); } sort(pares.begin(), pares.end(), maior); for (int i = 0; i < 6; i++) { int n; cin >> n; selecionados.push_back(pares[n - 1].first); } cout << selecionados[0]; for (int i = 1; i < 6; i++) { cout << " " << selecionados[i]; } cout << endl; return EXIT_SUCCESS; } ================================================ FILE: competitive-programming/interfatecs/1_2018/b.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef DEBUG #define debug(args...) { cerr << #args << ": "; dbg,args; cerr << endl; } struct debugger { template debugger& operator , (const T& v) { cerr << v << " "; return *this; } } dbg; #else #define debug(args...) #endif int main(void) { ios::sync_with_stdio(false); char C; int N; int TA = 0, TV = 0; cin >> C >> ws >> N; for (int i = 0; i < N; i++) { int n; cin >> n; if (C == 'V') { TV += n; C = 'A'; } else { TA += n; C = 'V'; } } cout << "VOCE: " << TV << " AMIGO: " << TA << endl; return EXIT_SUCCESS; } ================================================ FILE: competitive-programming/interfatecs/1_2018/c.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef DEBUG #define debug(args...) { cerr << #args << ": "; dbg,args; cerr << endl; } struct debugger { template debugger& operator , (const T& v) { cerr << v << " "; return *this; } } dbg; #else #define debug(args...) #endif int main(void) { ios::sync_with_stdio(false); int sum = 0; for (int i = 0; i < 3; i++) { int T, Q; cin >> T >> Q; sum += T / Q; } cout << sum << endl; return EXIT_SUCCESS; } ================================================ FILE: competitive-programming/interfatecs/1_2018/d.py ================================================ palavra = input() direcoes = input().split(' ') l, c = list(map(int, input().split(' '))) mat = [] locais_da_primeira_letra = [] for i in range(l): linha = [] for j, letra in enumerate(input()): linha.append(letra) if letra == palavra[0]: locais_da_primeira_letra.append((i, j)) mat.append(linha) def direction(letter): if letter == 'd': return (0, 1) elif letter == 'c': return (-1, 0) elif letter == 'b': return (1, 0) else: return (0, -1) def letra_correta(i, j, pc): return 0 <= i < l and 0 <= j < c and mat[i][j] == pc def procura(visitados, i, j, palavra, sequencia): if palavra == '': return sequencia result = None if (i, j) not in visitados and letra_correta(i, j, palavra[0]): for direcao in direcoes: di, dj = direction(direcao) result = procura(visitados + [(i, j)], i + di, j + dj, palavra[1:], sequencia + [(i + 1, j + 1)]) if result != None: break return result result = None for i, j in locais_da_primeira_letra: result = procura([], i, j, palavra, []) if result != None: break if result != None: print(','.join(list(map(str, result))).replace(' ','') + '.') else: print('impossivel!') ================================================ FILE: competitive-programming/interfatecs/1_2018/e.py ================================================ linha = input() linha = linha.replace('PQ', '').replace(' ', '') linha_final = '' especiais = '?.,!' for i in range(len(linha)): if linha[i] == 'R': if linha[i + 1] in especiais: pass else: linha_final += ' ' else: linha_final += linha[i] print(linha_final) ================================================ FILE: competitive-programming/interfatecs/1_2018/f.py ================================================ codigo_set = set() codido_set_saiu = set() s = input() codigos = input().split(' ') for codigo in codigos: codigo_set.add(codigo) i = input() saidas = input().split(' ') A = 0 I = 0 R = 0 for saida in saidas: if saida in codigo_set: if saida in codido_set_saiu: R += 1 else: A += 1 codido_set_saiu.add(saida) else: if saida in codido_set_saiu: R += 1 else: I += 1 codido_set_saiu.add(saida) print('%d A' % A) print('%d I' % I) print('%d R' % R) ================================================ FILE: competitive-programming/interfatecs/1_2018/g.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef DEBUG #define debug(args...) { cerr << #args << ": "; dbg,args; cerr << endl; } struct debugger { template debugger& operator , (const T& v) { cerr << v << " "; return *this; } } dbg; #else #define debug(args...) #endif int main(void) { ios::sync_with_stdio(false); string line; char c = '\n'; int qc = 0, ic, jc; char d = '\n'; int qd = 0, id, jd; int z = 0; while (getline(cin, line)) { for (int i = 0; i < line.length(); i++) { if (c == '\n') { c = line[i]; } else if (c != line[i] && d == '\n') { d = line[i]; } if (line[i] == c) { qc += 1; ic = z + 1; jc = i + 1; } else { qd += 1; id = z + 1; jd = i + 1; } } z += 1; } if (qc < qd) { cout << "LINHA " << ic << " COLUNA " << jc << endl; } else { cout << "LINHA " << id << " COLUNA " << jd << endl; } return EXIT_SUCCESS; } ================================================ FILE: competitive-programming/interfatecs/1_2018/h.cpp ================================================ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef DEBUG #define debug(args...) { cerr << #args << ": "; dbg,args; cerr << endl; } struct debugger { template debugger& operator , (const T& v) { cerr << v << " "; return *this; } } dbg; #else #define debug(args...) #endif int A; double R = 0.0; double saldo[32], resgate[32]; int main(void) { ios::sync_with_stdio(false); for(int i = 1; i <= 31; i++) { saldo[i] = 0.0; resgate[i] = 0.0; } cin >> A >> R; int temp; while(cin >> temp) { cin >> saldo[temp]; } double valor_restante = R; double cont = 0.0; for(int dia = 1; dia <= 31; dia++) cont += saldo[dia]; if(cont < R) { printf("INSUFICIENTE\n"); return 0; } for(int dia = A; valor_restante >= 0.0 && dia >= 1; dia--) { if(saldo[dia] <= valor_restante) { resgate[dia] = saldo[dia]; valor_restante -= resgate[dia]; } else { resgate[dia] = valor_restante; valor_restante = 0.0; } } for(int dia = 31; valor_restante >= 0.0 && dia > A; dia--) { if(saldo[dia] <= valor_restante) { resgate[dia] = saldo[dia]; valor_restante -= resgate[dia]; } else { resgate[dia] = valor_restante; valor_restante = 0.0; } } for(int dia = 1; dia <= 31; dia++) { if(resgate[dia] > 0.0) printf("%d %.2f (resgate de %.2f)\n", dia, saldo[dia] - resgate[dia], resgate[dia]); } return EXIT_SUCCESS; } ================================================ FILE: competitive-programming/interfatecs/1_2018/i.py ================================================ boletos = [] try: while True: boletos.append(input()) except EOFError: pass def data(data_string): ano = data_string[4:6] mes = data_string[2:4] dia = data_string[0:2] return int(''.join([ano, mes, dia])) def analisar_boleto(boleto): vencimento = boleto[4:10] pagamento = boleto[22:28] valor_inteiro = boleto[10:16] valor_decimal = boleto[16:18] valor = int(valor_inteiro) + int(valor_decimal) / 100 if data(pagamento) > data(vencimento): return 0, valor else: return valor, 0 total_ad = 0 total_id = 0 for boleto in boletos: ad, id = analisar_boleto(boleto) total_ad += ad total_id += id print('%.2f-ADIMPLENTE' % total_ad) print('%.2f-INADIMPLENTE' % total_id) ================================================ FILE: competitive-programming/interfatecs/1_2018/j.cpp ================================================ // J #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; #ifdef DEBUG #define debug(args...) { cerr << #args << ": "; dbg,args; cerr << endl; } struct debugger { template debugger& operator , (const T& v) { cerr << v << " "; return *this; } } dbg; #else #define debug(args...) #endif bool processado[101][101]; int mapa[101][101]; int L, C, Y, X, D; int cont = 0; void preenche(int y, int x) { if(!processado[y][x]) { processado[y][x] = true; cont++; if(x + 1 <= C && abs(mapa[Y][X] - mapa[y][x+1]) <= D) preenche(y, x+1); if(x - 1 >= 1 && abs(mapa[Y][X] - mapa[y][x-1]) <= D) preenche(y, x-1); if(y + 1 <= L && abs(mapa[Y][X] - mapa[y+1][x]) <= D) preenche(y+1, x); if(y - 1 >= 1 && abs(mapa[Y][X] - mapa[y-1][x]) <= D) preenche(y-1, x); } } int main(void) { ios::sync_with_stdio(false); memset(processado, false, sizeof processado); cin >> L >> C >> Y >> X >> D; for(int i = 1; i <= L; i++) { for(int j = 1; j <= C; j++) { cin >> mapa[i][j]; } } preenche(Y, X); cout << cont << endl; return EXIT_SUCCESS; } ================================================ FILE: competitive-programming/spoj-br/aero.cpp ================================================ #include #include #include #include using namespace std; int main() { int n1, n2, test=1; cin >> n1 >> n2; while (n1 + n2 != 0) { vector< pair > v; while (n2--) { int line1, line2; cin >> line1 >> line2; v.push_back(make_pair(line1, line2)); } map mapper; for (int i = 0; i < v.size(); i++) { if (mapper.find(v[i].first) != mapper.end()) mapper.find(v[i].first)->second++; else mapper[v[i].first] = 1; if (mapper.find(v[i].second) != mapper.end()) mapper.find(v[i].second)->second++; else mapper[v[i].second] = 1; } vector lines; for (map::iterator it = mapper.begin(); it != mapper.end(); ++it) { lines.push_back(it->second); } int max=0; for (int i = 0; i < lines.size(); i++) if (lines[i] > max) max = lines[i]; cout << "Teste " << test << endl; for (int i = 0; i < lines.size(); i++) if (lines[i] == max) printf("%d ", i+1); printf("\n\n"); test++; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/spoj-br/bafo.cpp ================================================ // BAFO #include #include using namespace std; int main() { int n, t_beto=0, t_aldo=0, x, y, counter=1; string result; cin >> n; if(n == 0) return 0; while(n != 0) { for (int i = 0; i < n; i++) { cin >> x >> y; t_aldo += x; t_beto += y; } if (t_aldo > t_beto) result = "Aldo"; else result = "Beto"; cout << "Teste " << counter << endl; cout << result << endl << endl; cin >> n; counter++; t_beto = 0; t_aldo = 0; } } ================================================ FILE: competitive-programming/spoj-br/bapostas.cpp ================================================ #include using namespace std; int main() { int n, num, total=0; cin >> n; while (n) { for (i = 0; i < n; i++) { cin >> num; } cin >> n; } return 0; } ================================================ FILE: competitive-programming/spoj-br/bit.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int total, test=1; cin >> total; while (total != 0) { int num = 4;; vector v; while (num--) { v.push_back(0); } while (total > 0) { if (total >= 50) { total -= 50; v[0]++; } else if (total >= 10) { total -= 10; v[1]++; } else if (total >= 5) { total -= 5; v[2]++; } else { total -= 1; v[3]++; } } cout << "Teste " << test << endl; for (int i = 0; i < 4; i++) { cout << v[i] << " "; } cout << endl << endl; test++; cin >> total; } return 0; } ================================================ FILE: competitive-programming/spoj-br/calcula.cpp ================================================ #include using namespace std; int main() { int n, total=0, test=1; cin >> n; while (n != 0) { for (int i = 0; i < n; i++) { int temp; cin >> temp; total += temp; } cout << "Teste " << test << endl; cout << total << endl << endl; test++; cin >> n; total = 0; } return 0; } ================================================ FILE: competitive-programming/spoj-br/calculadora.cpp ================================================ // CALCU11 #include #include using namespace std; int main() { int n, result; long double number, total=1; char op; cin >> n; while (n--) { cin >> number; cin >> op; if (op == '*') total *= number; else total /= number; } cout << fixed << setprecision(0) << total; return 0; } ================================================ FILE: competitive-programming/spoj-br/dentista.cpp ================================================ // JDENTIST #include #include using namespace std; int main() { int n, x, y, counter=0, status=1; vector consult; vector< vector > memo; cin >> n; while (n--) { cin >> x; cin >> y; if (!memo.empty()) { for (int i = 0; i < memo.size(); i++) { if ((x < memo[i][0] && y <= memo[i][0]) || (x >= memo[i][1] && y > memo[i][1])) { } else { status = 0; } } } if (status) { counter++; consult.push_back(x); consult.push_back(y); memo.push_back(consult); } status = 1; consult.clear(); } for(int i = 0; i < memo.size(); i++) { cout << memo[i][0] << " - " << memo[i][1] << endl; } cout << counter; } ================================================ FILE: competitive-programming/spoj-br/desculpa.cpp ================================================ #include #include using namespace std; int max(int a, int b) { return (a > b)? a : b; } int knapsack(int W, int wt[], int val[], int n) { int i, w; int K[n+1][W+1]; for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i==0 || w==0) K[i][w] = 0; else if (wt[i-1] <= w) K[i][w] = max(val[i-1] + K[i-1][w-wt[i-1]], K[i-1][w]); else K[i][w] = K[i-1][w]; } } return K[n][W]; } int main() { int W, n, test=1; cin >> W >> n; while (W + n != 0) { int wt[n], val[n]; for (int i = 0; i < n; i++) { int x, y; cin >> x >> y; wt[i] = x; val[i] = y; } cout << "Teste " << test << endl; printf("%d", knapsack(W, wt, val, n)); cout << endl << endl; cin >> W >> n; test++; } return 0; } ================================================ FILE: competitive-programming/spoj-br/eleicoes1.cpp ================================================ #include #include #include #include using namespace std; int main() { int votos, i, num, maior, contagem, candidato; map mapa; map::iterator it; while(scanf("%d", &num) != EOF) { mapa.erase ( mapa.begin(), mapa.end()); maior = candidato = -1; contagem = 0; for (i = 0; i < num; i++){ scanf("%d", &votos); if (mapa.find(votos) == mapa.end()) mapa[votos] = 1; else mapa[votos]++; } for ( it=mapa.begin(); it != mapa.end(); it++ ){ if ((*it).second > maior) { maior = (*it).second; candidato = (*it).first; } } cout << "\n" << candidato << "\n"; } return 0; } ================================================ FILE: competitive-programming/spoj-br/eleicoes2.cpp ================================================ #include #include #include using namespace std; int main() { int n, temp; vector v; cin >> n; while (n--) { cin >> temp; v.push_back(temp); } sort(v.begin(), v.end()); vector< pair > vetorzin; vetorzin.push_back(make_pair(1, v[0])); for (int i = 1; i < v.size(); i++) { int found = 0; for (int j = 0; j < vetorzin.size(); j++) { if (vetorzin[j].second == v[i]) { vetorzin[j].first++; found = 1; break; } } if (!found) vetorzin.push_back(make_pair(1, v[i])); } sort(vetorzin.begin(), vetorzin.end()); cout << vetorzin.back().second << endl; return 0; } ================================================ FILE: competitive-programming/spoj-br/estagio.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int n, test=1; cin >> n; while (n != 0) { vector< pair > v; while (n--) { int cod, media; cin >> cod >> media; v.push_back(make_pair(cod, media)); } int max = 0; for (int i = 0; i < v.size(); i++) if (v[i].second > max) max = v[i].second; cout << "Turma " << test << endl; for (int i = 0; i < v.size(); i++) if (v[i].second == max) cout << v[i].first << " "; cout << endl << endl; cin >> n; test++; } return 0; } ================================================ FILE: competitive-programming/spoj-br/fatorial.cpp ================================================ #include #include #include using namespace std; int custom_factorial(int n) { int temp, result, flag; vector v(1000000); v[0] = 1; for (int i = 1; i <= n; i++) { if (n < 4) v[i] = v[i - 1] * i; else { result = v[i - 1] * i; flag = 1; while (flag) { temp = result % 10; if (temp != 0) { v[i] = temp; flag = 0; } else { result /= 10; } } } } return v[n]; } int main() { int n, instance=1; while (scanf("%i", &n) != 0) { int result = custom_factorial(n); cout << "Instancia " << instance << endl; cout << result << endl; instance++; } return 0; } ================================================ FILE: competitive-programming/spoj-br/feyman.cpp ================================================ // FEYNMAN #include using namespace std; int quad(int n) { if (n == 1) return 1; return ((n * n) + quad(n-1)); } int main() { int n; cin >> n; while(n != 0) { cout << quad(n) << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/spoj-br/fliperam.cpp ================================================ #include #include #include using namespace std; int main() { int n1, n2, temp; vector v; cin >> n1 >> n2; int n = n1; while (n--) { cin >> temp; v.push_back(temp); } sort(v.begin(), v.end(), greater()); for (int i = 0; i < n2; i++) { cout << v[i] << endl; } return 0; } ================================================ FILE: competitive-programming/spoj-br/gangorra.cpp ================================================ // JGANGO14 #include using namespace std; int main() { int p1, p2, c1, c2; cin >> p1; cin >> c1; cin >> p2; cin >> c2; if(p1 * c1 == p2 * c2) { cout << 0; } else if(p1 * c1 > p2 * c2) { cout << -1; } else { cout << 1; } return 0; } ================================================ FILE: competitive-programming/spoj-br/guardacosta.cpp ================================================ // GUARDCOS #include #include using namespace std; int main() { float d, f, g, n, distancia_perpendicular = 12; while(scanf("%f %f %f", &d, &f, &g) != EOF) { n = sqrt((144 + d*d)); if ((12 / f) < (n / g)) cout << 'N' << endl; else cout << 'S' << endl; } return 0; } ================================================ FILE: competitive-programming/spoj-br/impedido.cpp ================================================ #include #include #include using namespace std; int main() { int n, m, temp1, temp2; char result; vector atacantes; vector defensores; cin >> n; cin >> m; while (n + m != 0) { for(int i = 0; i < n; i++) { cin >> temp1; atacantes.push_back(temp1); } for(int j = 0; j < m; j++) { cin >> temp2; defensores.push_back(temp2); } sort(atacantes.begin(), atacantes.end()); sort(defensores.begin(), defensores.end()); if (atacantes[0] < defensores[1]) cout << "Y" << endl; else cout << "N" << endl; cin >> n; cin >> m; atacantes.clear(); defensores.clear(); } return 0; } ================================================ FILE: competitive-programming/spoj-br/letra.cpp ================================================ // LETRA14 #include #include #include #include #include #include #include using namespace std; int main() { int end, start=0, n=0; float total; string frase, letra, last; vector palavras; getline(cin, letra); getline(cin, frase); istringstream iss(frase); copy(istream_iterator(iss), istream_iterator(), back_inserter(palavras)); for(int i = 0; i < palavras.size(); i++) { if(palavras[i].find(letra) != string::npos) n++; } total = palavras.size(); cout << fixed << setprecision(1) << (n / total) * 100; return 0; } ================================================ FILE: competitive-programming/spoj-br/loopmusi.cpp ================================================ #include #include using namespace std; int main() { int n, picos=0, temp; vector loop; cin >> n; while (n != 0) { for (int i = 0; i < n; i++) { cin >> temp; loop.push_back(temp); } loop.push_back(loop[0]); loop.push_back(loop[1]); for (int i = 1; i <= n; i++) { if ((loop[i] > loop[i-1] && loop[i] > loop[i+1]) || (loop[i] < loop[i-1] && loop[i] < loop[i+1])) picos++; } cout << picos << endl; picos = 0; loop.clear(); cin >> n; } return 0; } ================================================ FILE: competitive-programming/spoj-br/lua.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int n1, n2, test=1; cin >> n1 >> n2; while (n1 + n2 != 0) { vector v; for (int i = 0; i < n1; i++) { int temp; cin >> temp; v.push_back(temp); } int total = 0; for (int i = 0; i < n2; i++) total += v[i]; int max = (total / n2); int min = (total / n2); for (int i = n2; i < n1; i++) { total -= v[i-n2]; total += v[i]; int media = total / n2; if (media > max) max = media; if (media < min) min = media; } cout << "Teste " << test << endl; cout << min << " " << max << endl << endl; test++; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/spoj-br/macaco.cpp ================================================ #include #include #include using namespace std; int main() { int n, test=1; cin >> n; while (n) { vector< vector > retangulos; int temp; for (int i = 0; i < n; i++) { vector points; int time = 4; while (time--) { cin >> temp; points.push_back(temp); } retangulos.push_back(points); } int point1x=-10001, point1y=10001, point2x=10001, point2y=-10001; for (int i = 0; i < n; i++) { if (retangulos[i][0] > point1x && retangulos[i][1] < point1y) { point1x = retangulos[i][0]; point1y = retangulos[i][1]; } if (retangulos[i][1] < point2x && retangulos[i][3] > point2y) { point2x = retangulos[i][2]; point2y = retangulos[i][3]; } } cout << "Teste " << test << endl; int correct=0; for (int i = 0; i < n; i++) { if (point1x >= retangulos[i][0] && point1y <= retangulos[i][1] && point2x <= retangulos[i][2] && point2y >= retangulos[i][3]) correct++; } if (correct != n) cout << "nenhum" << endl << endl; else cout << point1x << " " << point1y << " " << point2x << " " << point2y << endl << endl; cin >> n; test++; } return 0; } ================================================ FILE: competitive-programming/spoj-br/minhoca.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; vector< vector > matrix; for (int i = 0; i < n1; i++) { vector v; for (int j = 0; j < n2; j++) { int temp; cin >> temp; v.push_back(temp); } matrix.push_back(v); } int max = 0; for (int i = 0; i < n1; i++) { int total = 0; for (int j = 0; j < n2; j++) { total += matrix[i][j]; } if (total > max) max = total; } for (int j = 0; j < n2; j++) { int total = 0; for (int i = 0; i < n1; i++) { total += matrix[i][j]; } if (total > max) max = total; } cout << max << endl; return 0; } ================================================ FILE: competitive-programming/spoj-br/miojo.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int t, n1, n2, result; cin >> t >> n1 >> n2; while (1) { if (n1 - n2 == t) { result = n1; break; } if (n2 - n1 == t) { result = n2; break; } if (n1 < n2) n1 += n1; else n2 += n2; } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/spoj-br/obi.cpp ================================================ // OBI8 #include using namespace std; int main() { int competidores, pontos, p1, p2, count=0; cin >> competidores; cin >> pontos; while (competidores--) { cin >> p1; cin >> p2; if (p1 + p2 >= pontos) count++; } cout << count; return 0; } ================================================ FILE: competitive-programming/spoj-br/obihanoi.cpp ================================================ #include #include #include #include #include #include using namespace std; int main() { int n, test=1; cin >> n; while (n != 0) { long long int times = pow(2, n) - 1; cout << "Teste " << test << endl; cout << times << endl << endl; times=0; test++; cin >> n; } return 0; } ================================================ FILE: competitive-programming/spoj-br/parprox.cpp ================================================ #include #include #include #include #include #include #include using namespace std; int main() { int n; vector< pair > vec; vector v; cin >> n; if (n <= 1) { cout << 0 << endl; return 0; } while (n--) { int n1, n2; cin >> n1 >> n2; vec.push_back(make_pair(n1, n2)); } for (int i = 0; i < vec.size()-1; i++) { for (int j = i + 1; j < vec.size(); j++) { int x = vec[i].first - vec[j].first; int y = vec[i].second - vec[j].second; if (x < 0) x *= (-1); if (y < 0) y *= (-1); double result = hypot(x, y); v.push_back(result); } } sort(v.begin(), v.end()); cout.precision(3); cout << fixed << v[0] << endl; return 0; } ================================================ FILE: competitive-programming/spoj-br/peca.cpp ================================================ // PECA7 #include #include #include #include using namespace std; int main() { int time, result, temp; vector numbers; cin >> time; result = time; for(int i = 0; i < time-1; i++) { cin >> temp; numbers.push_back(temp); } sort(numbers.begin(), numbers.end()); for(int j = 0; j < numbers.size(); j++) { if (j+1 != numbers[j]) { result = j+1; break; } } cout << result; return 0; } ================================================ FILE: competitive-programming/spoj-br/primo.cpp ================================================ // br.spoj.com/problems/PRIMO/ #include #include using namespace std; long long int is_prime(int num) { int number = num; int total_divisivel = 0; if (num < 0) number = -(number); if (number == 0 || number == 1) return 0; else if (number == 2) return 1; else if (number % 2 == 0) return 0; int s = sqrt(number); for (int i = 3; i <= s; i += 2) if (number % i == 0) return 0; return 1; } int main() { long long int n; cin >> n; if (is_prime(n)) cout << "sim" << endl; else cout << "nao" << endl; return 0; } ================================================ FILE: competitive-programming/spoj-br/rumo9s.cpp ================================================ #include using namespace std; int main() { int n; cin >> n; while (n != 0) { cin >> n; } return 0; } ================================================ FILE: competitive-programming/spoj-br/saldo.cpp ================================================ #include #include using namespace std; int main() { int n, test=1; cin >> n; while (n != 0) { for (int i = 0; i < n; i++) { } cout << "Teste " + test << endl; cin >> n; test++; } return 0; } ================================================ FILE: competitive-programming/spoj-br/saldo13.cpp ================================================ // SALDO13 #include using namespace std; int main() { int n, s, menor_saldo, total, temp; cin >> n; cin >> s; menor_saldo = s; total = s; while(n--) { cin >> temp; total += temp; if (total < menor_saldo) menor_saldo = total; } cout << menor_saldo; return 0; } ================================================ FILE: competitive-programming/spoj-br/sorvete.cpp ================================================ #include #include #include using namespace std; int main() { int test=1, s, p; vector< pair > vetorzin; vector< pair > v; cin >> p >> s; while (s + p != 0) { for (int i = 0; i < s; i++) { int n1, n2; cin >> n1 >> n2; vetorzin.push_back(make_pair(n1, n2)); } sort(vetorzin.begin(), vetorzin.end()); v.push_back(make_pair(vetorzin[0].first, vetorzin[0].second)); for (int i = 1; i < s; i++) { if (v.back().second < vetorzin[i].first) v.push_back(make_pair(vetorzin[i].first, vetorzin[i].second)); else if (v.back().second < vetorzin[i].second) v.back().second = vetorzin[i].second; } cout << "Teste " << test << endl; for (int i = 0; i < v.size(); i++) { cout << v[i].first << " " << v[i].second << endl; } cout << endl; v.clear(); vetorzin.clear(); test++; cin >> p >> s; } return 0; } ================================================ FILE: competitive-programming/spoj-br/sudoku.cpp ================================================ // SPOJ Problem Set (seletivas) - SUDOIME #include #include #include #include using namespace std; string correct_sudoku(vector< vector > matrix) { vector vetorzin_1; vector vetorzin_2; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { vetorzin_1.push_back(matrix[i][j]); vetorzin_2.push_back(matrix[j][i]); } sort(vetorzin_1.begin(), vetorzin_1.end()); sort(vetorzin_2.begin(), vetorzin_2.end()); for (int j = 0; j < 9; j++) { if ((vetorzin_1[j] != j+1) || (vetorzin_2[j] != j+1)) return "NAO"; } vetorzin_1.clear(); vetorzin_2.clear(); } } int main() { int n, counter=1, temp; string result="SIM"; vector vetor; vector< vector > matrix; cin >> n; while(n--) { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cin >> temp; vetor.push_back(temp); } matrix.push_back(vetor); vetor.clear(); } result = correct_sudoku(matrix); cout << "Instancia " << counter << endl; cout << result << endl; result="SIM"; matrix.clear(); counter++; } return 0; } ================================================ FILE: competitive-programming/spoj-br/telefone.cpp ================================================ // TEL8 #include #include using namespace std; int main() { string number, result=""; cin >> number; for(int i = 0; i < number.length(); i++) if (number[i] == 'A' || number[i] == 'B' || number[i] == 'C') result += "2"; else if (number[i] == 'D' || number[i] == 'E' || number[i] == 'F') result += "3"; else if (number[i] == 'G' || number[i] == 'H' || number[i] == 'I') result += "4"; else if (number[i] == 'J' || number[i] == 'K' || number[i] == 'L') result += "5"; else if (number[i] == 'M' || number[i] == 'N' || number[i] == 'O') result += "6"; else if (number[i] == 'P' || number[i] == 'Q' || number[i] == 'R' || number[i] == 'S') result += "7"; else if (number[i] == 'T' || number[i] == 'U' || number[i] == 'V') result += "8"; else if (number[i] == 'W' || number[i] == 'X' || number[i] == 'Y' || number[i] == 'Z') result += "9"; else result += number[i]; cout << result; return 0; } ================================================ FILE: competitive-programming/spoj-br/transporte.cpp ================================================ // TRANSP11 #include using namespace std; int main() { int a, b, c, x, y, z; cin >> a >> b >> c >> x >> y >> z; if ((a > x) || (b > y) || (c > z)) cout << 0; else { cout << ((x/a) * (y/b) * (z/c)); } return 0; } ================================================ FILE: competitive-programming/spoj-br/troco13.cpp ================================================ #include #include #include #include #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; int total = 0; while (n2--) { int n; cin >> n; if (total + n <= n1) total += n; } if (total == n1) cout << "S" << endl; else cout << "N" << endl; return 0; } ================================================ FILE: competitive-programming/spoj-br/vivo.cpp ================================================ #include #include using namespace std; int main() { int n1, n2, test=1; scanf("%d %d", &n1, &n2); while (n1 + n2 != 0) { int temp; vector v; for (int i = 0; i < n1; i++) { scanf("%d", &temp); v.push_back(temp); } while (n2--) { int n, j, erasing=0; scanf("%d %d", &n, &j); for (int i = 0; i < n; i++) { int t; scanf("%d", &t); if (t != j) { v.erase(v.begin() + i - erasing); erasing++; } } } cout << "Teste " << test << endl; cout << v[0] << endl << endl; test++; scanf("%d %d", &n1, &n2); } return 0; } ================================================ FILE: competitive-programming/spoj-br/wcw.cpp ================================================ #include #include using namespace std; vector merge(vector& vec, const vector& left, const vector& right) { vector result; unsigned left_it = 0, right_it = 0; while (left_it < left.size() && right_it < right.size()) { if (left[left_it] < right[right_it]) { result.push_back(left[left_it]); left_it++; } else { result.push_back(right[right_it]); right_it++; } } while (left_it < left.size()) { result.push_back(left[left_it]); left_it++; } while (right_it < right.size()) { result.push_back(right[right_it]); right_it++; } vec = result; return vec; } vector merge_sort(vector& vec) { if (vec.size() == 1) return vec; vector::iterator middle = vec.begin() + (vec.size() / 2); vector left(vec.begin(), middle); vector right(middle, vec.end()); left = merge_sort(left); right = merge_sort(right); return merge(vec, left, right); } int main() { int n; cin >> n; while (n--) { int x, temp; cin >> x; vector v; while (x--) { cin >> temp; v.push_back(temp); } cout << merge_sort(v) << endl; } return 0; } ================================================ FILE: competitive-programming/timus/a+b_problem.cpp ================================================ // http://acm.timus.ru/problem.aspx?space=1&num=1000 #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; cout << n1 + n2 << endl; } ================================================ FILE: competitive-programming/ucoder/armstrong_numbers.cpp ================================================ #include #include #include #include #include using namespace std; int main() { long int n; scanf("%li", &n); vector vetor; while (n != 0) { int total = 0, temp = n, teste, result=0; while (temp != 0) { teste = temp % 10; vetor.push_back(teste); temp = temp / 10; } for (int i = 2; i < 10; i++) { total = 0; for (int j = 0; j < vetor.size(); j++) { total += pow(vetor[j], i); } if (total == n) { result = i; break; } } if (result) cout << result << endl; else cout << "N" << endl; scanf("%li", &n); vetor.clear(); } return 0; } ================================================ FILE: competitive-programming/ucoder/historico_de_comandos.cpp ================================================ #include #include #include using namespace std; int main() { int n, x; while (cin >> n && n != 0) { int total = 0; map m; vector v; int aux; for (int i = 0; i < n; ++i) { cin >> x; v.push_back(x); m[x] = x; } map::iterator it; for (int i = 0; i < n; ++i) { aux = v[i]; total += m[aux]; for (it = m.begin(); it != m.end(); ++it) { it->second++; } m[aux] = 1; } cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/ucoder/imperador_cassius.cpp ================================================ #include using namespace std; int main() { int n1, n2, n=1; while (cin >> n1 && n1 != 0) { cin >> n2; cout << "Instancia " << n << endl; if (n1 == 1 && n2 == 2) cout << "segundo" << endl; else if (n1 == 1 && n2 == 3) cout << "primeiro" << endl; else if (n1 == 2 && n2 == 1) cout << "primeiro" << endl; else if (n1 == 2 && n2 == 3) cout << "segundo" << endl; else if (n1 == 3 && n2 == 1) cout << "segundo" << endl; else if (n1 == 3 && n2 == 2) cout << "primeiro" << endl; else cout << "empate" << endl; cout << endl; n++; } return 0; } ================================================ FILE: competitive-programming/ucoder/matriz_esparsa.cpp ================================================ #include using namespace std; int main() { int n, x, total, zeros, medium; cin >> n; while (n--) { cin >> x; total = x * x; zeros = total - (3 * x - 2); medium = total / 2; if (zeros > medium) cout << "S " << zeros << endl; else cout << "N " << zeros << endl; } return 0; } ================================================ FILE: competitive-programming/ucoder/obi.cpp ================================================ #include using namespace std; int main() { int n, n1, n2, total, counter = 0; cin >> n >> total; while (n--) { cin >> n1 >> n2; if (n1 + n2 >= total) counter++; } cout << counter << endl; return 0; } ================================================ FILE: competitive-programming/ucoder/tsetse.cpp ================================================ #include #include using namespace std; int main() { int n1, n2, x, instance = 1; cin >> n1 >> n2; while (n1 + n2 != 0) { if (n1 == 0 || n2 == 0) { cout << "Instancia " << instance << endl; cout << "sim" << endl; } else { vector v; vector< vector > matrix; for (int i = 0; i < n1; ++i) { for (int j = 0; j < n2; ++j) { cin >> x; v.push_back(x); } matrix.push_back(v); v.clear(); } int n, i = 0, j = 0, counter = 1; while (true) { n = matrix[i][j]; if (n == 1) { if (i == 0) { break; } else { matrix[i][j] = 0; i--; } } else if (n == 2) { if (i == 0 || j == n2-1) { break; } else { matrix[i][j] = 0; i--; j++; } } else if (n == 3) { if (j == n2-1) { break; } else { matrix[i][j] = 0; j++; } } else if (n == 4) { if (j == n2-1 || i == n1-1) { break; } else { matrix[i][j] = 0; j++; i++; } } else if (n == 5) { if (i == n1-1) { break; } else { matrix[i][j] = 0; i++; } } else if (n == 6) { if (j == 0 || i == n1-1) { break; } else { matrix[i][j] = 0; j--; i++; } } else if (n == 7) { if (j == 0) { break; } else { matrix[i][j] = 0; j--; } } else if (n == 8) { if (j == 0 || i == 0) { break; } else { matrix[i][j] = 0; j--; i--; } } counter++; if (matrix[i][j] == 0) break; } cout << "Instancia " << instance << endl; if (counter == n1 * n2) cout << "sim" << endl; else cout << "nao" << endl; } cin >> n1 >> n2; if (n1 + n2 != 0) cout << endl; instance++; } return 0; } ================================================ FILE: competitive-programming/uri/3d_virtual_museum.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2548 #include #include #include using namespace std; int main() { int N, M, num, total; vector V; while (cin >> N >> M) { total = 0; while (N--) { cin >> num; V.push_back(num); } sort(V.begin(), V.end(), greater()); for (int i = 0; V.size() > 0 && i < M; i++) total += V[i]; cout << total << endl; V.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/a_long_time_ago.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1962 #include using namespace std; int main() { int n; cin >> n; long long int n1; while (n--) { cin >> n1; if (n1 >= 2015) { cout << n1 - 2014 << " A.C." << endl; } else { cout << 2015 - n1 << " D.C." << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/above_average.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1214 #include #include #include using namespace std; int main() { int n; cin >> n; while (n--) { int x, temp; double total = 0; cin >> x; vector v; for (int i = 0; i < x; i++) { cin >> temp; v.push_back(temp); total += temp; } double average = total / x; double counter = 0; for (int i = 0; i < x; i++) if (v[i] > average) counter++; cout << fixed << setprecision(3) << (counter / x) * 100.00 << "%" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/above_secundary_diagonal.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1185 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter = 11, count = 0; for (int i = 0; i < 11; i++) { for (int j = 0; j < counter; j++) { total += v1[i][j]; count++; } counter--; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/above_the_main_diagonal.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1183 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter = 1, count = 0; for (int i = 0; i < 12; i++) { for (int j = counter; j < 12; j++) { total += v1[i][j]; count++; } counter++; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/abracadabra.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2484 #include #include using namespace std; int main() { string s; while (getline(cin, s)) { for (int i = 0; i < s.size(); i++) { for (int j = 0; j < i; j++) cout << " "; for (int j = 0; j < s.size()-i; j++) { if (j == 0) cout << s[j]; else cout << " " << s[j]; } cout << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/advancing_letters.cpp ================================================ #include using namespace std; int main() { string s1 = "abcdefghiz", s2 = "aaaaaaaaaa"; int counter = 0, counter1 = 0, counter2 = 0, counterz = 0; for (int i = 0; i < s1.size(); i++) counterz += 'z'; for (int i = 0; i < s1.size(); i++) counter1 += s1[i]; for (int i = 0; i < s2.size(); i++) counter2 += s2[i]; cout << counterz - counter1 + counter1 - counter2 << endl; cout << counterz << endl; cout << counter1 << endl; cout << counter2 << endl; for (int i = 0; i < s1.size(); i++) { counter += (s2[i] - s1[i]); } //cout << counter << endl; return 0; } ================================================ FILE: competitive-programming/uri/age_in_day.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1020 #include using namespace std; int main() { int time, year=0, month=0, day=0; cin >> time; while (time >= 365) { time -= 365; year++; } while (time >= 30) { time -= 30; month++; } while (time >= 1) { time -= 1; day++; } cout << year << " ano(s)" << endl; cout << month << " mes(es)" << endl; cout << day << " dia(s)" << endl; return 0; } ================================================ FILE: competitive-programming/uri/ages.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1154 #include #include using namespace std; int main() { int n, number=0; double total=0; cin >> n; while (n >= 0) { total += n; number++; cin >> n; } cout << fixed << setprecision(2) << total / number << endl; return 0; } ================================================ FILE: competitive-programming/uri/alarm_clock.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1103 #include using namespace std; int main() { int h1, m1, h2, m2, minutes=0; cin >> h1 >> m1 >> h2 >> m2; while (h1 + m1 + h2 + m2 != 0) { if (h1 == h2 && m1 == m2) { minutes = 1440; } else { if (h1 > h2) { if (m2 > m1) { minutes = 1440 - (h1 - h2) * 60 + (m2 - m1); } else if (m1 > m2) { minutes = 1440 - (h1 - h2) * 60 + (m2 - m1); } else { minutes = 1440 - (h1 - h2) * 60; } } else if (h2 > h1) { if (m1 > m2) { minutes = (h2 - h1) * 60 + m2 - m1; } else if (m2 > m1) { minutes = (h2 - h1) * 60 + m2 - m1; } else { minutes = (h2 - h1) * 60; } } else { if (m2 > m1) { minutes = m2 - m1; } else { minutes = 1440 + m2 - m1; } } } cout << minutes << endl; cin >> h1 >> m1 >> h2 >> m2; } return 0; } ================================================ FILE: competitive-programming/uri/alliteration.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1263 #include #include #include using namespace std; void split_by_space(vector &words, string phrase) { int index_start=0, length; string aux; for (int i = 0; i < phrase.size(); i++) { if (phrase[i] == ' ') { length = i - index_start; aux = phrase.substr(index_start, length); words.push_back(aux); index_start = i + 1; } else if (i == phrase.size()-1) { length = i - index_start + 1; aux = phrase.substr(index_start, length); words.push_back(aux); } } } int main() { string phrase; string alphabet = "ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyzABCDEFGHIJKLMNOPQRSTUVXWYZ"; vector words; while (getline(cin, phrase)) { vector alli; alli.push_back(0); split_by_space(words, phrase); char current_letter = words[0][0]; // first letter of the first word if (words.size() > 1) { for (int i = 1; i < words.size(); i++) { int letter_pos = alphabet.find(words[i][0]); if (current_letter == alphabet[letter_pos] || current_letter == alphabet[letter_pos + 26]) { alli.back()++; } else { alli.push_back(0); } current_letter = words[i][0]; } int counter = 0; for (int i = 0; i < alli.size(); i++) if (alli[i] > 0) counter++; cout << counter << endl; } else { cout << 0 << endl; } words.clear(); alli.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/andys_first_dictionary.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1215 #include #include #include #include using namespace std; vector parseString(string word) { vector v; int len = 0, base = 0, ascChar; for (int i = 0; i < word.size(); i++) { ascChar = word[i]; if (ascChar < 65 || (ascChar > 90 && ascChar < 97) || ascChar > 122) { v.push_back(word.substr(base, len)); base = i+1; len = -1; } len++; } v.push_back(word.substr(base, len)); return v; } string lowerCase(string word) { string lowerCaseWord = ""; char charac; int ascChar; for (int i = 0; i < word.size(); i++) { ascChar = word[i]; if (ascChar >= 65 && ascChar <= 90) { charac = ascChar + 32; lowerCaseWord += charac; } else { lowerCaseWord += word[i]; } } return lowerCaseWord; } int main() { string word, parsedWord; set s; vector v; while (cin >> word) { v = parseString(word); for (int i = 0; i < v.size(); i++) { parsedWord = lowerCase(v[i]); if (parsedWord != "" && parsedWord != " ") s.insert(parsedWord); } } for (set::iterator it = s.begin(); it != s.end(); ++it) cout << *it << endl; return 0; } ================================================ FILE: competitive-programming/uri/angry_ducks.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1163 #include #include #define PI 3.14159 #define g 9.80665 double rad(double angle) { return (angle / 180.0) * PI; } int main() { double h, alfa, v, t, Vx, Vy, x, aux1, aux2, p1, p2; int n; char character; while (scanf("%lf %lf %lf %d", &h, &p1, &p2, &n) > 0) { aux1 = (2*h)/g; for (; n > 0; n--) { scanf("%lf %lf", &alfa, &v); Vx = v * cosf(rad(alfa)); Vy = v * sinf(rad(alfa)); aux2 = Vy/g; t = sqrtf(aux1 + powf(aux2, 2)) + aux2; x = Vx * t; character = (x >= p1 && x <= p2) ? 'D': 'N'; printf("%.5lf -> %cUCK\n", x, character); } } return 0; } ================================================ FILE: competitive-programming/uri/animal.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1049 #include #include using namespace std; int main() { string s1, s2, s3; cin >> s1 >> s2 >> s3; if (s1 == "vertebrado") { if (s2 == "ave") { if (s3 == "carnivoro") { cout << "aguia" << endl; } else { cout << "pomba" << endl; } } else { if (s3 == "onivoro") { cout << "homem" << endl; } else { cout << "vaca" << endl; } } } else { if (s2 == "inseto") { if (s3 == "hematofago") { cout << "pulga" << endl; } else { cout << "lagarta" << endl; } } else { if (s3 == "hematofago") { cout << "sanguessuga" << endl; } else { cout << "minhoca" << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/approximate_number_of_primes.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2159 #include #include #include using namespace std; int main() { long long int n; long double min, max; cin >> n; min = n / log(n); max = min * 1.25506; cout << fixed << setprecision(1) << min << " " << max << endl; return 0; } ================================================ FILE: competitive-programming/uri/area.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1012 #include #include #include using namespace std; int main() { const double PI = 3.14159; float n1, n2, n3; cin >> n1 >> n2 >> n3; cout << fixed << setprecision(3) << "TRIANGULO: " << n1 * n3 / 2 << endl; cout << fixed << setprecision(3) << "CIRCULO: " << PI * pow(n3, 2) << endl; cout << fixed << setprecision(3) << "TRAPEZIO: " << (n1 + n2) * n3 / 2 << endl; cout << fixed << setprecision(3) << "QUADRADO: " << n2 * n2 << endl; cout << fixed << setprecision(3) << "RETANGULO: " << n1 * n2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/area_of_circle.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1002 #include #include #include using namespace std; int main() { const double PI = 3.14159; double r; cin >> r; cout << fixed << setprecision(4) << "A=" << PI * pow(r, 2) << endl; return 0; } ================================================ FILE: competitive-programming/uri/arranging_tasks.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1704 #include #include #include using namespace std; struct task { int V, T; }; bool sortByTime(task &ta1, task &ta2) { if (ta1.V >= ta2.V) return true; else if (ta1.V < ta2.V) return false; else return ta1.T <= ta2.T; } int main() { int N, H, V, T; while (cin >> N >> H) { vector tasks; while (N--) { cin >> V >> T; task ta; ta.V = V; ta.T = T; tasks.push_back(ta); } sort(tasks.begin(), tasks.end(), sortByTime); int value = 0; for (int i = 0; i < H && i < 10; i++) { if (tasks[i].T <= H) value += tasks[i].V; } cout << value << endl; } return 0; } ================================================ FILE: competitive-programming/uri/array_123.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1534 #include #include #include using namespace std; int main() { int n, one, two; while (cin >> n) { vector numbers; string num; one = 0; two = n-1; for (int i = 0; i < n; i++) { num = ""; for (int j = 0; j < n; j++) { if (one == j && one == two) num += "2"; else if (one == j) num += "1"; else if (two == j) num += "2"; else num += "3"; } one++; two--; numbers.push_back(num); } for (int i = 0; i < numbers.size(); i++) { cout << numbers[i] << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/array_change_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1175 #include #include using namespace std; int main() { vector v1; vector v2; int n, x; for (int i = 0; i < 20; i++) { cin >> n; v1.push_back(n); } for (int i = 19; i >= 0; i--) { x = v1[i]; v2.push_back(x); } for (int i = 0; i < 20; i++) cout << "N[" << i << "] = " << v2[i] << endl; return 0; } ================================================ FILE: competitive-programming/uri/array_fill_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1173 #include #include using namespace std; int main() { int n, count; cin >> n; vector v; while (count < 10) { v.push_back(n); n *= 2; count++; } for (int i = 0; i < 10; i++) { cout << "N[" << i << "] = " << v[i] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/array_fill_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1177 #include #include using namespace std; int main() { int n, counter=0; cin >> n; vector v; for (int i = 0; i < 1000; i++) { v.push_back(counter); if (counter == n-1) counter = 0; else counter++; } for (int i = 0; i < 1000; i++) { cout << "N[" << i << "] = " << v[i] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/array_fill_3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1178 #include #include #include using namespace std; int main() { double n; cin >> n; vector v; for (int i = 0; i < 100; i++) { v.push_back(n); n /= 2; } for (int i = 0; i < 100; i++) { cout << fixed << setprecision(4) << "N[" << i << "] = " << v[i] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/array_fill_4.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1179 #include #include using namespace std; bool is_full(vector &v) { if (v.size() == 5) return true; return false; } int main() { vector even; vector odd; int num; for (int i = 0; i < 15; i++) { cin >> num; if (num % 2 == 0) even.push_back(num); else odd.push_back(num); if (is_full(odd)) { for (int j = 0; j < 5; j++) cout << "impar[" << j << "] = " << odd[j] << endl; odd.clear(); } if (is_full(even)) { for (int j = 0; j < 5; j++) cout << "par[" << j << "] = " << even[j] << endl; even.clear(); } } for (int o_index = 0; o_index < odd.size(); o_index++) cout << "impar[" << o_index << "] = " << odd[o_index] << endl; for (int e_index = 0; e_index < even.size(); e_index++) cout << "par[" << e_index << "] = " << even[e_index] << endl; return 0; } ================================================ FILE: competitive-programming/uri/array_hash.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1257 #include #include using namespace std; int main() { int n, m; cin >> n; string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (n--) { cin >> m; int total = 0; string code; for (int i = 0; i < m; i++) { cin >> code; for (int j = 0; j < code.size(); j++) total += alphabet.find(code[j]) + i + j; } cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/array_replacement_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1172 #include #include using namespace std; int main() { int n; vector v; for (int i = 0; i < 10; i++) { cin >> n; if (n <= 0) v.push_back(1); else v.push_back(n); } for (int i = 0; i < 10; i++) { cout << "X[" << i << "] = " << v[i] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/array_selection_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1174 #include #include #include using namespace std; int main() { double n; vector v; for (int i = 0; i < 100; i++) { cin >> n; v.push_back(n); } for (int i = 0; i < 100; i++) if (v[i] <= 10) cout << fixed << setprecision(1) << "A[" << i << "] = " << v[i] << endl; return 0; } ================================================ FILE: competitive-programming/uri/as_abas_de_pericles.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2061 #include #include using namespace std; int main() { int n1, n2; string s; cin >> n1 >> n2; for (int i = 0; i < n2; i++) { cin >> s; if (s == "fechou") n1++; else n1--; } cout << n1 << endl; return 0; } ================================================ FILE: competitive-programming/uri/ascending_and_descending.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1113 #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; while(n1 != n2) { if (n1 > n2) { cout << "Decrescente" << endl; } else { cout << "Crescente" << endl; } cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/assigning_teams.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2345 #include #include #include using namespace std; int main() { int n; vector v; for (int i = 0; i < 4; i++) { cin >> n; v.push_back(n); } sort(v.begin(), v.end()); int diff1, diff2; diff1 = v[3] + v[0]; diff2 = v[2] + v[1]; if (diff1 > diff2) cout << diff1 - diff2 << endl; else cout << diff2 - diff1 << endl; return 0; } ================================================ FILE: competitive-programming/uri/automated_checking_machine.cpp ================================================ #include #include using namespace std; int main() { int n; vector v; char result = 'Y'; for (int i = 0; i < 5; i++) { cin >> n; v.push_back(n); } for (int i = 0; i < 5; i++) { cin >> n; if (n == v[i]) { result = 'N'; break; } } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/average_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1005 #include #include using namespace std; int main() { double a, b; cin >> a >> b; cout << fixed << setprecision(5) << "MEDIA = " << (a * 3.5 + b * 7.5) / 11 << endl; return 0; } ================================================ FILE: competitive-programming/uri/average_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1006 #include #include using namespace std; int main() { double a, b, c; cin >> a >> b >> c; cout << fixed << setprecision(1) << "MEDIA = " << (a * 2 + b * 3 + c * 5) / 10 << endl; return 0; } ================================================ FILE: competitive-programming/uri/average_3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1040 #include #include using namespace std; int main() { // weights 2, 3, 4 e 1 double n1, n2, n3, n4, n5; cin >> n1 >> n2 >> n3 >> n4; double final = (n1 * 2 + n2 * 3 + n3 * 4 + n4) / 10; cout << fixed << setprecision(1) << "Media: " << final << endl; if (final >= 7.0) { cout << "Aluno aprovado." << endl; } else if (final >= 5.0) { cin >> n5; cout << "Aluno em exame." << endl; cout << "Nota do exame: " << n5 << endl; final = (final + n5) / 2; if (final >= 5.0) { cout << "Aluno aprovado." << endl; } else { cout << "Aluno reprovado." << endl; } cout << fixed << setprecision(1) << "Media final: " << final << endl; } else { cout << "Aluno reprovado." << endl; } return 0; } ================================================ FILE: competitive-programming/uri/average_speed.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1304 #include #include using namespace std; int main() { return 0; } ================================================ FILE: competitive-programming/uri/back_to_high_school_physics.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1197 #include using namespace std; int main() { int n1, n2; while (scanf("%d %d", &n1, &n2) != EOF) cout << n1 * n2 * 2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/bacteria_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2356 #include #include using namespace std; int main() { string s1, s2; while (getline(cin, s1) && getline(cin, s2)) { if (s1.find(s2) == string::npos) cout << "Nao resistente" << endl; else cout << "Resistente" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/banknotes.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1018 #include using namespace std; int main() { int n1; cin >> n1; cout << n1 << endl; int total = n1; int cem=0, cinquenta=0, vinte=0, dez=0, cinco=0, dois=0, um=0; while (total >= 100) { total -= 100; cem++; } while (total >= 50) { total -= 50; cinquenta++; } while (total >= 20) { total -= 20; vinte++; } while (total >= 10) { total -= 10; dez++; } while (total >= 5) { total -= 5; cinco++; } while (total >= 2) { total -= 2; dois++; } while (total >= 1) { total -= 1; um++; } cout << cem << " nota(s) de R$ 100,00" << endl; cout << cinquenta << " nota(s) de R$ 50,00" << endl; cout << vinte << " nota(s) de R$ 20,00" << endl; cout << dez << " nota(s) de R$ 10,00" << endl; cout << cinco << " nota(s) de R$ 5,00" << endl; cout << dois << " nota(s) de R$ 2,00" << endl; cout << um << " nota(s) de R$ 1,00" << endl; return 0; } ================================================ FILE: competitive-programming/uri/banknotes_and_coins.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1021 #include using namespace std; int main() { float total; int cem=0, cinquenta=0, vinte=0, dez=0, cinco=0, dois=0, um=0; int cinquenta_centavos=0, vinte_e_cinco_centavos=0, dez_centavos=0, cinco_centavos=0, um_centavos=0; cin >> total; while (total >= 100) { total -= 100; cem++; } while (total >= 50) { total -= 50; cinquenta++; } while (total >= 20) { total -= 20; vinte++; } while (total >= 10) { total -= 10; dez++; } while (total >= 5) { total -= 5; cinco++; } while (total >= 2) { total -= 2; dois++; } while (total >= 1) { total -= 1; um++; } while (total >= 0.5) { total -= 0.50; cinquenta_centavos++; } while (total >= 0.25) { total -= 0.25; vinte_e_cinco_centavos++; } while (total >= 0.10) { total -= 0.10; dez_centavos++; } while (total >= 0.05) { total -= 0.05; cinco_centavos++; } while (total >= 0.01) { total -= 0.01; um_centavos++; } cout << "NOTAS:" << endl; cout << cem << " nota(s) de R$ 100.00" << endl; cout << cinquenta << " nota(s) de R$ 50.00" << endl; cout << vinte << " nota(s) de R$ 20.00" << endl; cout << dez << " nota(s) de R$ 10.00" << endl; cout << cinco << " nota(s) de R$ 5.00" << endl; cout << dois << " nota(s) de R$ 2.00" << endl; cout << "MOEDAS:" << endl; cout << um << " moeda(s) de R$ 1.00" << endl; cout << cinco_centavos << " moeda(s) de R$ 0.50" << endl; cout << vinte_e_cinco_centavos << " moeda(s) de R$ 0.25" << endl; cout << dez_centavos << " moeda(s) de R$ 0.10" << endl; cout << cinco_centavos << " moeda(s) de R$ 0.05" << endl; cout << um_centavos << " moeda(s) de R$ 0.01" << endl; return 0; } ================================================ FILE: competitive-programming/uri/baskharas_formula.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1036 #include #include #include using namespace std; int main() { double a, b, c; cin >> a >> b >> c; double delta = pow(b, 2) - 4 * a * c; if (delta > 0 && a != 0) { cout << fixed << setprecision(5) << "R1 = " << ((-1) * b + sqrt(delta)) / (2 * a) << endl; cout << fixed << setprecision(5) << "R2 = " << ((-1) * b - sqrt(delta)) / (2 * a) << endl; } else { cout << "Impossivel calcular" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/batmain.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2510 #include #include using namespace std; int main() { int N; string name; cin >> N; while (N--) { cin.ignore(); getline(cin, name); if (name != "Batmain") cout << "Y" << endl; else cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/bazinga.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1828 #include #include using namespace std; int main() { int n; cin >> n; string player1, player2; for (int i = 1; i <= n; i++) { cin >> player1 >> player2; cout << "Caso #" << i << ": "; if (player1 == player2) { cout << "De novo!" << endl; } else { if (player1 == "tesoura") { if (player2 == "papel" || player2 == "lagarto") cout << "Bazinga!" << endl; else cout << "Raj trapaceou!" << endl; } else if (player1 == "papel") { if (player2 == "pedra" || player2 == "Spock") cout << "Bazinga!" << endl; else cout << "Raj trapaceou!" << endl; } else if (player1 == "pedra") { if (player2 == "lagarto" || player2 == "tesoura") cout << "Bazinga!" << endl; else cout << "Raj trapaceou!" << endl; } else if (player1 == "lagarto") { if (player2 == "Spock" || player2 == "papel") cout << "Bazinga!" << endl; else cout << "Raj trapaceou!" << endl; } else if (player1 == "Spock") { if (player2 == "tesoura" || player2 == "pedra") cout << "Bazinga!" << endl; else cout << "Raj trapaceou!" << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/below_the_main_diagonal.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1184 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter = 1, count = 0; for (int i = 1; i < 12; i++) { for (int j = 0; j < counter; j++) { total += v1[i][j]; count++; } counter++; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/below_the_secundary_diagonal.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1186 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter = 11, count = 0; for (int i = 1; i < 12; i++) { for (int j = counter; j < 12; j++) { total += v1[i][j]; count++; } counter--; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/bill.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1866 #include using namespace std; int main() { int n; cin >> n; while (n--) { int x; cin >> x; if (x % 2 == 0) cout << 0 << endl; else cout << 1 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/bingo.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1136 #include #include #include #include using namespace std; bool isPossible(const set s, int n) { int i = 0; if (n > *s.rbegin()) return false; for (set::iterator it = s.begin(); it != s.end(); it++) { if (*it != i) return false; i++; } return true; } int main() { int n, b, x; while (cin >> n && cin >> b && n + b != 0) { vector v; set s; for (int i = 0; i < b; i++) { cin >> x; v.push_back(x); } sort(v.begin(), v.end()); for (int i = v.size()-1; i >= 0; i--) { for (int j = i; j >= 0; j--) { s.insert(v[i] - v[j]); } } if (isPossible(s, n)) cout << "Y" << endl; else cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/bla.cpp ================================================ // #include #include using namespace std; int main() { string "QWERTYUIOP[]-ASDFGHJKL;'ZXCVBNM,./"; string phrase; cin >> phrase; for (int i = 0; i < phrase.size(); i++) { if () } return 0; } ================================================ FILE: competitive-programming/uri/blobs.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1170 #include using namespace std; int main() { int n; double x; cin >> n; while (n--) { cin >> x; int counter = 0; while (x > 1) { x /= 2; counter++; } cout << counter << " dias" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/bloggo_shotcuts.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1239 #include #include using namespace std; string edit_italic(char charac, bool is_start) { if (is_start) return ""; else return ""; } string edit_bold(char charac, bool is_start) { if (is_start) return ""; else return ""; } int main() { int n; string line; while (getline(cin, line)) { string new_line = ""; bool italic_start = true; bool bold_start = true; for (int i = 0; i < line.size(); i++) { if (line[i] == '*') { new_line += edit_bold(line[i], italic_start); italic_start = !italic_start; } else if (line[i] == '_') { new_line += edit_italic(line[i], bold_start); bold_start = !bold_start; } else { new_line += line[i]; } } cout << new_line << endl; } return 0; } ================================================ FILE: competitive-programming/uri/bob_conduit.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1589 #include using namespace std; int main() { int n; long long int n1, n2; cin >> n; while (n--) { cin >> n1 >> n2; cout << n1 + n2 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/bodybuilder.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2144 #include using namespace std; int main() { int n1, n2, n3, counter = 0; float total, e = 0; while (cin >> n1 >> n2 >> n3 && n1 + n2 + n3 != 0) { total = (n1 + n2) * (1 + n3 / 30.00) / 2; if (total >= 1 && total < 13) cout << "Nao vai da nao" << endl; else if (total >= 13 && total < 14) cout << "E 13" << endl; else if (total >= 14 && total < 40) cout << "Bora, hora do show! BIIR!" << endl; else if (total >= 40 && total <= 60) cout << "Ta saindo da jaula o monstro!" << endl; else cout << "AQUI E BODYBUILDER!!" << endl; e += total; counter++; } cout << endl; if (e / counter > 40) cout << "Aqui nois constroi fibra rapaz! Nao e agua com musculo!" << endl; return 0; } ================================================ FILE: competitive-programming/uri/brazil_world_cup.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1564 #include using namespace std; int main() { int n; while (scanf("%d", &n) != EOF) { if (n == 0) { cout << "vai ter copa!" << endl; } else { cout << "vai ter duas!" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/brazilian_economy.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1796 #include using namespace std; int main() { int n, x, yes=0, no=0; cin >> n; while (n--) { cin >> x; if (x) no++; else yes++; } if (no >= yes) cout << "N" << endl; else cout << "Y" << endl; return 0; } ================================================ FILE: competitive-programming/uri/brick_game.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1436 #include #include #include using namespace std; int main() { int t, casi=1; cin >> t; while (t--) { vector v; int n, temp; cin >> n; for (int i = 0; i < n; i++) { cin >> temp; v.push_back(temp); } sort(v.begin(), v.end()); cout << "Case " << casi << ": " << v[n/2] << endl; casi++; } return 0; } ================================================ FILE: competitive-programming/uri/bubbles_and_bucket.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1088 #include #include using namespace std; int main() { int N, vetor[100001], aux, count; scanf("%d", &N); while (N > 0) { count = 0; for (int i = 1; i <= N; i++) { scanf("%d", &vetor[i]); } for (int i = 1; i <= N; i++) { while(vetor[i] != i) { aux = vetor[i]; vetor[i] = vetor[aux]; vetor[aux] = aux; count++; } } if (count % 2 == 0) printf("Carlos\n"); else printf("Marcelo\n"); scanf("%d", &N); } return 0; } ================================================ FILE: competitive-programming/uri/bubbles_and_bucket_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1088 #include #include #include #include using namespace std; int numberOfSwaps; bool countNumberOfSwaps(int n1, int n2) { if (n1 < n2) numberOfSwaps++; return n1 < n2; } int main() { int n, x; while (cin >> n && n != 0) { numberOfSwaps = 0; vector v; while (n--) { cin >> x; v.push_back(x); } sort(v.begin(), v.end(), countNumberOfSwaps); if (numberOfSwaps % 2 == 0) cout << "Carlos" << endl; else cout << "Marcelo" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/building_houses.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1541 #include #include using namespace std; int main() { int l1, l2, p; cin >> l1 >> l2 >> p; while (l1 != 0) { int area = l1 * l2; int land_size = sqrt(area * 100 / p); cout << land_size << endl; cin >> l1 >> l2 >> p; } return 0; } ================================================ FILE: competitive-programming/uri/building_walls.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2650 #include #include #include #include using namespace std; vector split(string s) { vector V; int startIndex = 0; for (int i = 1; i < s.size(); i++) { if (s[i] == ' ') { V.push_back(s.substr(startIndex, i+1)); startIndex = i+1; } V.push_back(startIndex, s.size() - startIndex); } return V; } int to_digit(string height) { int digit = 0; for (int i = 0; i < height.size(); i++) { digit += (height[i] - '0') * pow(10, height.size() - 1 - i); } return digit; } int main() { int N, W, H; string titan, name, line, height; vector V; cin >> N >> W; cin.ignore(); while (N--) { getline(cin, line); V = split(line); height = V.pop_back(); H = to_digit(height); if (H > W) { for (int i = 0; i < V.size()-1; i++) cout << V[i] << " "; cout << V[i] << endl; } V.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/buttlerflies.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1901 #include #include using namespace std; int new_specie(vector &v, int n) { int found = 0; for (int i = 0; i < v.size(); i++) if (v[i] == n) found = 1; if (found) return 0; else return 1; } int main() { int n; vector< vector > m; vector species; cin >> n; for (int i = 0; i < n; i++) { vector v; for (int j = 0; j < n; j++) { int temp; cin >> temp; v.push_back(temp); } m.push_back(v); } n = n * 2; int n1, n2; cin >> n1 >> n2; n1 -= 1; n2 -= 1; species.push_back(m[n1][n2]); while (n--) { if (new_specie(species, m[n1][n2])) species.push_back(m[n1][n2]); cin >> n1 >> n2; n1 -= 1; n2 -= 1; } cout << species.size() << endl; return 0; } ================================================ FILE: competitive-programming/uri/c_mais_ou_menos.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2486 #include #include using namespace std; int get_vitamine_c(string fruit) { if (fruit == "suco de laranja") return 120; else if (fruit == "morango fresco") return 85; else if (fruit == "mamao") return 85; else if (fruit == "goiaba vermelha") return 70; else if (fruit == "manga") return 56; else if (fruit == "laranja") return 50; else return 34; } int main() { int N, num, total_vitamine; string fruit; cin >> N; while (N != 0) { total_vitamine = 0; while (N--) { cin >> num; cin.ignore(); getline(cin, fruit); total_vitamine += num * get_vitamine_c(fruit); } if (total_vitamine < 110) cout << "Mais " << 110 - total_vitamine << " mg" << endl; else if (total_vitamine > 130) cout << "Menos " << total_vitamine - 130 << " mg" << endl; else cout << total_vitamine << " mg" << endl; cin >> N; } return 0; } ================================================ FILE: competitive-programming/uri/caeser_cipher.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1253 #include #include using namespace std; string shift(string str, int n) { string new_str = ""; string alphabet = "ZYXWVUTSRQPONMLKJIHGFEDCBAZYXWVUTSRQPONMLKJIHGFEDCBA"; int index; for (int i = 0; i < str.size(); i++) { index = alphabet.find(str[i]); index += n; new_str += alphabet[index]; } return new_str; } int main() { int n, shift_n; cin >> n; string str; for (int i = 0; i < n; i++) { cin >> str; cin >> shift_n; if (shift_n) str = shift(str, shift_n); cout << str << endl; } return 0; } ================================================ FILE: competitive-programming/uri/cannon.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1288 #include #include #include using namespace std; struct missile { int power, weight; }; bool compare(missile m1, missile m2) { if (m1.weight < m2.weight) return true; else if (m1.weight > m2.weight) return false; else return m1.power <= m2.power; } int max(int a, int b) { return a >= b ? a : b; } int main() { int C, N, X, Y, K, R; cin >> C; while (C--) { cin >> N; vector missiles; for (int i = 0; i < N; i++) { cin >> X >> Y; missile m; m.power = X; m.weight = Y; missiles.push_back(m); } cin >> K >> R; int dp[N][K+1]; sort(missiles.begin(), missiles.end(), compare); for (int i = 0; i <= K; i++) { if (i < missiles[0].weight) dp[0][i] = 0; else dp[0][i] = missiles[0].power; } for (int i = 1; i < N; i++) { for (int j = 0; j <= K; j++) { if (j < missiles[i].weight) dp[i][j] = dp[i-1][j]; else dp[i][j] = max(dp[i-1][j], dp[i-1][j-missiles[i].weight] + missiles[i].power); } } if (dp[N-1][K] >= R) cout << "Missao completada com sucesso" << endl; else cout << "Falha na missao" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/canteen_queue.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1548 #include #include #include using namespace std; int main() { int n, x, k; cin >> n; while (n--) { vector v, c; cin >> k; while (k--) { cin >> x; v.push_back(x); c.push_back(x); } sort(v.begin(), v.end()); int counter = 0; for (int i = 0; i < v.size(); i++) if (v[i] == c[i]) counter++; cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/cash_roial.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2595 #include #include #include using namespace std; int enemies_counter(vector &V, int cx, int cy, int N, int M) { int counter = 0; if (cx-1 >= 0 && cy-1 >= 0 && V[cx-1][cy-1] == 'T') counter++; if (cy-1 >= 0 && V[cx][cy-1] == 'T') counter++; if (cx+1 < N && cy-1 >= 0 && V[cx+1][cy-1] == 'T') counter++; if (cx-1 >= 0 && V[cx-1][cy] == 'T') counter++; if (cx+1 < N && V[cx+1][cy] == 'T') counter++; if (cx-1 >= 0 && cy+1 < M && V[cx-1][cy+1] == 'T') counter++; if (cy+1 < M && V[cx][cy+1] == 'T') counter++; if (cx+1 < N && cy+1 < M && V[cx+1][cy+1] == 'T') counter++; return counter; } int main() { int num, N, M, P, X, Y, cx, cy; vector V; string line; cin >> num; while (num--) { cin >> N >> M >> P; cin.ignore(); for (int i = 0; i < N; i++) { cin >> line; V.push_back(line); } while (P--) { cin >> cx >> cy; if (enemies_counter(V, cx-1, cy-1, N, M) >= 5) cout << "GRRR" << endl; else cout << "GG IZI" << endl; } V.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/chinese_whispers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1448 #include #include using namespace std; int main() { int n, instance=1; string s, s1, s2; cin >> n; cin.ignore(); while (getline(cin, s)) { getline(cin, s1); getline(cin, s2); int points_1=0, points_2=0; bool not_found = true; int winner = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == s1[i]) points_1++; if (s[i] == s2[i]) points_2++; if (not_found) { if (s[i] == s1[i] && s[i] != s2[i]) { not_found = false; winner = 1; } else if (s[i] != s1[i] && s[i] == s2[i]) { not_found = false; winner = 2; } } } cout << "Instancia " << instance << endl; instance++; if (points_1 == points_2) { if (winner == 0) cout << "empate" << endl; else if (winner == 1) cout << "time 1" << endl; else if (winner == 2) cout << "time 2" << endl; } else if (points_1 > points_2) { cout << "time 1" << endl; } else if (points_1 < points_2) { cout << "time 2" << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/chirrin_chirrion.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2583 #include #include #include using namespace std; int main() { int N, num; string s1, s2; cin >> N; while (N--) { map M; cin >> num; while (num--) { cin >> s1 >> s2; if (M.find(s1) == M.end() && s2 == "chirrin") M[s1] = 1; else if (M.find(s1) != M.end() && s2 == "chirrion") M[s1] = 0; } cout << "TOTAL" << endl; for (map::iterator it = M.begin(); it != M.end(); it++) { if (it->second == 1) cout << it->first << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/chocolate_factory.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1573 #include #include using namespace std; int main() { int n1, n2, n3; while (cin >> n1 >> n2 >> n3 && n1 + n2 + n3 != 0) { int total = n1 * n2 * n3; int cubic_root = cbrt(total); cout << cubic_root << endl; } return 0; } ================================================ FILE: competitive-programming/uri/christmas_decoration.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1761 #include #include #include using namespace std; int main() { double angle, distance, height; while (cin >> angle >> distance >> height) { cout << fixed << setprecision(2) << (tan(angle * 3.141592654 / 180.0) * distance + height) * 5 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/christmas_olympic.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2018 #include #include #include #include using namespace std; struct country { string name; int gold; int silver; int bronze; }; bool compareByMedals(const country &c1, const country &c2) { if (c1.gold > c2.gold) return true; else if (c1.gold == c2.gold) { if (c1.silver > c2.silver) return true; else if (c1.silver == c2.silver) { if (c1.bronze > c2.bronze) return true; else if (c1.bronze == c2.bronze) return c1.name < c2.name; } } return false; } int main() { int index, counter = 0; string game, first, second, third; map m; vector countries; while (getline(cin, game)) { getline(cin, first); getline(cin, second); getline(cin, third); if (m.find(first) != m.end()) { index = m[first]; countries[index].gold++; } else { m[first] = counter; country c; c.name = first; c.gold = 1; c.silver = 0; c.bronze = 0; countries.push_back(c); counter++; } if (m.find(second) != m.end()) { index = m[second]; countries[index].silver++; } else { m[second] = counter; country c; c.name = second; c.gold = 0; c.silver = 1; c.bronze = 0; countries.push_back(c); counter++; } if (m.find(third) != m.end()) { index = m[third]; countries[index].bronze++; } else { m[third] = counter; country c; c.name = third; c.gold = 0; c.silver = 0; c.bronze = 1; countries.push_back(c); counter++; } } sort(countries.begin(), countries.end(), compareByMedals); cout << "Quadro de Medalhas" << endl; for (int i = 0; i < countries.size(); i++) { cout << countries[i].name << " " << countries[i].gold << " " << countries[i].silver << " " << countries[i].bronze << endl; } return 0; } ================================================ FILE: competitive-programming/uri/christmas_trapeziums.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1765 #include #include using namespace std; int main() { int n, num; float n1, n2, h = 5.0; while (cin >> n && n != 0) { for (int i = 1; i <= n; i++) { cout << "Size #" << i << ":" << endl; cin >> num >> n1 >> n2; cout << fixed << setprecision(2) << "Ice Cream Used: " << num * (n1 + n2) * h / 2.0 << " cm2" << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/christmas_tree.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1768 #include #include using namespace std; int main() { int n, mid, start, end; while (cin >> n) { mid = n / 2; start = mid; end = mid; for (int i = 0; i < mid + 1; i++) { for (int j = 0; j < n; j++) { if (j >= start && j <= end) cout << "*"; else if (j > end) break; else cout << " "; } cout << endl; start--; end++; } for (int i = 0; i < n; i++) { if (i == mid) cout << "*"; else if (i > mid) break; else cout << " "; } cout << endl; for (int i = 0; i < n; i++) { if (i == mid || i == mid-1 || i == mid+1) cout << "*"; else if (i > mid+1) break; else cout << " "; } cout << endl << endl; } return 0; } ================================================ FILE: competitive-programming/uri/close_the_doors.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1371 #include #include using namespace std; int main() { long long n = 0, k; while(cin >> k) { long long i = 0; if (k == 0) break; for (n = 0; i < (int)sqrt(k); i++) { n += 2 * i + 1; if (i + 1 >= (int)sqrt(k)) cout << n; else cout << n << " "; } cout << endl; } } ================================================ FILE: competitive-programming/uri/coast_guard.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1247 #include #include using namespace std; int main() { float d, f, g, n, distancia_perpendicular = 12; while(scanf("%f %f %f", &d, &f, &g) != EOF) { n = sqrt((144 + d*d)); if ((12 / f) < (n / g)) cout << 'N' << endl; else cout << 'S' << endl; } return 0; } ================================================ FILE: competitive-programming/uri/coffee_machine.cpp ================================================ #include using namespace std; int main() { int N1, N2, N3; cin >> N1 >> N2 >> N3; int one = N2 * 2 + N3 * 4, two = N1 * 2 + N3 * 2, three = N1 * 4 + N2 * 2; if (one <= two && one <= three) cout << one << endl; else if (two <= three) cout << two << endl; else cout << three << endl; return 0; } ================================================ FILE: competitive-programming/uri/colision.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1618 #include using namespace std; int main() { int n, ax, ay, bx, by, cx, cy, dx, dy, x, y; cin >> n; while (n--) { cin >> ax >> ay >> bx >> by >> cx >> cy >> dx >> dy >> x >> y; if (x >= ax && x <= bx && y >= ay && y <= dy) cout << 1 << endl; else cout << 0 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/collectable_cards.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1028 #include using namespace std; int mcd(int n1, int n2) { if (n2 == 0) return n1; return mcd(n2, n1 % n2); } int main() { int n, n1, n2; cin >> n; while (n--) { cin >> n1 >> n2; if (n1 > n2) cout << mcd(n1, n2) << endl; else cout << mcd(n2, n1) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/colourful_flowers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1419 #include #include #include using namespace std; double get_greater_radius(int a, int b, int c) { double bottom = sqrt((a + b + c) * (b + c - a) * (c + a - b) * (a + b - c)); return (a * b * c) / (bottom); } double get_triangle_area(int l1, int l2, int l3) { double perim = (l1 + l2 + l3) / 2.0; double part1 = perim - l1; double part2 = perim - l2; double part3 = perim - l3; double area = sqrt(perim * part1 * part2 * part3); return area; } double get_smaller_circunference_radius(double triangle_area, double triangle_perimeter) { return 2 * triangle_area / triangle_perimeter; } int main() { double l1, l2, l3; const double PI = 3.1415926535897; while (scanf("%lf %lf %lf", &l1, &l2, & l3) != EOF) { double radius = get_greater_radius(l1, l2, l3); double circunference_area = PI * radius * radius; double triangle_area = get_triangle_area(l1, l2, l3); double smaller_circunference_radius = get_smaller_circunference_radius(triangle_area, l1+l2+l3); double smaller_circunference_area = PI * smaller_circunference_radius * smaller_circunference_radius; cout << fixed << setprecision(4) << circunference_area - triangle_area << " " << triangle_area - smaller_circunference_area << " " << smaller_circunference_area << endl; } return 0; } ================================================ FILE: competitive-programming/uri/column_in_array.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1182 #include #include #include #include using namespace std; int main() { int column; double n; cin >> column; string t; cin >> t; vector< vector > v1; for (int i = 0; i < 12; i++) { vector v2; for (int j = 0; j < 12; j++) { cin >> n; v2.push_back(n); } v1.push_back(v2); } if (t == "S") { double sum = 0; for (int i = 0; i < 12; i++) sum += v1[i][column]; cout << fixed << setprecision(1) << sum << endl; } else if (t == "M") { double average = 0; for (int i = 0; i < 12; i++) average += v1[i][column]; cout << fixed << setprecision(1) << average / 12 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/combiner.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1238 #include #include using namespace std; int main() { int n; cin >> n; string s1, s2; while (n--) { cin >> s1 >> s2; string result = ""; if (s1.size() >= s2.size()) { for (int i = 0; i < s2.size(); i++) { result += s1[i]; result += s2[i]; } result += s1.substr(s2.size(), s1.size() - 1); } else { for (int i = 0; i < s1.size(); i++) { result += s1[i]; result += s2[i]; } result += s2.substr(s1.size(), s2.size() - 1); } cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/compare_substring.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1237 #include #include using namespace std; int searchSubstring(string s) { for (int i = s.size(); i > 0; i--) { } } int main() { string s1, s2; while(getline(cin, s1)) { getline(cin, s2); if (s1.size() < s2.size()) { searchSubstring(s1); } else { searchSubstring(s2); } } return 0; } ================================================ FILE: competitive-programming/uri/complete_sequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1551 #include #include using namespace std; bool find_letter(char c) { string alphabet = "abcdefghijklmnopqrstuvwxyz"; if (alphabet.find(c) != -1) return true; return false; } bool not_in_phrase(char c, string phrase) { if (phrase.find(c) == -1) return true; return false; } int main() { int n; cin >> n; cin.ignore(); string phrase; while (n--) { getline(cin, phrase); string letters_on_phrase = ""; for (int i = 0; i < phrase.size(); i++) { if (find_letter(phrase[i]) && not_in_phrase(phrase[i], letters_on_phrase)) letters_on_phrase += phrase[i]; } if (letters_on_phrase.size() == 26) cout << "frase completa" << endl; else if (letters_on_phrase.size() >= 13) cout << "frase quase completa" << endl; else cout << "frase mal elaborada" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/consumption.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1014 #include #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; cout << fixed << setprecision(3) << n1 / n2 << " km/l" << endl; return 0; } ================================================ FILE: competitive-programming/uri/contando_ciclos.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2497 #include using namespace std; int main() { int N, counter = 1; while (cin >> N && N != -1) { cout << "Experiment " << counter << ": " << N / 2 << " full cycle(s)" << endl; counter++; } return 0; } ================================================ FILE: competitive-programming/uri/contest.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1514 #include #include using namespace std; int main() { int n1, n2, x; cin >> n1 >> n2; while (n1 + n2 != 0) { vector< vector > matrix; vector v; int num_problems = 0, solved; bool nobody_solved_all_problems = true; bool solved_by_one_person = true; bool no_problem_solved_by_everyone = true; bool solved_one_problem = true; for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { cin >> x; v.push_back(x); } matrix.push_back(v); v.clear(); } for (int i = 0; i < n1; i++) { solved = 0; for (int j = 0; j < n2; j++) if (matrix[i][j] == 1) solved++; if (solved == n2) nobody_solved_all_problems = false; if (solved == 0) solved_one_problem = false; } for (int i = 0; i < n2; i++) { solved = 0; for (int j = 0; j < n1; j++) if (matrix[j][i] == 1) solved++; if (solved == n1) no_problem_solved_by_everyone = false; if (solved == 0) solved_by_one_person = false; } if (nobody_solved_all_problems) num_problems++; if (solved_by_one_person) num_problems++; if (no_problem_solved_by_everyone) num_problems++; if (solved_one_problem) num_problems++; cout << num_problems << endl; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/contract_revision.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1120 #include #include using namespace std; int main() { string error_num, contract_num, result = ""; cin >> error_num >> contract_num; while (error_num != "0" || contract_num != "0") { for (int i = 0; i < contract_num.size(); i++) { if (error_num[0] != contract_num[i]) { if (result.size() > 0) result += contract_num[i]; else if (contract_num[i] != '0') result += contract_num[i]; } } if (result.size() > 0) cout << result << endl; else cout << 0 << endl; result.clear(); cin >> error_num >> contract_num; } return 0; } ================================================ FILE: competitive-programming/uri/converting_to_hexadecimal.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1957 #include #include using namespace std; // 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 string reverseString(string hex) { string newHex = ""; for (int i = hex.size()-1; i >= 0; i--) newHex += hex[i]; return newHex; } int main() { string hex = "0123456789ABCDEF", result = ""; int n, stringIndex; cin >> n; while (n > 0) { stringIndex = n % 16; n /= 16; result += hex[stringIndex]; } cout << reverseString(result) << endl; return 0; } ================================================ FILE: competitive-programming/uri/coordinates_of_a_point.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1041 #include using namespace std; int main() { double x, y; cin >> x >> y; if (x > 0 && y > 0) { cout << "Q1" << endl; } else if (x < 0 && y > 0) { cout << "Q2" << endl; } else if (x < 0 && y < 0) { cout << "Q3" << endl; } else if (x > 0 && y < 0) { cout << "Q4" << endl; } else if (x == 0 && y == 0) { cout << "Origem" << endl; } else if (x == 0 && y != 0) { cout << "Eixo Y" << endl; } else if (x != 0 && y == 0) { cout << "Eixo X" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/correct_colourful_flower.cpp ================================================ #include #include #include using namespace std; int main(){ double a, b, c; double violets, roses, girrassois; while(cin >> a >> b >> c){ double p = (a+b+c) / 2.0; double triangulo, circ_p, circ_g; triangulo = sqrt(p*(p-a)*(p-b)*(p-c)); circ_p = pow(triangulo/p,2)*(M_PI); circ_g = pow((a*b*c)/(4*triangulo),2)*(M_PI); violets = triangulo - circ_p; girrassois = circ_g - triangulo; roses = circ_p; cout << fixed << setprecision(4); cout << girrassois << " " << violets << " " << roses << endl; } return 0; } ================================================ FILE: competitive-programming/uri/corrida.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2516 #include #include using namespace std; int main() { double S, VA, VB; while (cin >> S >> VA >> VB) { if (VB >= VA) cout << "impossivel" << endl; else { cout << fixed << setprecision(2) << S / (VA - VB) << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/counting_crow.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1848 #include #include using namespace std; int main() { int scream_counter = 0, blink_counter = 0; string s; while (scream_counter < 3) { cin >> s; if (s == "caw") { scream_counter++; cin >> s; cout << blink_counter << endl; blink_counter = 0; } else { for (int i = 0; i < 3; i++) { if (s[i] == '*') { if (i == 0) blink_counter+= 4; else if (i == 1) blink_counter+= 2; else if (i == 2) blink_counter+= 1; } } } } return 0; } ================================================ FILE: competitive-programming/uri/counting_sheeps.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1609 #include #include using namespace std; int main() { int n, x, temp; cin >> n; while (n--) { cin >> x; set s; for (int i = 0; i < x; i++) { cin >> temp; s.insert(temp); } cout << s.size() << endl; } return 0; } ================================================ FILE: competitive-programming/uri/cutoff_rounder.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1305 #include #include #include using namespace std; string get_integer_part(string n) { int length; for (int i = 0; i < n.size(); i++) if (n[i] == '.') length = i; return n.substr(0, length); } string get_decimal_part(string n) { int initial; for (int i = 0; i < n.size(); i++) if (n[i] == '.') initial = i+1; return n.substr(initial, n.size() - initial); } int to_int(string num) { int number=0, num_digit; for (int i = 0; i < num.size(); i++) { num_digit = num[i] - '0'; number += num_digit * pow(10, num.size()-i-1); } return number; } double to_double(string num) { int num_digit; double number=0; for (int i = 0; i < num.size(); i++) { num_digit = num[i] - '0'; number += num_digit / pow(10, i+1); } cout << "*" << number << endl; return number; } bool is_num_decimal_greater_than_or_equal_to_cutoff_decimal(string num, string cutoff) { int limit, num_digit, cutoff_digit; if (num.size() > cutoff.size()) limit = cutoff.size(); else limit = num.size(); if (num == cutoff) { return true; } else { for (int i = 0; i < limit; i++) { num_digit = num[i] - '0'; cutoff_digit = cutoff[i] - '0'; if (num_digit > cutoff_digit) return true; } return false; } } bool has_period(string n) { for (int i = 0; i < n.size(); i++) if (n[i] == '.') return true; return false; } int main() { string num, cutoff; while (cin >> num >> cutoff) { if (has_period(num)) { string integer_part = get_integer_part(num); string num_decimal_part = get_decimal_part(num); string cutoff_decimal_part = get_decimal_part(cutoff); if (is_num_decimal_greater_than_or_equal_to_cutoff_decimal(num_decimal_part, cutoff_decimal_part)) cout << to_int(integer_part)+1 << endl; else cout << to_int(integer_part) << endl; } else { cout << num << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/cutoff_rounder_2.cpp ================================================ // http://www.urionlinejudge.com.br/judge/en/problems/view/1305 #include #include using namespace std; int main() { long double num, cutoff, fractional; int intnum; while (cin >> num >> cutoff) { intnum = num; fractional = num - intnum; if (fractional >= cutoff) cout << ((int) num + 1) << endl; else cout << ((int) num) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/dancing_sentence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1234 #include #include using namespace std; char to_uppercase(char charac) { string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int index = alphabet.find(charac) - 26; return alphabet[index]; } char to_lowercase(char charac) { string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; int index = alphabet.find(charac) + 26; return alphabet[index]; } bool is_uppercase(char charac) { string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; if (alphabet.find(charac) <= 25) return true; else return false; } int main() { string s; string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; while (getline(cin, s)) { string result = ""; bool uppercase = true; for (int i = 0; i < s.size(); i++) { if (s[i] == ' ') { result += s[i]; } else { if (uppercase) { if (is_uppercase(s[i])) result += s[i]; else result += to_uppercase(s[i]); uppercase = !uppercase; } else { if (is_uppercase(s[i])) result += to_lowercase(s[i]); else result += s[i]; uppercase = !uppercase; } } } cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/dangerous_dive.cpp ================================================ #include #include #include using namespace std; int main() { int n1, n2, x; while (cin >> n1 >> n2) { map m; vector v; for (int i = 1; i <= n2; i++) { cin >> x; m[x] = x; } for (int i = 1; i <= n1; i++) { if (m.find(i) == m.end()) v.push_back(i); } if (v.empty()) { cout << "*"; } else { for (int i = 0; i < v.size(); i++) { cout << v[i] << " "; } } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/dating_online.cpp ================================================ #include #include #include #include #include #define FOR(i, a) for(int i = 0; i < a; i++) #define POW(a) ((a) * (a)) using namespace std; int N; int v[100001]; int main() { while(scanf("%d", &N) != EOF) { FOR(i, N) scanf("%d", &v[i]); sort(v, v+N); double sin_ang = sin(2 * M_PI / N); double area = 0.0; double lado1 = v[N-1], lado_temp = v[N-2]; area += lado1 * lado_temp * sin_ang / 2; for (int i = N - 3; i >= 0; i--) { area += v[i] * v[i+2] * sin_ang / 2; } area += v[0] * v[1] * sin_ang / 2; printf("%.3lf\n", area); } return 0; } ================================================ FILE: competitive-programming/uri/deciphering_the_encrypted_card.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2502 #include #include using namespace std; string to_lowercase(string a) { string alphabet = "ABCDEFGHIJKLMNOPQRSTUVXWYZabcdefghijklmnopqrstuvxwyz"; string result = ""; for (int i = 0; i < a.size(); i++) { if (alphabet.find(a[i]) <= 25) result += alphabet[alphabet.find(a[i])+26]; else result += a[i]; } return result; } string decipher(string phrase, string f, string s) { string deciphered = ""; for (int i = 0; i < phrase.size(); i++) { if (f.find(phrase[i]) != string::npos) deciphered += s[f.find(phrase[i])]; else deciphered += phrase[i]; } return deciphered; } int main() { int N, C; string f, s, phrase; while (cin >> N >> C) { cin >> s >> f; s = to_lowercase(s); f = to_lowercase(f); while (C--) { cin.ignore(); getline(cin, phrase); cout << decipher(phrase, f, s) << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/delaunay_triangulation.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1620 #include #include using namespace std; int main() { long double l, i, x; while (cin >> l && l != 0) { i = l + l - 3; x = (i - l) / l; cout << fixed << setprecision(6) << x << endl; } return 0; } ================================================ FILE: competitive-programming/uri/desafio_de_bino.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2060 #include #include using namespace std; int main() { int n, x; map m; cin >> n; for(int i = 2; i < 6; i++) m[i] = 0; for (int i = 0; i < n; i++) { cin >> x; if (x % 2 == 0) m[2]++; if (x % 3 == 0) m[3]++; if (x % 4 == 0) m[4]++; if (x % 5 == 0) m[5]++; } map::iterator it; for (it = m.begin(); it != m.end(); it++) { cout << it->second << " Multiplo(s) de " << it->first << endl; } return 0; } ================================================ FILE: competitive-programming/uri/detective_watson_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1533 #include using namespace std; int main() { int n, x; while (cin >> n && n != 0) { int index, first, second, index_first = 1; cin >> x; first = x; for (int i = 2; i <= n; i++) { cin >> x; if (x > first) { second = first; first = x; index = index_first; index_first = i; } else if (x > second) { second = x; index = i; } } cout << index << endl; } return 0; } ================================================ FILE: competitive-programming/uri/detective_watson_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1533 #include #include #include #include using namespace std; int main() { int n, x; while (cin >> n && n != 0) { map m; vector v; for (int i = 1; i <= n; i++) { cin >> x; m[x] = i; v.push_back(x); } sort(v.begin(), v.end(), greater()); int key = v[1]; cout << m[key] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/diamonds_and_sand.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1069 #include #include using namespace std; int main() { string s; int n, d, open; cin >> n; while (n--) { d=0, open=0; cin >> s; for(int i = 0; i < s.size(); i++) { if (s[i] == '<') { open++; } else if (s[i] == '>') { if (open > 0) { open--; d++; } } } cout << d << endl; } return 0; } ================================================ FILE: competitive-programming/uri/diet_plan.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1248 #include #include #include #include using namespace std; int main() { int n; string diet, breakfest, lunch; cin >> n; cin.ignore(); while (n--) { vector< pair > valid_chars; bool is_cheating = false; getline(cin, diet); getline(cin, breakfest); getline(cin, lunch); for (int i = 0; i < diet.size(); i++) valid_chars.push_back(make_pair(diet[i], true)); int find_char; for (int i = 0; i < breakfest.size(); i++) { find_char = diet.find(breakfest[i]); if (find_char == -1) { is_cheating = true; break; } else { for (int j = 0; j < valid_chars.size(); j++) if (valid_chars[j].first == breakfest[i]) valid_chars[j].second = false; } } if (!is_cheating) { for (int i = 0; i < lunch.size(); i++) { find_char = diet.find(lunch[i]); if (find_char == -1) { is_cheating = true; break; } else { for (int j = 0; j < valid_chars.size(); j++) if (valid_chars[j].first == lunch[i]) valid_chars[j].second = false; } } if (is_cheating) cout << "CHEATER" << endl; else { string result = ""; for (int index = 0; index < valid_chars.size(); index++) if (valid_chars[index].second) result += valid_chars[index].first; sort(result.begin(), result.end()); cout << result << endl; } } else { cout << "CHEATER" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/difference.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1007 #include using namespace std; int main() { int n1, n2, n3, n4; cin >> n1 >> n2 >> n3 >> n4; cout << "DIFERENCA = " << n1 * n2 - n3 * n4 << endl; return 0; } ================================================ FILE: competitive-programming/uri/different_digits.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1285 #include #include using namespace std; int different_digits(int n) { vector v; while (n > 0) { v.push_back(n % 10); n /= 10; } int different = 1; for (int i = 0; i < v.size(); i++) { for (int j = i + 1; j < v.size(); j++) { if (v[i] == v[j]) { different = 0; break; } } } return different; } int main() { int n1, n2; while (scanf("%d %d", &n1, &n2) != EOF) { int counter=0; for (int i = n1; i <= n2; i++) if (different_digits(i)) counter++; cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/difn.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2518 #include #include #include using namespace std; int main() { double N, H, C, L, result; while (cin >> N ) { cin >> H >> C >> L; result = N * L * (sqrt(H * H + C * C)) / 10000; cout << fixed << setprecision(4) << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/dijkstra.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2653 #include #include #include using namespace std; int main() { string s; set ss; while (cin >> s) { ss.insert(s); } cout << ss.size() << endl; return 0; } ================================================ FILE: competitive-programming/uri/discovering_password.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2252 #include #include #include #include #include using namespace std; struct oil { float key; int value; }; string intToString(int passwordPart) { ostringstream ss; ss << passwordPart; return ss.str(); } bool compareOiliness(const oil &oil1, const oil &oil2) { if (oil1.key == oil2.key) return oil1.value < oil2.value; return oil1.key > oil2.key; } int main() { int n, casy = 1; float f; while (cin >> n) { vector oils; for (int i = 0; i < 10; i++) { cin >> f; oil o; o.key = f; o.value = i; oils.push_back(o); } sort(oils.begin(), oils.end(), compareOiliness); int passwordPart; string password = ""; for (int i = 0; i < n; i++) { passwordPart = oils[i].value; password += intToString(passwordPart); } cout << "Caso " << casy << ": " << password << endl; casy++; } return 0; } ================================================ FILE: competitive-programming/uri/distance.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1016 #include using namespace std; int main() { int distance; cin >> distance; cout << distance * 2 << " minutos" << endl; return 0; } ================================================ FILE: competitive-programming/uri/distance_between_two_points.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1015 #include #include #include using namespace std; int main() { float x1, y1, x2, y2; cin >> x1 >> y1 >> x2 >> y2; cout << fixed << setprecision(4) << sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2)) << endl; return 0; } ================================================ FILE: competitive-programming/uri/dividers.cpp ================================================ #include #include #include using namespace std; int main() { int a, b, c, d, result = -1; cin >> a >> b >> c >> d; vector divisors; for (int i = 1; i * i < c; i++) { if (c % i == 0) { divisors.push_back(i); divisors.push_back(c / i); } } sort(divisors.begin(), divisors.end()); for (int i = 0; i < divisors.size(); i++) { if (divisors[i] % a == 0 && divisors[i] % b != 0 && d % divisors[i] != 0) { result = divisors[i]; break; } } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/dividing_x_by_y.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1116 #include #include using namespace std; int main() { int n; double x, y; cin >> n >> x >> y; while (n--) { if (y != 0) { cout << fixed << setprecision(1) << x / y << endl; } else { cout << "divisao impossivel" << endl; } cin >> x >> y; } return 0; } ================================================ FILE: competitive-programming/uri/diving.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2311 #include #include #include #include #include using namespace std; int main() { int n; cin >> n; string name; float level, rate; while (n--) { cin >> name; vector rates; cin >> level; for (int i = 1; i <= 7; i++) { cin >> rate; rates.push_back(rate); } sort(rates.begin(), rates.end()); float total = 0; for (int i = 1; i < 6; i++) total += rates[i]; cout << setprecision(2) << fixed << name << " " << total * level << endl; } return 0; } ================================================ FILE: competitive-programming/uri/division_of_nlogonia.cpp ================================================ #include using namespace std; int main() { int k, m, n, x, y; cin >> k; while(k != 0) { cin >> m; cin >> n; while(k--) { cin >> x; cin >> y; if ((x < m) && (y < n)) cout << "SO" << endl; else if ((x > m) && (y < n)) cout << "SE" << endl; else if ((x < m) && (y > n)) cout << "NO" << endl; else if ((x > m) && (y > n)) cout << "NE" << endl; else cout << "divisa" << endl; } cin >> k; } return 0; } ================================================ FILE: competitive-programming/uri/divisors_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1157 #include using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { if (n % i == 0) cout << i << endl; } } ================================================ FILE: competitive-programming/uri/dracarys.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1849 #include #include using namespace std; unsigned long long int get_result1(int d1, int d2, int v1, int v2) { unsigned long long int x, y; if (d1 <= v1) x = d1; else x = v1; y = d2 + v2; if (x <= y) return x; else return y; } unsigned long long int get_result2(int d1, int d2, int v1, int v2) { unsigned long long int x, y; if (d2 <= v2) x = d2; else x = v2; y = d1 + v1; if (x <= y) return x; else return y; } unsigned long long int get_result3(int d1, int d2, int v1, int v2) { unsigned long long int x, y; if (d1 + v2 <= d2 + v1) { x = d1 + v2; if (d2 <= v1) y = d2; else y = v1; } else { x = d2 + v1; if (d1 <= v2) y = d1; else y = v2; } if (x <= y) return x; else return y; } int main() { int d1, d2, v1, v2, x, y; unsigned long long int result1, result2, result3, result; cin >> d1 >> d2 >> v1 >> v2; result1 = get_result1(d1, d2, v1, v2); result2 = get_result2(d1, d2, v1, v2); result3 = get_result3(d1, d2, v1, v2); if (result1 >= result2 && result1 >= result3) result = pow(result1, 2); else if (result2 >= result3) result = pow(result2, 2); else result = pow(result3, 2); cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/drought.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1023 #include #include #include #include using namespace std; struct city { int comsumption; int inhabitants; }; bool compareCities(const city &a, const city &b) { return a.comsumption < b.comsumption; } vector groupByMediumComsumption(vector &cities) { vector v; int n = cities[0].inhabitants, coms = cities[0].comsumption; for (int i = 1; i < cities.size(); i++) { if (coms == cities[i].comsumption) n += cities[i].inhabitants; else { city ci; ci.inhabitants = n; ci.comsumption = coms; v.push_back(ci); n = cities[i].inhabitants; coms = cities[i].comsumption; } } city ci; ci.inhabitants = n; ci.comsumption = coms; v.push_back(ci); return v; } int main() { int n, c=1, hab, litres; vector cities; cin >> n; while (n != 0) { float totalLitres = 0, totalInhabitants = 0; for (int i = 0; i < n; i++) { cin >> hab >> litres; totalInhabitants += hab; totalLitres += litres; city ci; ci.comsumption = litres / hab; ci.inhabitants = hab; cities.push_back(ci); } sort(cities.begin(), cities.end(), compareCities); vector nCities = groupByMediumComsumption(cities); cout << "Cidade# " << c << ":" << endl; cout << nCities[0].inhabitants << "-" << nCities[0].comsumption; for (int i = 1; i < nCities.size(); i++) cout << " " << nCities[i].inhabitants << "-" << nCities[i].comsumption; cout << endl; cout << fixed << setprecision(2) << "Consumo medio: " << (totalLitres / totalInhabitants) - 0.0049999999 << " m3." << endl; cin >> n; if (n) cout << endl; c++; cities.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/easy_difference_dates.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2315 #include using namespace std; int main() { int dates[12] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; int day1, day2, month1, month2, totalDays; cin >> day1 >> month1 >> day2 >> month2; if (month2 > month1) { totalDays = dates[month1-1] - day1 + day2; for (int i = month1; i < month2 - 1; i++) totalDays += dates[i]; } else { totalDays = day2 - day1; } cout << totalDays << endl; return 0; } ================================================ FILE: competitive-programming/uri/easy_fibonacci.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1151 #include using namespace std; int main() { int n, n1=0, n2=1, x; cin >> n; if (n == 1) { cout << n1 << endl; } else if (n == 2) { cout << n1 << " " << n2 << endl; } else if (n > 2){ cout << n1 << " " << n2 << " "; n -= 2; while (n > 0) { x = n2; n2 += n1; n1 = x; cout << n2; if (n == 1) { cout << endl; break; } cout << " "; n--; } } return 0; } ================================================ FILE: competitive-programming/uri/easy_problem_from_rujia_liu_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1424 #include #include using namespace std; int getKthOccurrence(vector &ar, int k, unsigned long long int v) { int counter = 0; for (int i = 0; i < ar.size(); i++) { if (ar[i] == v) { counter++; if (counter == k) return i+1; } } return 0; } int main() { int n, m, k, x; unsigned long long int v; while (cin >> n >> m) { vector ar; for (int i = 0; i < n; i++) { cin >> x; ar.push_back(x); } for (int j = 0; j < m; j++) { cin >> k >> v; cout << getKthOccurrence(ar, k, v) << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/easy_problem_from_rujia_liu_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1424 #include #include #include using namespace std; int getKthOccurrence(map< int, vector > &hash, int k, int v) { int counter = 0; for (int i = 0; i < hash[v].size(); i++) { counter++; if (counter == k) return hash[v][i]; } return 0; } int main() { int n, m, k, v, x; while (cin >> n >> m) { map< int, vector > hash; vector ar; for (int i = 1; i <= n; i++) { cin >> x; if (hash.find(x) != hash.end()) hash[x].push_back(i); else { ar.push_back(i); hash[x] = ar; ar.clear(); } } for (int j = 0; j < m; j++) { cin >> k >> v; cout << getKthOccurrence(hash, k, v) << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/eletrical_outlet.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1930 #include using namespace std; int main() { int t1, t2, t3, t4; cin >> t1 >> t2 >> t3 >> t4; cout << t1 + t2 + t3 + t4 - 3 << endl; return 0; } ================================================ FILE: competitive-programming/uri/encryption.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1024 #include #include using namespace std; int get_index(char letter) { string ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}"; if (letter == '/') letter = '.'; return ascii.find(letter); } int get_element(char index) { string ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}"; char element = ascii[index]; if (element == '.') element = '/'; return element; } int is_number(char letter) { string numbers = "012345678910"; if (numbers.find(letter) != -1) return 1; return 0; } string shift_to_the_right(string old_string) { string new_string = ""; string ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}"; for (int i = 0; i < old_string.size(); i++) { if (is_number(old_string[i]) || old_string[i] == ' ' || ascii.find(old_string[i]) == -1) { new_string += old_string[i]; } else { int index = get_index(old_string[i]); index += 3; new_string += get_element(index); } } return new_string; } string shift_to_the_left(string old_string) { string new_string = ""; string ascii = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.]^_`abcdefghijklmnopqrstuvwxyz{-}"; for (int i = 0; i < old_string.size(); i++) { if (is_number(old_string[i]) || old_string[i] == ' ' || ascii.find(old_string[i]) == -1) { new_string += old_string[i]; } else { int index = get_index(old_string[i]); index--; new_string += get_element(index); } } return new_string; } string reverse(string password) { string reversed_string = ""; for (int i = password.size()-1; i >= 0; i--) reversed_string += password[i]; return reversed_string; } int main() { int n; cin >> n; cin.ignore(); while (n--) { string password, encrypted_password; getline(cin, password); // first step: shift to the right encrypted_password = shift_to_the_right(password); // second step: reverse string encrypted_password = reverse(encrypted_password); // third step: shift to the left encrypted_password = shift_to_the_left(encrypted_password); cout << encrypted_password << endl; } return 0; } // Texto #3 --> 3# rvzgV // abcABC1 --> 1FECedc // vxpdylY .ph --> ks. \n{frzx // vv.xwfxo.fd --> gi.r{hyz-xx // qvzgV // 3B // 1EDCedc // /n{frzx ================================================ FILE: competitive-programming/uri/engine_failure.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2167 #include using namespace std; int main() { int n, current, x, result = 0; cin >> n >> current; for (int i = 2; i <= n; i++) { cin >> x; if (x < current) { result = i; break; } else { current = x; } } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/erasing_and_winning.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1084 #include #define MAX 100100 int main(){ char stack[MAX], num; int top, n, d, number_of_cleaned; while (scanf("%d%d", &n, &d) && (n + d)) { number_of_cleaned = 0; top = -1; for (int i = 0; i < n; i++) { scanf(" %c", &num); while (top > -1 && number_of_cleaned < d && num > stack[top]) { top--; number_of_cleaned++; } if (top + 1 < n - d) stack[++top] = num; } stack[++top] = '\0'; printf("%s\n", stack); } return 0; } ================================================ FILE: competitive-programming/uri/estimating_the_mean.cpp ================================================ #include #include using namespace std; int maximum_subsequence_sum(vector &v) { int max_seq = 0, result = 0, greater = v[0]; for (int i = 1; i < v.size(); i++) if (v[i] > greater) greater = v[i]; for (int i = 0; i < v.size(); i++) { if (v[i] == greater) max_seq++; else max_seq = 0; if (max_seq > result) result = max_seq; } return result; } int main() { int n, num, x, result, casy = 1; cin >> n; while (n--) { cin >> num; vector v; while (num--) { cin >> x; v.push_back(x); } result = maximum_subsequence_sum(v); cout << "Caso #" << casy << ": " << result << endl; casy++; } return 0; } ================================================ FILE: competitive-programming/uri/etiquetas_de_noel.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2482 #include #include #include using namespace std; int main() { int N, M; string language, merry, name; map languages; cin >> N; while (N--) { cin >> language; cin.ignore(); getline(cin, merry); languages[language] = merry; } cin >> M; cin.ignore(); while (M--) { getline(cin, name); cin >> language; cout << name << endl << languages[language] << endl << endl; } return 0; } ================================================ FILE: competitive-programming/uri/even_and_odd.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1259 #include #include #include using namespace std; int main() { vector odds, evens; int n; cin >> n; while (cin >> n) { if (n % 2 == 0) evens.push_back(n); else odds.push_back(n); } sort(evens.begin(), evens.end()); sort(odds.begin(), odds.end(), greater()); for (int i = 0; i < evens.size(); i++) cout << evens[i] << endl; for (int i = 0; i < odds.size(); i++) cout << odds[i] << endl; return 0; } ================================================ FILE: competitive-programming/uri/even_between_five_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1065 #include using namespace std; int main() { int positives=0, negatives=0, even=0, odd=0; for (int i = 0; i < 5; i++) { int n; cin >> n; if (n > 0) { positives++; } else if (n < 0) { negatives++; } if (n < 0) n = n * (-1); if (n % 2 == 0) { even++; } else { odd++; } } cout << even << " valor(es) par(es)" << endl; cout << odd << " valor(es) impar(es)" << endl; cout << positives << " valor(es) positivo(s)" << endl; cout << negatives << " valor(es) negativo(s)" << endl; return 0; } ================================================ FILE: competitive-programming/uri/even_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1059 #include using namespace std; int main() { for (int i = 2; i <= 100; i++) { if (i % 2 == 0) cout << i << endl; } return 0; } ================================================ FILE: competitive-programming/uri/even_or_odd.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1074 #include #include using namespace std; int main() { long long int x; int n; cin >> n; while (n--) { cin >> x; if (x == 0) { cout << "NULL" << endl; } else if (x > 0) { if (x % 2 == 0) { cout << "EVEN POSITIVE" << endl; } else { cout << "ODD POSITIVE" << endl; } } else { if (x % 2 == 0) { cout << "EVEN NEGATIVE" << endl; } else { cout << "ODD NEGATIVE" << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/even_square.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1073 #include #include using namespace std; int main() { long long int n; cin >> n; for (long long int i = 2; i <= n; i += 2) { long long int exp = pow(i, 2); cout << i << "^2 = " << exp << endl; } return 0; } ================================================ FILE: competitive-programming/uri/event.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2172 #include using namespace std; int main() { long long int n1, n2, total; while (cin >> n1 >> n2 && n1 + n2 != 0) { total = n1 * n2; cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/event_time.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1061 #include #include using namespace std; int main() { string str1, str2, s3, s4, s5, s6; int d1, d2, h1, h2, m1, m2, s1, s2; cin >> str1 >> d1; cin >> h1 >> str2 >> m1 >> s3 >> s1; cin >> s4 >> d2; cin >> h2 >> s5 >> m2 >> s6 >> s2; int d, h, m, s; if (d2 >= d1) { d = d2 - d1; } if (h2 >= h1) { h = h2 - h1; } else { h = 24 - h1 + h2; d--; } if (m2 >= m1) { m = m2 - m1; } else { m = 60 - m1 + m2; h--; } if (s2 >= s1) { s = s2 - s1; } else { s = 60 - s1 + s2; m--; } cout << d << " dia(s)" << endl; cout << h << " hora(s)" << endl; cout << m << " minuto(s)" << endl; cout << s << " segundo(s)" << endl; return 0; } ================================================ FILE: competitive-programming/uri/exceeding_z.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1150 #include using namespace std; int main() { int n, n1, n2, total=1; cin >> n1 >> n2; while (n2 <= n1) { cin >> n2; } n = n1; while (true) { n += n1 + 1; n1++; total++; if (n > n2) { break; } } cout << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/exchanging_cards.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1104 #include #include using namespace std; int main() { int a, b, temp; cin >> a >> b; while (a + b != 0) { map alice; map betty; for (int i = 0; i < a; i++) { cin >> temp; if (alice.find(temp) != alice.end()) alice[temp]++; else alice[temp] = 0; } for (int i = 0; i < b; i++) { cin >> temp; if (betty.find(temp) != betty.end()) betty[temp]++; else betty[temp] = 0; } int alice_counter = 0, betty_counter = 0; for (map::iterator it = alice.begin(); it != alice.end(); it++) { if (betty.find(it->first) == betty.end()) alice_counter++; } for (map::iterator it = betty.begin(); it != betty.end(); it++) { if (alice.find(it->first) == alice.end()) betty_counter++; } if (alice_counter < betty_counter) cout << alice_counter << endl; else cout << betty_counter << endl; cin >> a >> b; } return 0; } ================================================ FILE: competitive-programming/uri/experiments.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1094 #include #include #include using namespace std; int main() { int c=0, r=0, s=0, n, x; string animal; cin >> n; while (n--) { cin >> x >> animal; if (animal == "C") { c += x; } else if (animal == "R") { r += x; } else if (animal == "S") { s += x; } } int total = c + r + s; double total_for_percentage = total; cout << "Total: " << total << " cobaias" << endl; cout << "Total de coelhos: " << c << endl; cout << "Total de ratos: " << r << endl; cout << "Total de sapos: " << s << endl; cout << fixed << setprecision(2) << "Percentual de coelhos: " << c / total_for_percentage * 100.00 << " %" << endl; cout << fixed << setprecision(2) << "Percentual de ratos: " << r / total_for_percentage * 100.00 << " %" << endl; cout << fixed << setprecision(2) << "Percentual de sapos: " << s / total_for_percentage * 100.00 << " %" << endl; return 0; } ================================================ FILE: competitive-programming/uri/extremely_basic.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/runs/add/1001 #include using namespace std; int main() { int a, b, x; cin >> a >> b; cout << "X = " << a + b << endl; return 0; } ================================================ FILE: competitive-programming/uri/face_2015_free_gift.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1944 #include #include #include using namespace std; int main() { int n, giftNumber = 0; bool opposite; string word, lastWord; char letter; cin >> n; vector words; words.push_back("FACE"); while (n--) { word = ""; opposite = true; lastWord = words.back(); for (int i = 3; i >= 0; i--) { cin >> letter; word += letter; if (lastWord[i] != letter) opposite = false; } if (opposite) { giftNumber++; words.pop_back(); if (words.empty()) words.push_back("FACE"); } else words.push_back(word); } cout << giftNumber << endl; return 0; } ================================================ FILE: competitive-programming/uri/factorial.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1936 #include #include #include using namespace std; int main() { map factorial; int n, index = 1; cin >> n; factorial[0] = 1; factorial[1] = 1; for (int i = 2; factorial[i-1] < n; i++) { if (factorial[i-1] * i > n) break; factorial[i] = factorial[i-1] * i; index = i; } int counter = 0; for (int i = index; i > 0 && n > 0; i--) { while (n >= factorial[i]) { n -= factorial[i]; counter++; } } cout << counter << endl; return 0; } ================================================ FILE: competitive-programming/uri/factorial_again.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1429 #include #include using namespace std; long long int factorial(int n) { if (n < 1) return 1; return n * factorial(n - 1); } int main() { int n; cin >> n; while (n != 0) { vector v; long long int total = 0; while (n) { v.push_back(n % 10); n /= 10; } for (int i = 0; i < v.size(); i++) total += factorial(i+1) * v[i]; cout << total << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/factorial_sum.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1161 #include using namespace std; unsigned long long int factorial(int n) { if (n == 1) return 1; return n * factorial(n - 1); } int main() { int n1, n2; unsigned long long int result1, result2; while (scanf("%llu %llu", &n1, &n2) != EOF) { result1 = factorial(n1); result2 = factorial(n2); cout << result1 + result2 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/fake_tickets.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1318 #include #include using namespace std; int main() { map m; int n1, n2, x; while (cin >> n1 >> n2 && n1 + n2 != 0) { for (int i = 0; i < n2; i++) { cin >> x; if (m.find(x) == m.end()) m[x] = 1; else m[x]++; } map::iterator it; int counter = 0; for (it = m.begin(); it != m.end(); it++) { if (it->second > 1) counter++; } cout << counter << endl; m.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/fans_and_ballons.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1870 #include #include #include using namespace std; int get_left_fan(vector< vector > &matrix, int row, int column) { while (true) { column--; if (matrix[row][column] != 0) return matrix[row][column]; } } int get_right_fan(vector< vector > &matrix, int row, int column) { while (true) { column++; if (matrix[row][column] != 0) return matrix[row][column]; } } int is_it_safe_for_left(vector< vector > &matrix, int row, int column, int walk_num) { for (int i = 1; i <= walk_num; i++) { if (matrix[row][column+i] != 0) return column+i; } return -1; } int is_it_safe_for_right(vector< vector > &matrix, int row, int column, int walk_num) { for (int i = 1; i <= walk_num; i++) { if (matrix[row][column-i] != 0) return column-i; } return -1; } int main() { int rows, columns, position, temp; while (cin >> rows >> columns >> position && rows + columns + position != 0) { vector v; vector< vector > matrix; for (int i = 0; i < rows; i++) { for (int j = 0; j < columns; j++) { cin >> temp; v.push_back(temp); } matrix.push_back(v); v.clear(); } int result_row = -1, result_column = -1; position--; for (int i = 0; i < rows; i++) { if (matrix[i][position] != 0) { result_column = position; result_row = i; break; } int left_fan = get_left_fan(matrix, i, position); int right_fan = get_right_fan(matrix, i, position); if (left_fan > right_fan) { result_column = is_it_safe_for_left(matrix, i, position, left_fan - right_fan); result_row = i; if (result_column != -1) break; else position += left_fan - right_fan; } else if (right_fan > left_fan) { result_column = is_it_safe_for_right(matrix, i, position, right_fan - left_fan); result_row = i; if (result_column != -1) break; else position -= right_fan - left_fan; } } if (result_column == -1) cout << "OUT " << position+1 << endl; else cout << "BOOM " << result_row+1 << " " << result_column+1 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/farm_robot.cpp ================================================ #include using namespace std; int main (void) { int A, B, C; cin >> A >> B >> C; int N = 1; int M = 0; if (C == 1) M++; for (int i = 0; i < B; i++) { int COMM; cin >> COMM; N += COMM; if (N == 0) N = A; else if (N > A) N = 1; if (N == C) M++; } cout << M << endl; return 0; } ================================================ FILE: competitive-programming/uri/fase.cpp ================================================ #include #include #include using namespace std; int main() { int N, M, num; vector V; cin >> N >> M; while (N--) { cin >> num; V.push_back(num); } sort(V.begin(), V.end(), greater()); int result = M; for (int i = M; i < V.size(); i++) { if (V[i] == V[i-1]) result++; else break; } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/fast_fibonacci.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2164 #include #include #include using namespace std; long double fibonacci(int n) { return (pow(((1 + sqrt(5)) / 2), n) - pow(((1 - sqrt(5)) / 2), n)) / sqrt(5); } int main() { int n; cin >> n; cout << fixed << setprecision(1) << fibonacci(n) << endl; return 0; } ================================================ FILE: competitive-programming/uri/fast_prime_number.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1221 #include #include using namespace std; int is_prime(int n) { if (n == 2) return 1; if ((n % 2) == 0) return 0; int s = sqrt(n); for (int i = 3; i <= s; i += 2) if (n % i == 0) return 0; return 1; } int main() { int n, x; cin >> n; while (n--) { cin >> x; if (is_prime(x)) cout << "Prime" << endl; else cout << "Not Prime" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/feedback.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1546 #include #include #include using namespace std; int main() { int n, k, x; vector team_members; team_members.push_back("Rolien"); team_members.push_back("Naej"); team_members.push_back("Elehcim"); team_members.push_back("Odranoel"); cin >> n; while (n--) { cin >> k; while (k--) { cin >> x; cout << team_members[x-1] << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/feyman.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1323 #include using namespace std; int feyman(int n) { if (n == 1) return 1; return n * n + feyman(n - 1); } int main() { int n; cin >> n; while (n != 0) { cout << feyman(n) << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/fibonacci_again.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1531 #include #include using namespace std; #define MOD 1000000007; long long int a,b,c,d; void fast_fib(long long int n,long long int ans[]) { if (n == 0) { ans[0] = 0; ans[1] = 1; return; } fast_fib((n/2),ans); a = ans[0]; b = ans[1]; c = 2 * b - a; if (c < 0) c += MOD; c = (a * c) % MOD; d = (a*a + b*b) % MOD; if (n % 2 == 0) { ans[0] = c; ans[1] = d; } else { ans[0] = d; ans[1] = c+d; } } int main() { long long int n1; int n2; while (scanf("%lli %i", &n1, &n2) != EOF) { long long int ans[2]={0}; fast_fib(n1, ans); long long int res[2]={0}; fast_fib(ans[0], res); cout << res[0] % n2 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/fibonacci_array.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1176 #include using namespace std; long long int fib(int n) { long long int n1=0, n2=1, aux; if (n == 0) { return 0; } else if (n == 1) { return 1; } else { for (int i = 1; i < n; i++) { aux = n2; n2 += n1; n1 = aux; } return n2; } } int main() { long long int n; int x; cin >> n; while (n--) { cin >> x; cout << "Fib(" << x << ") = " << fib(x) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/fila_do_supermercado.cpp ================================================ #include #include #include using namespace std; int getIndexOfSmallerTimeSpent(map &m) { int smaller = 99999, index = 0; map::iterator it; for (it = m.begin(); it != end(); it++) { if (it->second < smaller) { smaller = it->second; index = it->first; } } return index; } int main() { int cashiers, clients, x; cin >> cashiers >> clients; vector ca, cli; for (int i = 0; i < cashiers; i++) { cin >> x; ca.push_back(x); } for (int i = 0; i < clients; i++) { cin >> x; cli.push_back(x); } map t_gastos; for (int i = 0; i < cashiers; i++) { t_gastos[i] = cashiers[i] * clients[i]; } int index = getIndexOfSmallerTimeSpent(m); return 0; } ================================================ FILE: competitive-programming/uri/fire_flowers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1039 #include #include using namespace std; int to_positive(int number) { if (number < 0) return number * (-1); return number; } int main() { int r1, x1, y1, r2, x2, y2; while (cin >> r1 >> x1 >> y1 >> r2 >> x2 >> y2) { int distance_x = to_positive(x1 - x2); int distance_y = to_positive(y1 - y2); double total_distance = sqrt(pow(distance_x, 2) + pow(distance_y, 2)); if (r1 < r2) { cout << "MORTO" << endl; } else { if (r1 >= r2 + total_distance) cout << "RICO" << endl; else cout << "MORTO" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/fit_or_dont_fit_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1240 #include #include #include using namespace std; int verify_number(unsigned long long int n1, unsigned long long int n2) { vector v1, v2; while (n2 > 0) { v1.push_back(n1 % 10); v2.push_back(n2 % 10); n1 /= 10; n2 /= 10; } for (int j = 0; j < v2.size(); j++) if (v1[j] != v2[j]) return 0; return 1; } int main() { int n; cin >> n; while (n--) { unsigned long long int n1, n2; cin >> n1 >> n2; if (n1 >= n2 && verify_number(n1, n2)) { cout << "encaixa" << endl; } else { cout << "nao encaixa" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/fit_or_dont_fit_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1241 #include #include using namespace std; int main() { int n; cin >> n; string n1, n2; while (n--) { cin >> n1 >> n2; if (n1.size() >= n2.size()) { int pos = n1.size() - n2.size(); int length = n1.size() - pos; string subs = n1.substr(pos, length); if (subs == n2) cout << "encaixa" << endl; else cout << "nao encaixa" << endl; } else { cout << "nao encaixa" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/fixed_password.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1114 #include using namespace std; int main() { int n; cin >> n; while (n != 2002) { cin >> n; cout << "Senha Invalida" << endl; } cout << "Acesso Permitido" << endl; return 0; } ================================================ FILE: competitive-programming/uri/flavious_josephus_legend.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1030 #include #include using namespace std; int verify_last_value(vector &v) { int counter = 0; for (int i = 0; i < v.size(); i++) if (v[i] == 1) counter++; return counter; } int can_be_counted(vector &v, int index, int n) { while (v[index] == 0) { if (index == n - 1) index = 0; else index++; cout << index << " "; } cout << endl; return index; } int get_last_value_index(vector &v) { for (int i = 0; i < v.size(); i++) if (v[i] == 1) return i; } int main() { int nc, n, k, c = 1; cin >> nc; while (nc--) { cin >> n >> k; vector v; int i = 0, counter = 1; for (int i = 0; i < n; i++) v.push_back(1); while (verify_last_value(v)) { i = can_be_counted(v, i, n); if (counter == k) { v[i] = 0; counter = 0; } else { counter++; } i++; if (i == n - 1) i = 0; } cout << "Case " << c << ": " << get_last_value_index(v) << endl; c++; } return 0; } ================================================ FILE: competitive-programming/uri/flavious_josephus_legend2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1030 #include #include using namespace std; int parse_index(int index, int size) { while (index >= size) index -= size; return index; } int main() { long long int n, num1, num2; int casy = 1; cin >> n; while (n--) { cin >> num1 >> num2; num2--; vector v; for (int i = 1; i <= num1; i++) v.push_back(i); int index = 0; while (v.size() > 1) { index += num2; index = parse_index(index, v.size()); v.erase(v.begin() + index); } cout << "Case " << casy << ": " << v[0] << endl; casy++; } return 0; } ================================================ FILE: competitive-programming/uri/flavious_josephus_legend3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1030 #include using namespace std; int josephus(int n, int k) { if (n == 1) return 0; return (josephus(n-1, k) + k) % n; } int main() { int n, n1, n2, counter = 1; cin >> n; while (n--) { cin >> n1 >> n2; cout << "Case " << counter << ": " << josephus(n1, n2)+1 << endl; counter++; } return 0; } ================================================ FILE: competitive-programming/uri/flowers_flourish_from_france.cpp ================================================ #include #include #include #include #include #include using namespace std; int main() { string frase; vector palavras; getline(cin, frase); while(frase != "*") { transform(frase.begin(), frase.end(), frase.begin(), ::tolower); istringstream iss(frase); copy(istream_iterator(iss), istream_iterator(), back_inserter(palavras)); char letra = frase[0]; char result = 'Y'; for(int i = 0; i < palavras.size(); i++) { if(palavras[i][0] != letra) { result = 'N'; break; } } cout << result << endl; getline(cin, frase); palavras.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/football.cpp ================================================ #include #include #include using namespace std; int main() { int matches, num_buy, goals1, goals2; while (cin >> matches >> num_buy) { vector pos, neg, zeros; for (int i = 0; i < matches; i++) { cin >> goals1 >> goals2; if (goals1 - goals2 == 0) zeros.push_back(0); else if (goals1 - goals2 < 0) neg.push_back(goals1 - goals2); else pos.push_back(goals1 - goals2); } int counter = 0; counter += pos.size() * 3; for (int i = 0; i < zeros.size(); i++) { if (num_buy > 0) { zeros[i]++; num_buy--; counter += 3; } else { counter++; } } sort(neg.begin(), neg.end(), greater()); if (num_buy > 0) { int ind = 0; while (ind < neg.size()) { if (num_buy <= 0) break; neg[ind]++; num_buy--; if (neg[ind] > 0) ind++; } } for (int i = 0; i < neg.size(); i++) { if (neg[i] == 0) counter++; else if (neg[i] > 0) counter += 3; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/frequent_asked_questions.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1553 #include #include using namespace std; int main() { int n, k, num; while (cin >> n >> k && n + k != 0) { map m; int counter = 0; for (int i = 0; i < n; i++) { cin >> num; if (m.find(num) != m.end()) m[num]++; else m[num] = 1; } map::iterator it; for (it = m.begin(); it != m.end(); it++) { if (it->second >= k) counter++; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/friends_of_habey.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2136 #include #include #include #include #include using namespace std; bool compareByName(string name1, string name2) { return name1.size() >= name2.size(); } int main() { string name, want; set peopleThatWant; set peopleThatDoNotWant; vector v; while (cin >> name && name != "FIM") { cin >> want; if (want == "YES") { peopleThatWant.insert(name); v.push_back(name); } else peopleThatDoNotWant.insert(name); } for (set::iterator it = peopleThatWant.begin(); it != peopleThatWant.end(); it++) { cout << *it << endl; } for (set::iterator it = peopleThatDoNotWant.begin(); it != peopleThatDoNotWant.end(); it++) { cout << *it << endl; } cout << endl; sort(v.begin(), v.end(), compareByName); cout << "Amigo do Habay:" << endl << v[0] << endl; return 0; } ================================================ FILE: competitive-programming/uri/fuel_spent.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1017 #include #include using namespace std; int main() { int time, velocity; cin >> time >> velocity; cout << fixed << setprecision(3) << time * velocity / 12.0 << endl; return 0; } ================================================ FILE: competitive-programming/uri/functions.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1555 #include using namespace std; int main() { int n, n1, n2; cin >> n; while (n--) { cin >> n1 >> n2; int rafa = (3 * n1) * (3 * n1) + n2 * n2; int beto = 2 * (n1 * n1) + (5 * n2 * 5 * n2); int carlos = (n2 * n2 * n2) - 100 * n1; if (rafa > beto && rafa > carlos) cout << "Rafael ganhou" << endl; else if (beto > carlos) cout << "Beto ganhou" << endl; else cout << "Carlos ganhou" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/galopeira.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2147 #include #include #include using namespace std; int main() { int n; float seconds; string s; cin >> n; while (n--) { cin >> s; seconds = s.size() / 100.00; cout << fixed << setprecision(2) << seconds << endl; } return 0; } ================================================ FILE: competitive-programming/uri/game_of_the_greatness.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1397 #include using namespace std; int main() { int n, n1, n2; cin >> n; while (n) { int counter1=0, counter2=0; while (n--) { cin >> n1 >> n2; if (n1 > n2) counter1++; else if (n2 > n1) counter2++; } cout << counter1 << " " << counter2 << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/general_exam.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2534 #include #include #include using namespace std; int main() { int N, Q, X; vector V, R; while (cin >> N >> Q) { while (N--) { cin >> X; V.push_back(X); } sort(V.begin(), V.end(), greater()); while (Q--) { cin >> X; cout << V[X-1] << endl; } V.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/getline_fruits.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1217 #include #include #include using namespace std; int num_of_fruits(string fruits) { int num = 1; for (int i = 0; i < fruits.size(); i++) if (fruits[i] == ' ') num++; return num; } int main() { string fruits; int n, day_kg = 0, day = 1; double total_kg = 0.0, total_money, money; cin >> n; for (int i = 0; i < n; i++) { cin >> money; total_money += money; cin.ignore(); getline(cin, fruits); day_kg = num_of_fruits(fruits); total_kg += day_kg; cout << "day " << day << ": " << day_kg << " kg" << endl; day++; } double kg_per_day = total_kg / n, money_per_day = total_money / day; cout << fixed << setprecision(2) << kg_per_day << " kg by day" << endl; cout << fixed << setprecision(2) << "R$ " << money_per_day << " by day" << endl; return 0; } ================================================ FILE: competitive-programming/uri/getline_one.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1216 #include #include #include using namespace std; int main() { string s; int n, counter=0; double total=0; while (getline(cin, s)) { cin >> n; total += n; counter++; cin.ignore(); } cout << fixed << setprecision(1) << total / counter << endl; return 0; } ================================================ FILE: competitive-programming/uri/getline_three_shoes.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1218 #include #include using namespace std; int main() { bool first = true, found; string num, shoes, shoe_num = ""; int casy = 1; while (cin >> num) { int fem = 0, mas = 0, number_shoes = 0; cin.ignore(); getline(cin, shoes); for (int i = 0; i < shoes.size(); i += 5) { int ind = i; if (shoes.substr(i, 2) == num) { ind += 3; if (shoes[ind] == 'F') fem++; else mas++; number_shoes++; } } if (first) { cout << "Caso " << casy << ":" << endl; first = false; } else { cout << endl << "Caso " << casy << ":" << endl; } cout << "Pares Iguais: " << number_shoes << endl; cout << "F: " << fem << endl; cout << "M: " << mas << endl; casy++; } return 0; } ================================================ FILE: competitive-programming/uri/going_to_the_market.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1281 #include #include #include #include using namespace std; int main() { string product; int n, numOfPrices, numOfProducts, num; float price, total; cin >> n; while (n--) { total = 0; map m; cin >> numOfPrices; while (numOfPrices--) { cin >> product >> price; m[product] = price; } cin >> numOfProducts; while (numOfProducts--) { cin >> product >> num; total += m[product] * num; } cout << fixed << setprecision(2) << "R$ " << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/grains_in_a_chess_board.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1169 #include #include using namespace std; int main() { int n, x; cin >> n; while (n--) { cin >> x; if (x < 64) { unsigned long long int grains = 1; while (x--) grains *= 2; unsigned long long int kl = (grains / 12) / 1000 ; cout << kl << " kg" << endl; } else { unsigned long long int grains = pow(2, 63) - 1; unsigned long long int kl = (grains / 6) / 1000 ; cout << kl << " kg" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/grenais.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1131 #include using namespace std; int main() { int n1, n2, n, inter=0, gremio=0, empate=0, total=1; cin >> n1 >> n2; if (n1 > n2) { inter++; } else if (n2 > n1) { gremio++; } else { empate++; } cout << "Novo grenal (1-sim 2-nao)" << endl; cin >> n; while (n == 1) { cin >> n1 >> n2; if (n1 > n2) { inter++; } else if (n2 > n1) { gremio++; } else { empate++; } cout << "Novo grenal (1-sim 2-nao)" << endl; cin >> n; total++; } cout << total << " grenais" << endl; cout << "Inter:" << inter << endl; cout << "Gremio:" << gremio << endl; cout << "Empates:" << empate << endl; if (inter > gremio) cout << "Inter venceu mais" << endl; else if (gremio > inter) cout << "Gremio venceu mais" << endl; else cout << "Nao houve vencedor" << endl; return 0; } ================================================ FILE: competitive-programming/uri/growing_sequences.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1146 #include using namespace std; int main() { int x; cin >> x; while (x != 0) { for (int i = 1; i <= x; i++) { cout << i; if (i == x) break; cout << " "; } cout << endl; cin >> x; } return 0; } ================================================ FILE: competitive-programming/uri/guess_what.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1547 #include #include #include #include using namespace std; int main() { int n; cin >> n; while (n--) { vector v; int n1, n2, temp, result = -1; cin >> n1 >> n2; for (int i = 0; i < n1; i++) { cin >> temp; v.push_back(temp); if (temp == n2 && result != -1) result = i+1; } if (result != -1) { cout << result << endl; } else { int min = 101; for (int i = 0; i < v.size(); i++) { if (abs(n2 - v[i]) < min) { min = abs(n2 - v[i]); result = i+1; } } cout << result << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/guilherme_and_his_kites.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1921 #include using namespace std; int main() { long long int n; cin >> n; cout << n * (n - 3) / 2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/guru_da_sorte.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2508 #include #include using namespace std; int get_value_for(string name) { int value = 0; for (int i = 0; i < name.size(); i++) { if (name[i] == 'A' || name[i] == 'a' || name[i] == 'j' || name[i] == 'J' || name[i] == 's' || name[i] == 'S') value++; else if (name[i] == 'B' || name[i] == 'b' || name[i] == 'k' || name[i] == 'K' || name[i] == 't' || name[i] == 'T') value += 2; else if (name[i] == 'C' || name[i] == 'c' || name[i] == 'l' || name[i] == 'L' || name[i] == 'u' || name[i] == 'U') value += 3; else if (name[i] == 'D' || name[i] == 'd' || name[i] == 'm' || name[i] == 'M' || name[i] == 'v' || name[i] == 'V') value += 4; else if (name[i] == 'E' || name[i] == 'e' || name[i] == 'n' || name[i] == 'N' || name[i] == 'w' || name[i] == 'W') value += 5; else if (name[i] == 'F' || name[i] == 'f' || name[i] == 'o' || name[i] == 'O' || name[i] == 'x' || name[i] == 'X') value += 6; else if (name[i] == 'G' || name[i] == 'g' || name[i] == 'p' || name[i] == 'P' || name[i] == 'y' || name[i] == 'Y') value += 7; else if (name[i] == 'H' || name[i] == 'h' || name[i] == 'q' || name[i] == 'Q' || name[i] == 'z' || name[i] == 'Z') value += 8; else if (name[i] == 'I' || name[i] == 'i' || name[i] == 'r' || name[i] == 'R') value += 9; } return value; } int get_result(int N) { int num; while (N >= 10) { num = 0; while (N > 0) { num += N % 10; N /= 10; } N = num; } return N; } int main() { int N, num; string name; while (getline(cin, name)) { N = get_value_for(name); cout << get_result(N) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hailstone_sequences.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1441 #include using namespace std; int resolve(int h, int max) { if (h == 1) return max; cout << "h: " << h << " max: " << max << endl; if (h % 2 == 0) h = h / 2; else h = 3 * h + 1; if (h > max) max = h; return resolve(h, max); } int main() { int n; while (cin >> n && n) { cout << resolve(n, n) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hall_of_murderers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1861 #include #include #include #include using namespace std; bool find(string murder, vector &people_killed) { for (int j = 0; j < people_killed.size(); j++) { if (people_killed[j] == murder) return true; } return false; } int main() { vector people_killed; vector< pair > murders; string murder, killed; while (cin >> murder >> killed) { bool found = false; for (int i = 0; i < murders.size(); i++) { if (murders[i].first == murder) { found = true; murders[i].second++; break; } } if (!found) murders.push_back(make_pair(murder, 0)); people_killed.push_back(killed); } for (int i = 0; i < people_killed.size(); i++) cout << people_killed[i] << " "; cout << endl; for (int i = 0; i < murders.size(); i++) cout << murders[i].first << " "; cout << endl; int num_of_killed = 0; for (int i = 0; i < murders.size(); i++) { if (find(murders[i].first, people_killed)) { murders.erase(murders.begin() + i + 1 - num_of_killed); num_of_killed++; } } sort(murders.begin(), murders.end()); cout << "HALL OF MURDERERS" << endl; for (int j = 0; j < murders.size(); j++) cout << murders[j].first << " " << murders[j].second << endl; return 0; } ================================================ FILE: competitive-programming/uri/hall_of_murderers_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1861 #include #include #include #include using namespace std; struct person { string name; int kill; bool killed; }; int findPerson(vector &people, string name) { for (int i = 0; i < people.size(); i++) { if (people[i].name == name) return i; } return -1; } bool compareByName(const person &a, const person &b) { return a.name < b.name; } int main() { int murderIndex, victimIndex; string murder, victim; vector people; while (cin >> murder >> victim) { murderIndex = findPerson(people, murder); if (murderIndex != -1) { people[murderIndex].kill++; } else { person p; p.kill = 1; p.killed = false; people.push_back(p); } victimIndex = findPerson(people, victim); if (victimIndex != -1) people[victimIndex].killed = true; } cout << "HALL OF MURDERERS" << endl; sort(people.begin(), people.end(), compareByName); for (int i = 0; i < people.size(); i++) { if (!people[i].killed) { cout << people[i].name << " " << people[i].kill << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/hall_of_murderers_3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1861 #include #include #include #include #include using namespace std; int main() { const int DEAD = -1; int murderIndex, victimIndex; string murder, victim; map people; while (cin >> murder >> victim) { if (people.find(murder) != people.end() && people[murder] != DEAD) people[murder]++; else if (people.find(murder) == people.end()) people[murder] = 1; if (people.find(victim) != people.end()) people[victim] = DEAD; else if (people.find(victim) == people.end()) people[victim] = DEAD; } cout << "HALL OF MURDERERS" << endl; for (map::iterator it = people.begin(); it != people.end(); ++it) { if (it->second != DEAD) cout << it->first << " " << it->second << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hamekameka.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2591 #include #include using namespace std; string ka(int as) { string s = "k"; for (int i = 0; i < as; i++) s += "a"; return s; } int main() { int N, as; string s; cin >> N; while (N--) { cin >> s; as = (s.find("m") - 1) * (s.size() - 3 - s.find("k")); cout << ka(as) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/handball.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1715 #include using namespace std; int main() { int players, matches, p; while (cin >> players >> matches) { int counter = 0; for (int i = 0; i < players; i++) { bool scored = true; for (int j = 0; j < matches; j++) { cin >> p; if (p == 0) scored = false; } if (scored) counter++; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hardwood_species.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1260 #include #include #include #include using namespace std; int main() { int n; float numberOfTrees; string name; cin >> n; cin.ignore(); getline(cin, name); while (n--) { map trees; numberOfTrees = 0; while (getline(cin, name)) { if (name != "") { if (trees.find(name) != trees.end()) trees[name]++; else trees[name] = 1; numberOfTrees++; } else { break; } } map::iterator it; for (it = trees.begin(); it != trees.end(); ++it) { cout << fixed << setprecision(4) << it->first << " " << (it->second / numberOfTrees) * 100.00 << endl; } if (n != 0) cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hash_tables.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1256 #include #include #include using namespace std; int main() { int n, m, c, x, key; cin >> n; for (int a = 0; a < n; a++) { map > hash; vector v; cin >> m >> c; for (int i = 0; i < c; i++) { cin >> x; key = x % m; hash[key].push_back(x); } for (int i = 0; i < m; i++) { cout << i << " -> "; for (int j = 0; j < hash[i].size(); j++) cout << hash[i][j] << " -> "; cout << "\\" << endl; } if (a < n-1) cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hashmat_the_brave_warrior.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1198 #include using namespace std; int main() { long long int n1, n2; while (scanf("%llu %llu", &n1, &n2) != EOF) { if (n1 > n2) cout << n1 - n2 << endl; else cout << n2 - n1 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hay_points.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1261 #include #include #include using namespace std; int main() { int n1, n2, points; cin >> n1 >> n2; map wordPoints; string word; for (int i = 0; i < n1; i++) { cin >> word >> points; wordPoints[word] = points; } int totalPoints; string wordOfJobDescription; while (n2--) { totalPoints = 0; while(cin >> wordOfJobDescription && wordOfJobDescription != ".") { if (wordPoints.find(wordOfJobDescription) != wordPoints.end()) totalPoints += wordPoints[wordOfJobDescription]; } cout << totalPoints << endl; } return 0; } ================================================ FILE: competitive-programming/uri/he_is_offside!.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1410 #include #include #include using namespace std; int main() { int n, m, temp1, temp2; char result; vector atacantes; vector defensores; cin >> n; cin >> m; while (n + m != 0) { for(int i = 0; i < n; i++) { cin >> temp1; atacantes.push_back(temp1); } for(int j = 0; j < m; j++) { cin >> temp2; defensores.push_back(temp2); } sort(atacantes.begin(), atacantes.end()); sort(defensores.begin(), defensores.end()); if (atacantes[0] < defensores[1]) cout << "Y" << endl; else cout << "N" << endl; cin >> n; cin >> m; atacantes.clear(); defensores.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/head_or_tails.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1329 #include using namespace std; int main() { int mary=0, john=0; int n, temp; cin >> n; while (n != 0) { while (n--) { cin >> temp; if (temp) john++; else mary++; } cout << "Mary won " << mary << " times and John won " << john << " times" << endl; cin >> n; } } ================================================ FILE: competitive-programming/uri/height.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1566 #include #include #include using namespace std; int main() { int n, x, num; scanf("%i", &n); while (n--) { vector v; scanf("%i", &num); for (int i = 0; i < num; i++) { scanf("%i", &x); v.push_back(x); } sort(v.begin(), v.end()); printf("%i", v[0]); for (int i = 1; i < num; i++) printf(" %i", v[i]); printf("\n"); } return 0; } ================================================ FILE: competitive-programming/uri/hello_galaxy.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1515 #include #include #include using namespace std; int main() { int n, year, years; string planet; while (cin >> n && n != 0) { map m; for (int i = 0; i < n; ++i) { cin >> planet >> year >> years; m[year+years] = planet; } cout << m.begin()->second << endl; } return 0; } ================================================ FILE: competitive-programming/uri/help!.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1367 #include #include using namespace std; bool problem_incorrected(string problems, char problem) { if (problems.find(problem) != -1) return true; return false; } bool problem_solved(string problems, char problem) { if (problems.find(problem) != -1) return true; return false; } int incorrect_submission_counter(string problems, char problem) { int counter = 0; for (int i = 0; i < problems.size(); i++) if (problems[i] == problem) counter++; return counter; } int main() { int n; cin >> n; string solved_problems = ""; string incorrect_problems = ""; while (n != 0) { int total_points = 0; char problem; int point; string status; for (int i = 0; i < n; i++) { cin >> problem >> point >> status; if (status == "correct") { if (!problem_solved(solved_problems, problem)) { if (problem_incorrected(incorrect_problems, problem)) total_points += point + 20 * incorrect_submission_counter(incorrect_problems, problem); else total_points += point; solved_problems += problem; } } else { incorrect_problems += problem; } } cout << solved_problems.size() << " " << total_points << endl; solved_problems.clear(); incorrect_problems.clear(); cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/help_girafales.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1911 #include #include #include using namespace std; int get_index(vector< pair > names, string name) { for (int i = 0; i < names.size(); i++) { if (names[i].first == name) return i; } } int main() { vector< pair > names; int n, m, counter = 0; string name, signature; cin >> n; while (n != 0) { while (n--) { cin >> name >> signature; names.push_back(make_pair(name, signature)); } cin >> m; for (int i = 0; i < m; i++) { cin >> name >> signature; bool falsy = false; int error_counter = 0; int ind = get_index(names, name); for (int j = 0; j < signature.size(); j++) { //cout << names[i].second[j] << " " << signature[j] << endl; if (names[ind].second[j] != signature[j]) error_counter++; if (error_counter > 1) { falsy = true; break; } } if (falsy) counter++; } cout << counter << endl; counter = 0; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/help_seu_madruga.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1912 #include #include #include #include using namespace std; int main() { int n, temp, a, total=0, counter=0, greater=0, result; cin >> n >> a; while (n + a != 0) { vector v; for (int i = 0; i < n; i++) { cin >> temp; total += temp; v.push_back(temp); if (temp > greater) greater = temp; } result = greater - 1; if (total == a) { cout << ":D" << endl; } else { sort(v.begin(), v.end(), std::greater()); while (true) { counter = 0; for (int i = 0; i < n; i++) { if (v[i] - result > 0) counter += v[i] - result; else break; } if (counter >= a) break; else result--; } if (counter == a) { double bla = result; cout << fixed << setprecision(4) << bla << endl; } else { cout << "-.-" << endl; } } cin >> n >> a; total = 0; greater = 0; } return 0; } ================================================ FILE: competitive-programming/uri/help_seu_madruga_int.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1912 #include #include #include using namespace std; int get_bigger(vector &v) { int max = v[0]; for (int i = 1; i < v.size(); i++) if (v[i] > max) max = v[i]; return max; } int area_binary_search(vector &v, int area) { int NOT_FOUND = -1; int low = 0, high = get_bigger(v), mid, sum; while (low <= high) { mid = (low + high) / 2; sum = 0; for (int i = 0; i < v.size(); i++) if (v[i] - mid > 0) sum += v[i] - mid; if (sum == area) return mid; else if (sum > area) low = mid + 1; else high = mid - 1; } return NOT_FOUND; } int main() { vector v; int n, x, value, temp, counter; cin >> n >> value; while (n + value != 0) { for (int i = 0; i < n; i++) { cin >> temp; v.push_back(temp); } float result; result = area_binary_search(v, value); if (result == -1) cout << "-.-" << endl; else if (result == 0) cout << ":D" << endl; else cout << fixed << setprecision(4) << result << endl; cin >> n >> value; v.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/help_the_federation.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1588 #include #include #include #include using namespace std; struct team { int id; string name; int points; int wins; int goals; }; bool compareTeams(const team &team1, const team &team2) { if (team1.points > team2.points) return true; else if (team1.points == team2.points) { if (team1.wins > team2.wins) return true; else if (team1.wins == team2.wins) { if (team1.goals > team2.goals) return true; else if (team1.goals == team2.goals && team1.id < team2.id) return true; } } return false; } int main() { int num, n, m, goal1, goal2; string name, player1, player2; cin >> num; while (num--) { cin >> n >> m; vector teams; for (int i = 0; i < n; i++) { teams.push_back(team()); cin >> name; teams[i].id = i; teams[i].name = name; teams[i].points = 0; teams[i].wins = 0; teams[i].goals = 0; } for (int i = 0; i < m; i++) { cin >> goal1 >> player1 >> goal2 >> player2; if (goal1 > goal2) { for (int j = 0; j < teams.size(); j++) { if (teams[j].name == player1) { teams[j].points += 3; teams[j].wins++; teams[j].goals += goal1; } if (teams[j].name == player2) teams[j].goals += goal2; } } else if (goal1 < goal2) { for (int j = 0; j < teams.size(); j++) { if (teams[j].name == player2) { teams[j].points += 3; teams[j].wins++; teams[j].goals += goal2; } if (teams[j].name == player1) teams[j].goals += goal1; } } else { for (int j = 0; j < teams.size(); j++) { if (teams[j].name == player1) { teams[j].points++; teams[j].goals += goal1; } if (teams[j].name == player2) { teams[j].points++; teams[j].goals += goal2; } } } } sort(teams.begin(), teams.end(), compareTeams); for (int i = 0; i < teams.size(); i++) { cout << teams[i].name << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/hexagonal_tiles_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1393 #include #include using namespace std; int main() { int n; map m; m[1] = 1; m[2] = 2; m[3] = 3; m[4] = 5; m[5] = 8; m[6] = 13; m[7] = 21; m[8] = 34; m[9] = 55; m[10] = 89; m[11] = 144; m[12] = 233; m[13] = 377; m[14] = 610; m[15] = 987; m[16] = 1597; m[17] = 2584; m[18] = 4181; m[19] = 6765; m[20] = 10946; m[21] = 17711; m[22] = 28657; m[23] = 46368; m[24] = 75025; m[25] = 121393; m[26] = 196418; m[27] = 317811; m[28] = 514229; m[29] = 832040; m[30] = 1346269; m[31] = 2178309; m[32] = 3524578; m[33] = 5702887; m[34] = 9227465; m[35] = 14930352; m[36] = 24157817; m[37] = 39088169; m[38] = 63245986; m[39] = 102334155; m[40] = 165580141; while (cin >> n && n) { cout << m[n] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hexagonal_tiles_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1393 #include using namespace std; int resolve(int n1, int n2) { if (n == 1) return 1; else if (n == 2) return 2; else return resolve(n-2, n-1); } int main() { int n; while (cin >> n && n) { if (n == 1) cout << 1 << endl; else if (n == 2) cout << 2 << endl; else cout << resolve(n-2, n-1) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hidden_message.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1272 #include #include using namespace std; int main() { int n; cin >> n; string s; getline(cin, s); while (n--) { getline(cin, s); int can_get_letter = 1; string result = ""; for (int i = 0; i < s.size(); i++) { if (can_get_letter && s[i] != ' ') { result.push_back(s[i]); can_get_letter = 0; } else { if (s[i] == ' ') can_get_letter = 1; } } cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/highest_and_position.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1080 #include using namespace std; int main() { int n, max=0, index; for (int i = 1; i <= 100; i++) { cin >> n; if (n > max) { max = n; index = i; } } cout << max << endl << index << endl; return 0; } ================================================ FILE: competitive-programming/uri/hohoho.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1759 #include using namespace std; int main() { int n; cin >> n; for (int i = 0; i < n; i++) { if (n-1 == i) { cout << "Ho!" << endl; } else { cout << "Ho "; } } return 0; } ================================================ FILE: competitive-programming/uri/honey_reservoir.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2029 #include #include #include using namespace std; int main() { float vol, diam, area, height, pi=3.14, radius; while (scanf("%f %f", &vol, &diam) != EOF) { radius = diam / 2; area = pi * pow(radius, 2); height = vol / area; cout << fixed << setprecision(2) << "ALTURA = " << height << endl; cout << fixed << setprecision(2) << "AREA = " << area << endl; } return 0; } ================================================ FILE: competitive-programming/uri/hours_and_minutes.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1300 #include using namespace std; int main() { int angle; while (scanf("%i", &angle) != EOF) { if (angle % 6 == 0) cout << "Y" << endl; else cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/how_easy.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1243 #include #include #include using namespace std; bool correct_word(string word) { string not_word_part = "0123456789 ."; for (int j = 0; j < word.size(); j++) if (not_word_part.find(word[j]) != -1) return false; return true; } vector parse_string(string line) { vector v; string word = ""; for (int i = 0; i < line.size(); i++) { if (line[i] == ' ' && word.size() > 0) { if (correct_word(word)) v.push_back(word); word.clear(); } else if (line[i] == '.' && i < line.size() - 1 && line[i+1] == ' ' && word.size() > 0) { if (correct_word(word)) v.push_back(word); word.clear(); word += line[i]; } else if (i == line.size() - 1) { if (line[i] != '.') word += line[i]; if (correct_word(word)) v.push_back(word); word.clear(); } else { if (line[i] != ' ') word += line[i]; } } return v; } int main() { vector words; string phrase; int word_size_counter = 0, words_size, average; while (getline(cin, phrase)) { words = parse_string(phrase); words_size = words.size(); if (words_size) { for (int i = 0; i < words_size; i++) word_size_counter += words[i].size(); average = word_size_counter / words_size; if (average <= 3) cout << 250 << endl; else if (average <= 5) cout << 500 << endl; else cout << 1000 << endl; } else { cout << 250 << endl; } word_size_counter = 0; } return 0; } ================================================ FILE: competitive-programming/uri/huehue.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2242 #include #include using namespace std; string removeConsoants(string s) { string stringWithoutConsoants = "", vogals = "aeiou"; for (int i = 0; i < s.size(); i++) { if (vogals.find(s[i]) != -1) stringWithoutConsoants += s[i]; } return stringWithoutConsoants; } bool funniest(string s) { for (int i = 0; i < s.size(); i++) { if (s[i] != s[s.size()-i-1]) return false; } return true; } int main() { string s; cin >> s; s = removeConsoants(s); if (funniest(s)) cout << "S" << endl; else cout << "N" << endl; return 0; } ================================================ FILE: competitive-programming/uri/i_am_toorg.cpp ================================================ #include using namespace std; int main() { int N; cin >> N; while (N--) { cout << "I am Toorg!" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/ice_statuses.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1034 #include #include #include using namespace std; int min(int a, int b) { return (a < b)? a : b; } int main() { int T, N, M, num; cin >> T; while (T--) { cin >> N >> M; vector V; while (N--) { cin >> num; V.push_back(num); } sort(V.begin(), V.end()); int dp[V.size()][M+1]; for (int i = 0; i <= M; i++) dp[0][i] = i; for (int i = 1; i < V.size(); i++) { for (int j = 0; j <= M; j++) { if (V[i] <= j) dp[i][j] = min(1 + dp[i][j-V[i]], dp[i-1][j]); else dp[i][j] = dp[i-1][j]; } } cout << dp[V.size()-1][M] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/identifying_tea.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2006 #include using namespace std; int main() { int n, counter=5, total=0, x; cin >> n; while (counter--) { cin >> x; if (n == x) total++; } cout << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/image.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1516 #include #include #include using namespace std; string concatenate(char c, int times) { string new_string = ""; for (int i = 0; i < times; i++) new_string += c; return new_string; } int main() { int m, n, a, b; cin >> m >> n; while (m + n != 0) { string v = ""; vector draw; char pixel; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { cin >> pixel; v += pixel; } draw.push_back(v); v.clear(); } cin >> a >> b; int mult_m = a / m, mult_n = b / n; for (int i = 0; i < m; i++) { string line = ""; for (int j = 0; j < n; j++) line += concatenate(draw[i][j], mult_n); for (int x = 0; x < mult_m; x++) cout << line << endl; } cout << endl; draw.clear(); cin >> m >> n; } return 0; } ================================================ FILE: competitive-programming/uri/impar_par_roubo.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2059 #include using namespace std; int main() { int p, j1, j2, r, a; cin >> p >> j1 >> j2 >> r >> a; if (r == 1 && a == 1) cout << "Jogador 2 ganha!" << endl; else if (r == 1 && a == 0) cout << "Jogador 1 ganha!" << endl; else { int sum = j1 + j2; if (sum % 2 == 0 && p == 1) cout << "Jogador 1 ganha!" << endl; else if (sum % 2 == 0 && p == 0) cout << "Jogador 2 ganha!" << endl; else if (sum % 2 != 0 && p == 0) cout << "Jogador 1 ganha!" << endl; else cout << "Jogador 2 ganha!" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/inferior_area.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1188 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter1=5, counter2=7, count = 0; for (int i = 7; i < 12; i++) { for (int j = counter1; j < counter2; j++) { total += v1[i][j]; count++; } counter1--; counter2++; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/inside_out.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1235 #include #include using namespace std; int main() { int n; string line; cin >> n; cin.ignore(); while (n--) { getline(cin, line); int pos = line.size() / 2; string new_line = ""; for (int i = pos-1; i >= 0; i--) new_line += line[i]; for (int i = line.size()-1; i >= pos; i--) new_line += line[i]; cout << new_line << endl; } return 0; } ================================================ FILE: competitive-programming/uri/international_chat.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1581 #include #include #include using namespace std; int main() { int num, n; cin >> num; string lang; while (num--) { cin >> n; vector languages; for (int i = 0; i < n; i++) { cin >> lang; languages.push_back(lang); } string first_language = languages[0]; bool english = false; for (int j = 1; j < languages.size(); j++) { if (first_language != languages[j]) { english = true; break; } } if (english) cout << "ingles" << endl; else cout << first_language << endl; languages.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/internship.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2533 #include #include using namespace std; int main() { int M, N, C, sum_of_c, sum_of_nc; while(cin >> M) { sum_of_c = 0, sum_of_nc = 0; while (M--) { cin >> N >> C; sum_of_nc += N * C; sum_of_c += C; } cout << fixed << setprecision(4) << sum_of_nc / (sum_of_c * 100.00) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/interval.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1037 #include using namespace std; int main() { double n; cin >> n; // [0,25] (25,50], (50,75], (75,100] if (n >= 0.0 && n < 25.0) { cout << "Intervalo [0,25]" << endl; } else if (n > 25.0 && n <= 50.0) { cout << "Intervalo (25,50]" << endl; } else if (n > 50.0 && n <= 75.0) { cout << "Intervalo (50,75]" << endl; } else if (n > 75.0 && n <= 100.0) { cout << "Intervalo (75,100]" << endl; } else { cout << "Fora de intervalo" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/interval2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1072 #include using namespace std; int main() { int in=0, out=0, n, x; cin >> n; while (n--) { cin >> x; if (x >= 10 && x <= 20) { in++; } else { out++; } } cout << in << " in" << endl; cout << out << " out" << endl; return 0; } ================================================ FILE: competitive-programming/uri/inverse_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1984 #include #include using namespace std; int main() { string numbers, inverse=""; cin >> numbers; int numbers_size = numbers.size(); for (int i = numbers_size-1; i >= 0; i--) inverse += numbers[i]; cout << inverse << endl; return 0; } ================================================ FILE: competitive-programming/uri/is_triangle.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1929 #include using namespace std; int is_triangle(int a, int b, int c) { if ((a < b + c) && (b < a + c) && (c < a + b)) return 1; else return 0; } int main() { int a, b, c, d, triangle=0; cin >> a >> b >> c >> d; if (is_triangle(a, b, c) || is_triangle(a, b, d) || is_triangle(a, c, d) || is_triangle(b, c, d)) { cout << "S" << endl; } else { cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/jetiqui.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2587 #include #include using namespace std; int main() { int N, index1 = -1, index2; string word1, word2, word; cin >> N; while (N--) { cin >> word1 >> word2 >> word; for (int i = 0; i < word.size(); i++) { if (word[i] == '_') { if (index1 == -1) index1 = i; else index2 = i; } } if (word1[index1] == word2[index2] || word1[index2] == word2[index1]) cout << "Y" << endl; else cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/jingle_composing.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1430 #include #include #include using namespace std; int main() { string val, id = "WHQESTX"; vector v; v.push_back(1.0); v.push_back(1.0/2); v.push_back(1.0/4); v.push_back(1.0/8); v.push_back(1.0/16); v.push_back(1.0/32); v.push_back(1.0/64); while (cin >> val && val != "*") { int counter = 0; float duration = 0; int index; for (int i = 0; i < val.size(); i++) { if (val[i] == '/') { if (duration == 1) counter++; duration = 0; } else { index = id.find(val[i]); duration += v[index]; } } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/jogatina_ufpa.cpp ================================================ #include using namespace std; int main() { int N, I, UID, G, total; while (cin >> N >> I) { total = 0; while (N--) { cin >> UID >> G; if (UID == I && G == 0) total++; } cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/jogo_da_boca.py ================================================ n = input() print n % 3 ================================================ FILE: competitive-programming/uri/jollo.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1321 #include #include #include using namespace std; int main() { int a, b, c, x, y; cin >> a >> b >> c >> x >> y; vector prince; vector princess; while (a + b + c + x + y != 0) { princess.push_back(a); princess.push_back(b); princess.push_back(c); prince.push_back(x); prince.push_back(y); sort(princess.begin(), princess.end()); sort(prince.begin(), prince.end()); int princess_smaller = princess[0]; int prince_smaller = prince[0]; if (prince_smaller < princess_smaller) cout << -1 << endl; else { } cin >> a >> b >> c >> x >> y; } return 0; } ================================================ FILE: competitive-programming/uri/joulupukki.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2025 #include #include #include using namespace std; vector split(string s) { vector words; string word; int pos = 0; for (int i = 0; i < s.size(); i++) { if (s[i] == ' ') { word = s.substr(pos, i-pos); words.push_back(word); pos = i+1; } } word = s.substr(pos, s.size()-pos); words.push_back(word); return words; } string transformWord(string word) { if (word.size() == 10) { if (word.substr(1, 8) == "oulupukk") return "Joulupukki"; } else if (word.size() == 11) { if (word.substr(1, 8) == "oulupukk") return "Joulupukki."; } return word; } int main() { int n; cin >> n; cin.ignore(); string s; while (n--) { getline(cin, s); vector words = split(s); for (int i = 0; i < words.size(); i++) { if (i < words.size()-1) cout << transformWord(words[i]) << " "; else cout << transformWord(words[i]) << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/jumping_frog.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1961 #include using namespace std; int main() { int n, x, jump, before, after, win=1; cin >> jump >> n; cin >> x; before = x; while (n--) { cin >> x; after = x; if (after > before) { if (after - before > jump) { win = 0; break; } } else { if (before - after > jump) { win = 0; break; } } before = after; } if (win) cout << "YOU WIN" << endl; else cout << "GAME OVER" << endl; return 0; } ================================================ FILE: competitive-programming/uri/just_in_time.cpp ================================================ #include #include using namespace std; bool isPrimo(int n); int menorPrimo(int n); int main (void) { int N; cin >> N; cout << menorPrimo(N) << endl; return 0; } bool isPrimo(int n) { if (n < 2) return false; if (n == 2) return true; if (n % 2 == 0) return false; int sq = sqrt(n) + 1; for (int i = 3; i <= sq; i += 2) { if (n % i == 0) return false; } return true; } int menorPrimo(int n) { while (n >= 2) { if (isPrimo(n)) return n; n--; } return n; } ================================================ FILE: competitive-programming/uri/justifier.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1273 #include #include #include using namespace std; int get_greater_size(vector &v) { int max = 0; for (int i = 0; i < v.size(); i++) if (v[i].size() > max) max = v[i].size(); return max; } string concatenate_spaces(int n) { string spaces = ""; while (n--) spaces += " "; return spaces; } int main() { int n; cin >> n; string s, spaces; while (n) { vector v; while (n--) { cin >> s; v.push_back(s); } int greater_size = get_greater_size(v); for (int i = 0; i < v.size(); i++) { spaces = concatenate_spaces(greater_size - v[i].size()); v[i].insert(0, spaces); cout << v[i] << endl; } cin >> n; if (n) cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/justifier_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1273 #include #include #include using namespace std; int get_greater_size(vector &v) { int max = 0; for (int i = 0; i < v.size(); i++) if (v[i].size() > max) max = v[i].size(); return max; } string concatenate_spaces(int n) { string spaces = ""; while (n--) spaces += " "; return spaces; } string remove_first_spaces(string phrase) { string phrase_without_first_spaces = ""; bool can_assign = false; for (int i = 0; i < phrase.size(); i++) { if (phrase[i] != ' ') can_assign = true; if (can_assign) phrase_without_first_spaces += phrase[i]; } return phrase_without_first_spaces; } string remove_spaces(string phrase) { string phrase_without_spaces = ""; bool can_assign = false; for (int i = 0; i < phrase.size(); i++) { if (phrase[i] != ' ') { if (can_assign) phrase_without_spaces += " "; phrase_without_spaces += phrase[i]; } if (phrase[i] == ' ') can_assign = true; else can_assign = false; } return phrase_without_spaces; } int main() { int n; cin >> n; string s, spaces; while (n != 0) { vector v; int counter = 1; cin.ignore(); while (counter <= n) { getline(cin, s); s = remove_first_spaces(s); s = remove_spaces(s); v.push_back(s); counter++; } int greater_size = get_greater_size(v); for (int i = 0; i < v.size(); i++) { spaces = concatenate_spaces(greater_size - v[i].size()); v[i].insert(0, spaces); cout << v[i] << endl; } cin >> n; if (n) cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/kage_bunshin_no_jutsu.cpp ================================================ #include using namespace std; int jutsuNumber(long long int N) { if (N <= 1) return 0; return 1 + jutsuNumber(N / 2); } int main() { long long int N; while (cin >> N) { cout << jutsuNumber(N) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/kiloman.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1250 #include #include #include using namespace std; bool is_hit(vector &v, string js, int ind) { if (js[ind] == 'S' && (v[ind] == 1 || v[ind] == 2)) return true; if (js[ind] == 'J' && v[ind] > 2) return true; return false; } int main() { int n, x, temp; string js; vector v; cin >> n; while (n--) { int counter = 0; cin >> x; for (int i = 0; i < x; i++) { cin >> temp; v.push_back(temp); } cin >> js; for (int ind = 0; ind < x; ind++) if (is_hit(v, js, ind)) counter++; cout << counter << endl; v.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/koch_snowflake.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1760 #include #include #include using namespace std; int main() { int l; double total; while (cin >> l) { total = 8 * pow(l, 2) * (sqrt(3)) / 20; cout << fixed << setprecision(2) << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/lap.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1708 #include using namespace std; int main() { int n1, n2; while (cin >> n1 >> n2) { int t1=n1, t2=n2, counter=1; while(true) { counter++; t1 += n1; if (t1 <= t2) break; t2 += n2; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/laser_sculpture.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1107 #include #include using namespace std; int main() { vector v; int n1, n2, x; while (cin >> n1 >> n2 && n1 + n2 != 0) { for (int i = 0; i < n2; i++) { cin >> x; v.push_back(n1-x); } int counter = v[0]; for (int i = 1; i < n2; i++) { if (v[i] > v[i-1]) counter += v[i] - v[i-1]; } cout << counter << endl; v.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/last_analogimon.cpp ================================================ #include using namespace std; int main() { int N, M, cityX, cityY, monsterX, monsterY, X, seconds; while (cin >> N >> M) { seconds = 0; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cin >> X; if (X == 1) { cityY = i; cityX = j; } else if (X == 2) { monsterY = i; monsterX = j; } } } if (cityX > monsterX) seconds += cityX - monsterX; else seconds += monsterX - cityX; if (cityY > monsterY) seconds += cityY - monsterY; else seconds += monsterY - cityY; cout << seconds << endl; } return 0; } ================================================ FILE: competitive-programming/uri/laundry.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1794 #include using namespace std; int main() { int n, la, lb, sa, sb; cin >> n >> la >> lb >> sa >> sb; if (n >= la && n <= lb && n >= sa && n <= sb) cout << "possivel" << endl; else cout << "impossivel" << endl; return 0; } ================================================ FILE: competitive-programming/uri/leaders_impeachment.cpp ================================================ #include using namespace std; int main() { int N, X; double total = 0.0, rule = 2.0 / 3.0; while (cin >> N) { while (N--) { cin >> X; total += X; } if (total / N >= rule) cout << "impeachment" << endl; else cout << "acusacao arquivada" << endl; total = 0.0; } return 0; } ================================================ FILE: competitive-programming/uri/led.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1168 #include #include using namespace std; int main() { int n; string x; cin >> n; int ar[10] = { 6, 2, 5, 4, 5, 6, 3, 7, 6 }; while (n--) { cin >> x; int total = 0; for (int i = 0; i < x.size(); i++) { int num = (int)x[i]; total += ar[num]; } cout << total << " leds" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/left_area.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1188 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter1=1, count = 0; for (int i = 1; i < 11; i++) { for (int j = 0; j < counter1; j++) { total += v1[i][j]; count++; } if (i < 5) counter1++; else if (i > 5) counter1--; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/libertadores_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1536 #include #include #include #include using namespace std; vector parse_string(string line) { vector v; string word = ""; for (int i = 0; i < line.size(); i++) { if (line[i] == ' ') { v.push_back(word); word.clear(); } else if (i == line.size() - 1) { word += line[i]; v.push_back(word); word.clear(); } else { word += line[i]; } } return v; } int to_digit(char digit) { return digit - '0'; } int string_to_number(string n) { if (n == "") { return -1; } else { int num = 0; for (int i = 0; i < n.size(); i++) { num = num * 10 + to_digit(n[i]); } return num; } } struct team { int points; int goals_difference; int goals_away; }; int main() { vector matches; int n; cin >> n; cin.ignore(); string match; while (n--) { team team1, team2; team1.points = 0; team1.goals_difference = 0; team1.goals_away = 0; team2.points = 0; team2.goals_difference = 0; team2.goals_away = 0; getline(cin, match); matches = parse_string(match); int goals1 = string_to_number(matches.front()); int goals2 = string_to_number(matches.back()); if (goals1 > goals2) team1.points += 3; else if (goals1 < goals2) team2.points += 3; else { team1.points += 1; team2.points += 1; } team1.goals_difference += goals1; team2.goals_difference += goals2; team2.goals_away += goals2; getline(cin, match); matches = parse_string(match); goals1 = string_to_number(matches.front()); goals2 = string_to_number(matches.back()); if (goals1 > goals2) team2.points += 3; else if (goals1 < goals2) team2.points += 3; else { team1.points += 1; team2.points += 1; } team2.goals_difference += goals1; team1.goals_difference += goals2; team1.goals_away += goals2; if (team1.points > team2.points) cout << "Time 1" << endl; else if (team2.points > team1.points) cout << "Time 2" << endl; else if (team1.goals_difference > team2.goals_difference) cout << "Time 1" << endl; else if (team1.goals_difference < team2.goals_difference) cout << "Time 2" << endl; else if (team1.goals_away > team2.goals_away) cout << "Time 1" << endl; else if (team1.goals_away < team2.goals_away) cout << "Time 2" << endl; else cout << "Penaltis" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/libertadores_2.cpp ================================================ #include #include #include using namespace std; int main() { int T; cin>>T; while(T--) { int ga=0, gb=0, va=0, vb=0, gaw=0, gbw=0; int a, b; scanf("%d x %d", &a, &b); if(a>b) va++; if(b>a) vb++; ga += a; gb += b; gbw = b; scanf("%d x %d", &b, &a); if(a>b) va++; if(b>a) vb++; ga += a; gb += b; gaw = a; if(va > vb) cout<<"Time 1\n"; else if(vb > va) cout<<"Time 2\n"; else if(ga > gb) cout<<"Time 1\n"; else if(gb > ga) cout<<"Time 2\n"; else if(gaw > gbw) cout<<"Time 1\n"; else if(gbw > gaw) cout<<"Time 2\n"; else cout<<"Penaltis\n"; } return 0; } ================================================ FILE: competitive-programming/uri/line_in_array.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1181 #include #include #include #include using namespace std; int main() { int line; double n; cin >> line; string t; cin >> t; vector< vector > v1; for (int i = 0; i < 12; i++) { vector v2; for (int j = 0; j < 12; j++) { cin >> n; v2.push_back(n); } v1.push_back(v2); } if (t == "S") { double sum = 0; for (int i = 0; i < 12; i++) sum += v1[line][i]; cout << fixed << setprecision(1) << sum << endl; } else if (t == "M") { double average = 0; for (int i = 0; i < 12; i++) average += v1[line][i]; cout << fixed << setprecision(1) << average / 12 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/linear_parking_lot.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1523 #include #include using namespace std; struct car { int arrive; int left; }; int main() { int N, K, arrive, left; bool can; cin >> N >> K; while (N + K != 0) { vector parking_lot; can = true; while (N--) { cin >> arrive >> left; car c; c.arrive = arrive; c.left = left; while (parking_lot.size() > 0 && parking_lot.back().left <= arrive) parking_lot.pop_back(); if ((parking_lot.size() >= K && c.arrive < parking_lot.back().left) || parking_lot.size() > 0 && c.left > parking_lot.back().left) { can = false; } else { parking_lot.push_back(c); } } if (can) cout << "Sim" << endl; else cout << "Nao" << endl; cin >> N >> K; } return 0; } ================================================ FILE: competitive-programming/uri/little_ant.cpp ================================================ #include using namespace std; int main() { int n; long long int x; cin >> n; while (n--) { cin >> x; cout << (x+1) / 2 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/little_ducks.py ================================================ # https://www.urionlinejudge.com.br/judge/en/problems/view/2334 n = int(raw_input()) while n != -1: if n == 0: print(0) else: print(n - 1) n = int(raw_input()) ================================================ FILE: competitive-programming/uri/logical_sequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1144 #include using namespace std; int main() { int n, i=1; int count1=1, count2=1, count3=1; int x1=1, x2=2; int y1=1, y2=1, y3=1, y4=2; cin >> n; n *= 2; while (n--) { cout << i << " " << x1 << " " << y1 << endl; if (count1 % 2 == 0) { i++; } if (count2 % 2 == 0) { x1 += x2; x2 += 2; } else { x1++; } if (count3 % 2 == 0) { y2 = 6 * y3; y1 += y2; y3 += y4; y4++; } else { y1++; } count1++; count2++; count3++; } return 0; } ================================================ FILE: competitive-programming/uri/logical_sequence_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1145 #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; for (int i = 1; i <= n2; i++) { cout << i; if (i % n1 == 0) cout << endl; else cout << " "; } return 0; } ================================================ FILE: competitive-programming/uri/lost_boots.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1245 #include #include #include #include using namespace std; int main() { int n; while (cin >> n) { map > boots; int num; string side; for (int i = 0; i < n; i++) { cin >> num >> side; if (boots.find(num) == boots.end()) { map sides; sides[side] = 1; boots[num] = sides; } else { if (boots[num].find(side) == boots[num].end()) { boots[num][side] = 1; } else { boots[num][side]++; } } } int counter = 0; for (map >::iterator it = boots.begin(); it != boots.end(); it++) { if (it->second["D"] < it->second["E"]) counter += it->second["D"]; else counter += it->second["E"]; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/lowest_number_and_position.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1180 #include using namespace std; int main() { int n, position, lowest=1001, x; cin >> n; for (int i = 0; i < n; i++) { cin >> x; if (x < lowest) { lowest = x; position = i; } } cout << "Menor valor: " << lowest << endl; cout << "Posicao: " << position << endl; return 0; } ================================================ FILE: competitive-programming/uri/lu_di_oh.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2542 #include #include using namespace std; int main() { int N, M, L, X, m_choice, l_choice; while (cin >> N) { vector< vector > m_cards; vector< vector > l_cards; cin >> M >> L; while (M--) { vector card; for (int i = 0; i < N; i++) { cin >> X; card.push_back(X); } m_cards.push_back(card); } while (L--) { vector card; for (int i = 0; i < N; i++) { cin >> X; card.push_back(X); } l_cards.push_back(card); } cin >> m_choice >> l_choice >> X; if (m_cards[m_choice-1][X-1] > l_cards[l_choice-1][X-1]) cout << "Marcos" << endl; else if (m_cards[m_choice-1][X-1] < l_cards[l_choice-1][X-1]) cout << "Leonardo" << endl; else cout << "Empate" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/lucro.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1310 #include using namespace std; int max(int a, int b) { return (a > b)? a : b; } int main() { int N, C, pricePerDay; while (cin >> N >> pricePerDay) { int revenue[N+1]; revenue[0] = 0; for (int i = 1; i <= N; i++) { cin >> C; revenue[i] = C; } int dp[N+1][N+1]; for (int i = 0; i < N+1; i++) { for (int j = 0; j < N+1; j++) { if (i != 0 && i == j) dp[i][j] = revenue[i] - pricePerDay; else dp[i][j] = 0; } } for (int i = 1; i < N+1; i++) { for (int j = i+1; j < N+1; j++) { if (dp[i][j] == 0) dp[i][j] = dp[i][j-1] + dp[j][j]; } } int greater = 0; for (int i = 1; i < N+1; i++) { for (int j = i; j < N+1; j++) { greater = max(dp[i][j], greater); } } cout << greater << endl; } return 0; } ================================================ FILE: competitive-programming/uri/lucro_otimizado.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1310 #include using namespace std; int max(int a, int b) { return (a > b)? a : b; } int main() { int N, C, pricePerDay; while (cin >> N >> pricePerDay) { int dp[N+1][N+1] = {}; for (int i = 1; i <= N; i++) { cin >> C; dp[i][i] = C - pricePerDay; } for (int i = 1; i < N+1; i++) { for (int j = i+1; j < N+1; j++) { if (dp[i][j] == 0) dp[i][j] = dp[i][j-1] + dp[j][j]; } } int greater = 0; for (int i = 1; i < N+1; i++) { for (int j = i; j < N+1; j++) { greater = max(dp[i][j], greater); } } cout << greater << endl; } return 0; } ================================================ FILE: competitive-programming/uri/macpronalts.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1985 #include #include using namespace std; double total_price(int code, int number) { double total; if (code == 1001) total = number * 1.5; else if (code == 1002) total = number * 2.5; else if (code == 1003) total = number * 3.5; else if (code == 1004) total = number * 4.5; else if (code == 1005) total = number * 5.5; return total; } int main() { int n, code, number; double total=0; cin >> n; while (n--) { cin >> code >> number; total += total_price(code, number); } cout << fixed << setprecision(2) << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/maesters_map.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1855 #include #include #include using namespace std; int main() { int n1, n2, i=0, j=0, found=0, direction=0; cin >> n2 >> n1; vector v; string x; for (int i = 0; i < n1; i++) { cin >> x; v.push_back(x); } if (v[i][j] != '.') { while (true) { if (v[i][j] == '*') { found = 1; break; } if (v[i][j] == 'X') break; if (v[i][j] == '>') { direction = 1; v[i][j] = 'X'; } else if (v[i][j] == 'v') { direction = 2; v[i][j] = 'X'; } else if (v[i][j] == '<') { direction = 3; v[i][j] = 'X'; } else if (v[i][j] == '^') { direction = 4; v[i][j] = 'X'; } else { v[i][j] = 'X'; } if (direction == 1) { j++; } else if (direction == 2) { i++; } else if (direction == 3) { j--; } else if (direction == 4) { i--; } } } if (found) cout << "*" << endl; else cout << "!" << endl; return 0; } ================================================ FILE: competitive-programming/uri/mean_median_problem.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1379 #include #include using namespace std; int is_integer(double n) { if (floor(n) == n) return 1; else return 0; } int main() { unsigned long long int n1, n2; long long int n3; cin >> n1 >> n2; while (n1 + n2 != 0) { unsigned long long int mean, median; int found = 0; if (n1 < n2) median = n1; else median = n2; if (is_integer(median * 3 - n1 - n2)) { n3 = median * 3 - n1 - n2; found = 1; } cout << n3 << endl; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/medal_table.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2312 #include #include #include #include using namespace std; struct country { string name; int gold; int silver; int bronze; }; bool compareByMedals(const country &c1, const country &c2) { if (c1.gold > c2.gold) return true; else if (c1.gold == c2.gold) { if (c1.silver > c2.silver) return true; else if (c1.silver == c2.silver) { if (c1.bronze > c2.bronze) return true; else if (c1.bronze == c2.bronze) return c1.name < c2.name; } } return false; } int main() { string country_name; int n, gold, silver, bronze; cin >> n; vector countries; while (n--) { cin >> country_name >> gold >> silver >> bronze; country c; c.name = country_name; c.gold = gold; c.silver = silver; c.bronze = bronze; countries.push_back(c); } sort(countries.begin(), countries.end(), compareByMedals); for (int i = 0; i < countries.size(); i++) { cout << countries[i].name << " " << countries[i].gold << " " << countries[i].silver << " " << countries[i].bronze << endl; } return 0; } ================================================ FILE: competitive-programming/uri/merry_christmaaaas.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2483 #include #include using namespace std; string happiness_index(int index) { string result = ""; while (index--) result += "a"; return result; } int main() { cout << "Feliz nat"; int index; cin >> index; cout << happiness_index(index); cout << "l!" << endl; } ================================================ FILE: competitive-programming/uri/mirror_sequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2157 #include #include #include using namespace std; string toString(int n) { stringstream ss; ss << n; return ss.str(); } string reverseString(string s) { string reversedString = ""; for (int i = s.size()-1; i >= 0; i--) reversedString += s[i]; return reversedString; } int main() { int n, min, max; string n1, n2, result, numbers = "0123456789"; cin >> n; while (n--) { cin >> min >> max; result = ""; for (int i = min; i <= max; i++) { result += toString(i); } result += reverseString(result); cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/mjolnir.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1865 #include #include using namespace std; int main() { string hero; int n, force; cin >> n; while (n--) { cin >> hero >> force; if (hero == "Thor") cout << "Y" << endl; else cout << "N" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/monetary_formatting.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1309 #include #include using namespace std; bool under_ten(string cents) { if (cents == "0" || cents == "1" || cents == "2" || cents == "3" || cents == "4" || cents == "5" || cents == "6" || cents == "7" || cents == "8" || cents == "9") return true; return false; } string reverse_string(string s) { string result_string = ""; for (int i = s.size()-1; i >= 0; i--) result_string += s[i]; return result_string; } string parse_string(string s, string cents) { string new_s = ""; new_s += cents[1]; new_s += cents[0]; new_s += "."; int comma = 1; for (int i = s.size()-1; i >= 0; i--) { new_s += s[i]; if (comma == 3 && i != 0) { new_s += ","; comma = 1; } else { comma++; } } new_s += "$"; new_s = reverse_string(new_s); return new_s; } int main() { string money, cents; while (cin >> money) { cin >> cents; if (under_ten(cents)) cents = "0" + cents; int money_size = money.size(); string real_money = parse_string(money, cents); cout << real_money << endl; } return 0; } ================================================ FILE: competitive-programming/uri/montanha_russa.cpp ================================================ #include using namespace std; int main() { int N, min, max, X, total; while (cin >> N >> min >> max) { total = 0; while (N--) { cin >> X; if (X >= min && X <= max) total++; } cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/month.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1052 #include #include #include using namespace std; int main() { vector v; v.push_back("January"); v.push_back("February"); v.push_back("March"); v.push_back("April"); v.push_back("May"); v.push_back("June"); v.push_back("July"); v.push_back("August"); v.push_back("September"); v.push_back("October"); v.push_back("November"); v.push_back("December"); int n; cin >> n; cout << v[n-1] << endl; return 0; } ================================================ FILE: competitive-programming/uri/moon_phases.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1893 #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; if (n2 >= 97 && n2 <= 100) cout << "cheia" << endl; else if (n2 >= 0 && n2 <= 2) cout << "nova" << endl; else if (n1 < n2) cout << "crescente" << endl; else cout << "minguante" << endl; return 0; } ================================================ FILE: competitive-programming/uri/morse.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2338 #include #include using namespace std; void createMorseTable(map &morse) { morse[".-"] = "a"; morse["-..."] = "b"; morse["-.-."] = "c"; morse["-.."] = "d"; morse["."] = "e"; morse["..-."] = "f"; morse["--."] = "g"; morse["...."] = "h"; morse[".."] = "i"; morse[".---"] = "j"; morse["-.-"] = "k"; morse[".-.."] = "l"; morse["--"] = "m"; morse["-."] = "n"; morse["---"] = "o"; morse[".--."] = "p"; morse["--.-"] = "q"; morse[".-."] = "r"; morse["..."] = "s"; morse["-"] = "t"; morse["..-"] = "u"; morse["...-"] = "v"; morse[".--"] = "w"; morse["-..-"] = "x"; morse["-.--"] = "y"; morse["--.."] = "z"; } string buildCode(string partial, int j) { if (partial.find("...") != string::npos) { return morse[substr(j, partial.find("..."))]; } return morse[substr(partial.find("...")+3, partial.size()-partial.find("...")+3)]; } int main() { int N, i, j; string s, result, partial; while (N--) { map morse; createMorseTable(morse); cin >> s; result = ""; i = 0, j = 0; while (i < s.size()) { if (s.find(".......") != string::npos) { while (j < s.size()) { partial = substr(i, s.find(".......")); result += buildCode(partial, j); j = partial.find("...")+3; } } else { while (j < s.size()) { partial = substr(i, s.size()-s.find(".......")+7); result += buildCode(partial, j); j = partial.find("...")+3; } } } } return 0; } ================================================ FILE: competitive-programming/uri/motoboy.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1286 #include #include #include using namespace std; int max(int a, int b) { return a > b? a : b; } struct Obj { int time, pizza; }; bool sortByPizza(Obj obj1, Obj obj2) { if (obj1.pizza < obj2.pizza) return true; else if (obj1.pizza > obj2.pizza) return false; else return obj1.time < obj2.time; } int main() { int N, P, time, pizza; while (cin >> N && N) { vector objects; cin >> P; for (int i = 0; i < N; i++) { cin >> time >> pizza; Obj object; object.time = time; object.pizza = pizza; objects.push_back(object); } sort(objects.begin(), objects.end(), sortByPizza); int dp[N][P+1]; for (int i = 0; i <= P; i++) { if (objects[0].pizza <= i) dp[0][i] = objects[0].time; else dp[0][i] = 0; } for (int i = 1; i < N; i++) { for (int j = 0; j < P; j++) { if (j - objects[i].pizza >= 0) dp[i][j] = max(dp[i-1][j - objects[i].pizza] + objects[i].time, dp[i-1][j]); else dp[i][j] = dp[i-1][j]; } } cout << dp[N-1][P-1] << " min."<< endl; } return 0; } ================================================ FILE: competitive-programming/uri/multiple_of_13.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1132 #include using namespace std; int main() { int x, y, total=0; cin >> x >> y; if (x < y) { for (int i = x; i <= y; i++) { if (i % 13 != 0) { total += i; } } } else { for (int i = y; i <= x; i++) { if (i % 13 != 0) { total += i; } } } cout << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/multiple_reading.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1262 #include #include using namespace std; int main() { int n; string process; while (cin >> process) { cin >> n; int counter = 0; int number_of_rs = 0; for (int i = 0; i < process.size(); i++) { if (process[i] == 'W') { counter++; number_of_rs = 0; } else { if (number_of_rs == 0) counter++; number_of_rs++; } if (number_of_rs >= n) number_of_rs = 0; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/multiples.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1044 #include using namespace std; int is_multiple(int n1, int n2) { if (n1 > n2) { if (n1 % n2 == 0) return 1; else return 0; } else if (n2 > n1) { if (n2 % n1 == 0) return 1; else return 0; } return 1; } int main() { int n1, n2; cin >> n1 >> n2; if (is_multiple(n1, n2)) { cout << "Sao Multiplos" << endl; } else { cout << "Nao sao Multiplos" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/multiplication_table.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1078 #include using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= 10; i++) { cout << i << " x " << n << " = " << n * i << endl; } return 0; } ================================================ FILE: competitive-programming/uri/musical_loop.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1089 #include #include using namespace std; int main() { int n, picos=0, temp; vector loop; cin >> n; while (n != 0) { for (int i = 0; i < n; i++) { cin >> temp; loop.push_back(temp); } loop.push_back(loop[0]); loop.push_back(loop[1]); for (int i = 1; i <= n; i++) { if ((loop[i] > loop[i-1] && loop[i] > loop[i+1]) || (loop[i] < loop[i-1] && loop[i] < loop[i+1])) picos++; } cout << picos << endl; picos = 0; loop.clear(); cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/name_at_form.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2160 #include #include using namespace std; int main() { string phrase; getline(cin, phrase); if (phrase.size() <= 80) cout << "YES" << endl; else cout << "NO" << endl; return 0; } ================================================ FILE: competitive-programming/uri/natural_sum.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1805 #include using namespace std; int main() { unsigned long long int n1, n2, total; cin >> n1 >> n2; total = (n1 + n2) * (n2 - n1 + 1) / 2; cout << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/new_record.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2551 #include using namespace std; int main() { int N; double best, time, distance; while (cin >> N) { best = 0; for (int i = 1; i <= N; i++) { cin >> time >> distance; if (distance / time > best) { best = distance / time; cout << i << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/nine.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2217 #include using namespace std; int main() { int n; long long int num; cin >> n; while (n--) { cin >> num; if (num % 2 == 0) cout << 1 << endl; else cout << 9 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/number_frequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1171 #include #include #include using namespace std; int get_position(vector< pair >& v, int el) { for (int i = 0; i < v.size(); i++) if (el == v[i].first) return i; return v.size(); } int main() { int n, x; cin >> n; vector< pair > v; cin >> x; v.push_back(make_pair(x, 1)); n--; while (n--) { cin >> x; if (get_position(v, x) < v.size()) v[get_position(v, x)].second++; else v.push_back(make_pair(x, 1)); } sort(v.begin(), v.end()); for (int i = 0; i < v.size(); i++) cout << v[i].first << " aparece " << v[i].second << " vez(es)" << endl; return 0; } ================================================ FILE: competitive-programming/uri/obi_uri.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2062 #include #include #include using namespace std; int main() { int n; cin >> n; string s, ns; vector v; while (n--) { cin >> s; v.push_back(s); } vector v1; for (int i = 0; i < v.size(); i++) { if (v[i].size() == 3) { if (v[i].substr(0, 2) == "UR") v1.push_back("URI"); else if (v[i].substr(0, 2) == "OB") v1.push_back("OBI"); else v1.push_back(v[i]); } else { v1.push_back(v[i]); } } for (int i = 0; i < v1.size(); i++) { if (i == v1.size()-1) cout << v1[i]; else cout << v1[i] << " "; } cout << endl; return 0; } ================================================ FILE: competitive-programming/uri/odd_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1067 #include using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { if (i % 2 != 0) cout << i << endl; } return 0; } ================================================ FILE: competitive-programming/uri/og.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1387 #include using namespace std; int main() { int n1, n2; cin >> n1 >> n2; while (n1 + n2 != 0) { cout << n1 + n2 << endl; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/one_two_three.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1332 #include #include #include using namespace std; int verify_num(string num, string number, int n) { int total = num.size(), sum = 0; for (int j = 0; j < num.size(); j++) if (num[j] == number[j]) sum++; if (sum + 1 >= total) return n; return -1; } int main() { int n; cin >> n; string number; vector numbers; numbers.push_back("one"); numbers.push_back("two"); numbers.push_back("three"); while (n--) { cin >> number; for (int i = 0; i < 3; i++) { int result = verify_num(numbers[i], number, i+1); if (result != -1) { cout << result << endl; break; } } } return 0; } ================================================ FILE: competitive-programming/uri/operator_game.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2493 #include #include #include #include using namespace std; struct operation { int first_operator; int second_operator; int result; }; bool is_result_correct(const operation &op, string oper) { bool sum_correct = op.first_operator + op.second_operator == op.result, subtraction_correct = op.first_operator - op.second_operator == op.result, multiplication_correct = op.first_operator * op.second_operator == op.result; return (oper == "+" && sum_correct || oper == "-" && subtraction_correct || oper == "*" && multiplication_correct || oper == "I" && !sum_correct && !subtraction_correct && !multiplication_correct); } int main() { int N, first_operator, second_operator, result, ID; char useless; string name, oper; while (cin >> N) { vector operations; vector people; for (int i = 0; i < N; i++) { cin >> first_operator >> second_operator >> useless >> result; operation op; op.first_operator = first_operator; op.second_operator = second_operator; op.result = result; operations.push_back(op); } for (int i = 0; i < N; i++) { cin >> name >> ID >> oper; if (!is_result_correct(operations[ID-1], oper)) people.push_back(name); } if (people.size() == N) { cout << "None Shall Pass!" << endl; } else if (people.size() > 0) { sort(people.begin(), people.end()); cout << people[0]; for (int i = 1; i < people.size(); i++) cout << " " << people[i]; cout << endl; } else { cout << "You Shall All Pass!" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/optical_reader.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1129 #include #include using namespace std; int main() { int n, counter=0, num, result; string results = "ABCDE"; cin >> n; while (n != 0) { for (int j = 0; j < n; j++) { for (int i = 0; i < 5; i++) { cin >> num; if (num <= 127) { counter++; result = i; } } if (counter != 1) cout << "*" << endl; else cout << results[result] << endl; counter = 0; } cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/our_days_are_never_coming_back.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1864 #include #include using namespace std; int main() { int n; cin >> n; string text = "LIFE IS NOT A PROBLEM TO BE SOLVED"; string final = ""; for (int i = 0; i < n; i++) final += text[i]; cout << final << endl; return 0; } ================================================ FILE: competitive-programming/uri/painel_led.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2292 #include #include using namespace std; char change_light(char type, int num, bool change) { if (type == 'X' && num == 0 && change) return 'O'; if (type == 'O' && num == 0 && change) return 'X'; if (type == 'X' && num == 1) return 'O'; if (type == 'O' && num == 1) return 'X'; if (type == 'X' && num % 2 != 0) return 'O'; if (type == 'O' && num % 2 != 0) return 'X'; if (num % 2 == 0) return type; } int main() { int N, num; string s, result; bool change; cin >> N; while (N--) { change = false; cin >> s >> num; result = ""; for (int i = 0; i < s.size(); i++) { result += change_light(s[i], num, change); change = change_light(s[i], num, change) == s[i]; num /= 2; } cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/palindrome_game.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2588 #include #include #include using namespace std; int main() { string s; int N; while (cin >> s) { map mapper; N = 0; for (int i = 0; i < s.size(); i++) { if (mapper.find(s[i]) != mapper.end()) mapper.find(s[i])->second++; else mapper[s[i]] = 1; } for (map::iterator it = mapper.begin(); it != mapper.end(); it++) if (it->second % 2 != 0) N++; if (N == 0) cout << 0 << endl; else cout << --N << endl; } return 0; } ================================================ FILE: competitive-programming/uri/pandorgas.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1585 #include using namespace std; int main() { int result; float n, n1, n2; cin >> n; while (n--) { cin >> n1 >> n2; result = n1 * n2 / 2; cout << result << " cm2" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/pao_de_queijo_sweeper.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2552 #include #include using namespace std; int calculate(const vector< vector > &matrix, int i, int j, int max_line, int max_column) { if (matrix[i][j] == 1) return 9; int total = 0; if (i+1 <= max_line) total += matrix[i+1][j]; // bottom if (i-1 >= 0) total += matrix[i-1][j]; // top if (j+1 <= max_column) total += matrix[i][j+1]; // right if (j-1 >= 0) total += matrix[i][j-1]; // left return total; } int main() { int N, M, X; while (cin >> N >> M) { vector< vector > matrix; for (int i = 0; i < N; i++) { vector V; for (int j = 0; j < M; j++) { cin >> X; V.push_back(X); } matrix.push_back(V); } for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { cout << calculate(matrix, i, j, N-1, M-1); } cout << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/parafusos_e_porcas.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/1520 #include #include #include using namespace std; int main() { int N, n1, n2; while (cin >> N) { vector V; while (N--) { cin >> n1 >> n2; for (int i = n1; i <= n2; i++) { V.push_back(i); } } sort(V.begin(), V.end()); cin >> N; n1 = -1; n2 = -1; for (int i = 0; i < V.size(); i++) { if (N == V[i]) { n1 = i; break; } } for (int i = V.size()-1; i >= 0; i--) { if (N == V[i]) { n2 = i; break; } } if (n1 != -1 && n2 != -1) cout << N << " found from " << n1 << " to " << n2 << endl; else cout << N << " not found" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/parenthesis_balance.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1068 #include #include using namespace std; int main() { string operation; int open = 0, close = 0; bool correct = true; while (getline(cin, operation)) { for (int i = 0; i < operation.size(); i++) { if (operation[i] == '(') { open++; } else if (operation[i] == ')') { close++; if (open < close) { break; correct = false; } } } if (correct && open == close) cout << "correct" << endl; else cout << "incorrect" << endl; open = 0; close = 0; correct = true; } return 0; } ================================================ FILE: competitive-programming/uri/parity.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2176 #include #include using namespace std; int main() { int numOfOneBits = 0; string s; cin >> s; for (int i = 0; i < s.size(); i++) if (s[i] == '1') numOfOneBits++; if (numOfOneBits % 2 == 0) s += '0'; else s += '1'; cout << s << endl; return 0; } ================================================ FILE: competitive-programming/uri/pascal_library.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1267 #include #include using namespace std; int main() { int alumnis, dinners, temp; vector al; cin >> alumnis >> dinners; while (alumnis + dinners != 0) { bool didit = false; for (int i = 0; i < alumnis; i++) al.push_back(0); for (int j = 0; j < dinners; j++) { for (int i = 0; i < alumnis; i++) { cin >> temp; if (temp) al[i]++; } } for (int i = 0; i < alumnis; i++) { if (al[i] == dinners) { didit = true; break; } } if (didit) cout << "yes" << endl; else cout << "no" << endl; al.clear(); cin >> alumnis >> dinners; } return 0; } ================================================ FILE: competitive-programming/uri/password.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2146 #include using namespace std; int main() { int n; while (cin >> n) { cout << n-1 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/password_validator.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2253 #include #include using namespace std; bool validateString(string s) { string alphabetUppercase = "ABCDEFGHIJKLMNOPQRSTUVXWYZ"; string alphabetLowercase = "abcdefghijklmnopqrstuvxwyz"; string numbers = "0123456789"; bool hasUppercasedChar = false, hasLowercasedChar = false, hasNumber = false; for (int i = 0; i < s.size(); i++) { if (alphabetUppercase.find(s[i]) != string::npos) hasUppercasedChar = true; if (alphabetLowercase.find(s[i]) != string::npos) hasLowercasedChar = true; if (numbers.find(s[i]) != string::npos) hasNumber = true; } return hasUppercasedChar && hasLowercasedChar && hasNumber; } bool validatePunctuation(string s) { if (s.find("á") == string::npos && s.find("é") == string::npos && s.find("í") == string::npos && s.find("ó") == string::npos && s.find("ú") == string::npos && s.find("Á") == string::npos && s.find("É") == string::npos && s.find("Í") == string::npos && s.find("Ó") == string::npos && s.find("Ú") == string::npos && s.find("â") == string::npos && s.find("ê") == string::npos && s.find("î") == string::npos && s.find("ô") == string::npos && s.find("û") == string::npos && s.find("Â") == string::npos && s.find("Ê") == string::npos && s.find("Î") == string::npos && s.find("Ô") == string::npos && s.find("Û") == string::npos && s.find("ã") == string::npos && s.find("ẽ") == string::npos && s.find("ĩ") == string::npos && s.find("õ") == string::npos && s.find("ũ") == string::npos && s.find("Ã") == string::npos && s.find("Ẽ") == string::npos && s.find("Ĩ") == string::npos && s.find("Õ") == string::npos && s.find("Ũ") == string::npos && s.find("à") == string::npos && s.find("è") == string::npos && s.find("ì") == string::npos && s.find("ò") == string::npos && s.find("ù") == string::npos && s.find("À") == string::npos && s.find("È") == string::npos && s.find("Ì") == string::npos && s.find("Ò") == string::npos && s.find("Ù") == string::npos && s.find(".") == string::npos && s.find(",") == string::npos && s.find(";") == string::npos && s.find("!") == string::npos && s.find("?") == string::npos && s.find(":") == string::npos && s.find("(") == string::npos && s.find(")") == string::npos && s.find("[") == string::npos && s.find("]") == string::npos && s.find("{") == string::npos && s.find("}") == string::npos && s.find("-") == string::npos && s.find("\"") == string::npos && s.find("\\") == string::npos && s.find("/") == string::npos && s.find("...") == string::npos && s.find("'") == string::npos && s.find("^") == string::npos && s.find("`") == string::npos && s.find("~") == string::npos && s.find("+") == string::npos && s.find("-") == string::npos && s.find("=") == string::npos && s.find("_") == string::npos && s.find("*") == string::npos && s.find("&") == string::npos && s.find("¨") == string::npos && s.find("%") == string::npos && s.find("$") == string::npos && s.find("#") == string::npos && s.find("@") == string::npos && s.find(">") == string::npos && s.find("<") == string::npos && s.find(" ") == string::npos) return true; return false; } bool validateSize(string s) { if (s.size() >= 6 && s.size() <= 32) return true; return false; } int main() { string s; while (getline(cin, s)) { if (validateString(s) && validatePunctuation(s) && validateSize(s)) cout << "Senha valida." << endl; else cout << "Senha invalida." << endl; } return 0; } ================================================ FILE: competitive-programming/uri/paulas_mathematic_game.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1192 #include #include #include using namespace std; int main() { int n; cin >> n; while (n--) { string x; cin >> x; int n1 = x[0] - 48; int n2 = x[2] - 48; if (n1 == n2) { cout << n1 * n2 << endl; } else if (isupper(x[1])) { cout << n2 - n1 << endl; } else { cout << n1 + n2 << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/peaks_and_valleys.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2162 #include using namespace std; int main() { int n, first, second, result = 1; bool bigger; cin >> n >> first >> second; n -= 2; if (first > second) { bigger = true; } else if (first < second) { bigger = false; } else { cout << 0 << endl; return 0; } while (n--) { first = second; cin >> second; if (first > second && !bigger) bigger = true; else if (first < second && bigger) bigger = false; else result = 0; } cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/pedrinhos_christmas.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2139 #include using namespace std; int main() { int month, day, days; int daysInEachMonth[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 25 }; while (cin >> month >> day) { if (month == 12) { if (day < 24) cout << "Faltam " << 25 - day << " dias para o natal!" << endl; else if (day == 24) cout << "E vespera de natal!" << endl; else if (day == 25) cout << "E natal!" << endl; else cout << "Ja passou!" << endl; } else { days = daysInEachMonth[month-1] - day; for (int i = month; i < 12; i++) days += daysInEachMonth[i]; cout << "Faltam " << days << " dias para o natal!" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/pepe.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2152 #include #include using namespace std; string parsePhrase(string hour, string minute, int opened) { string parsedHour, parsedMinute, numbers = "0123456789"; if (hour.size() == 1) parsedHour = "0" + hour; else parsedHour = hour; if (minute.size() == 1) parsedMinute = "0" + minute; else parsedMinute = minute; if (opened) return parsedHour + ":" + parsedMinute + " - A porta abriu!"; else return parsedHour + ":" + parsedMinute + " - A porta fechou!"; } int main() { int n, opened; string hour, minute; cin >> n; while (n--) { cin >> hour >> minute >> opened; cout << parsePhrase(hour, minute, opened) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/perfect_number.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1164 #include using namespace std; int main() { int n, x, total=0; cin >> n; while (n--) { cin >> x; for (int i = 1; i < x; i++) { if (x % i == 0) total += i; if (total > x) break; } if (total == x) cout << x << " eh perfeito" << endl; else cout << x << " nao eh perfeito" << endl; total = 0; } return 0; } ================================================ FILE: competitive-programming/uri/phin_bonati.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2149 #include using namespace std; long long int willBonatiAlgorithm(int n) { long long int n1 = 0, n2 = 1, result; if (n == 1) return 0; else if (n == 2) return 1; else { for (int i = 3; i <= n; i++) { if (i % 2 != 0) result = n1 + n2; else result = n1 * n2; n1 = n2; n2 = result; } } return result; } int main() { int n; long long int result; while (cin >> n) { result = willBonatiAlgorithm(n); cout << result << endl; } } ================================================ FILE: competitive-programming/uri/pizza_pre_bh.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2554 #include #include using namespace std; struct date { int day; int month; int year; }; int main() { int N, D, X, day, month, year, total, result; char useless; while (cin >> N >> D) { result = -1; vector dates; for (int j = 0; j < D; j++) { total = 0; cin >> day >> useless >> month >> useless >> year; date d; d.day = day; d.month = month; d.year = year; dates.push_back(d); for (int i = 0; i < N; i++) { cin >> X; total += X; } if (total == N && result == -1) result = j; } if (result == -1) cout << "Pizza antes de FdI" << endl; else cout << dates[result].day << "/" << dates[result].month << "/" << dates[result].year << endl; } return 0; } ================================================ FILE: competitive-programming/uri/pokemon.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1836 #include #include #include using namespace std; int main() { int n, l, b, iv, e, result; string pokemon; cin >> n; for (int i = 1; i <= n; i++) { cin >> pokemon >> l; cout << "Caso #" << i << ": " << pokemon << " nivel " << l << endl; for (int j = 0; j < 4; j++) { cin >> b >> iv >> e; if (j == 0) result = ((iv + b + 50 + sqrt(e) / 8) * l / 50) + 10; else result = ((iv + b + sqrt(e) / 8) * l / 50) + 5; if (j == 0) cout << "HP: " << result << endl; else if (j == 1) cout << "AT: " << result << endl; else if (j == 2) cout << "DF: " << result << endl; else cout << "SP: " << result << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/pomekon_collection.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2174 #include #include #include using namespace std; int main() { int n; string pokemonName; set pokemons; cin >> n; while (n--) { cin >> pokemonName; pokemons.insert(pokemonName); } cout << "Falta(m) " << 151 - pokemons.size() << " pomekon(s)." << endl; return 0; } ================================================ FILE: competitive-programming/uri/pomekons_battle.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2221 #include using namespace std; int main() { int numberOfInstance, attack, defense, bonus, level; float firstPlayerValue, secondPlayerValue; cin >> numberOfInstance; while (numberOfInstance--) { cin >> bonus; cin >> attack >> defense >> level; firstPlayerValue = (attack + defense) / 2.0; if (level % 2 == 0) firstPlayerValue += bonus; cin >> attack >> defense >> level; secondPlayerValue = (attack + defense) / 2.0; if (level % 2 == 0) secondPlayerValue += bonus; if (firstPlayerValue > secondPlayerValue) cout << "Dabriel" << endl; else if (secondPlayerValue > firstPlayerValue) cout << "Guarte" << endl; else cout << "Empate" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/population_increase.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1160 #include using namespace std; int main() { int n, p1, p2, years=0; double g1, g2; cin >> n; while (n--) { cin >> p1 >> p2; cin >> g1 >> g2; while (true) { p1 += p1 * g1 / 100; p2 += p2 * g2 / 100; years++; if (p1 > p2 || years > 100) break; } if (years > 100) cout << "Mais de 1 seculo." << endl; else cout << years << " anos." << endl; years = 0; } return 0; } ================================================ FILE: competitive-programming/uri/positive_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1060 #include using namespace std; int main() { int total=0; for (int i = 0; i < 6; i++) { double n; cin >> n; if (n > 0) total++; } cout << total << " valores positivos" << endl; return 0; } ================================================ FILE: competitive-programming/uri/positives_and_average.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1064 #include using namespace std; int main() { int total=0; double total1=0; for (int i = 0; i < 6; i++) { double n; cin >> n; if (n > 0) { total++; total1 += n; } } cout << total << " valores positivos" << endl; cout << total1 / total << endl; return 0; } ================================================ FILE: competitive-programming/uri/power_crisis.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1031 #include #include using namespace std; vector buildVector(int n) { vector v; for(int i = 0; i < n; i++) v.push_back(1); return v; } int getLastRegion(vector regions, int m) { int counter = 0, max = regions.size(), ind = 0, c = m; while (counter < max - 1) { while (regions[ind] == 0) { ind++; if (ind >= max) ind -= max; } if (c == m) { regions[ind] = 0; counter++; c = 0; } ind++; c++; if (ind >= max) ind -= max; } for (int i = 0; i < regions.size(); i++) if (regions[i] == 1) return i+1; } int main() { vector v; int n, regionIndex; while (cin >> n && n != 0) { int i = 1; while(true) { if (getLastRegion(buildVector(n), i) == 13) { regionIndex = i; break; } i++; } cout << regionIndex << endl; } return 0; } ================================================ FILE: competitive-programming/uri/preface.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1837 // 9 4 --> 2 1 // 9 -4 --> -2 1 // -9 4 --> -3 3 // -9 -4 --> 3 3 #include using namespace std; int main() { int x, n, q, r; float n1, n2,xf; cin >> n1 >> n2; n = n2; if (n < 0) n *= -1; for (int i = 0; i < n; i++) { x = (n1 - i) / n2; xf = (n1 - i) / n2; if (x == xf) { r = i; q = x; break; } } cout << q << " " << r << endl; return 0; } ================================================ FILE: competitive-programming/uri/presents.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2022 #include #include #include #include #include using namespace std; struct product { string name; int preference; float price; }; bool compareProducts(const product &p1, const product &p2) { if (p1.preference > p2.preference) return true; else if (p1.preference == p2.preference) { if (p1.price < p2.price) return true; else if (p1.price == p2.price) return p1.name < p2.name; } return false; } int main() { string name, productName; int n, preference; float price; while (cin >> name) { cin >> n; vector products; for (int i = 0; i < n; i++) { cin.ignore(); getline(cin, productName); cin >> price >> preference; product p; p.name = productName; p.preference = preference; p.price = price; products.push_back(p); } sort(products.begin(), products.end(), compareProducts); cout << "Lista de " << name << endl; for (int i = 0; i < n; i++) { cout << products[i].name << " - R$"; cout << fixed << setprecision(2) << products[i].price << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/primary_arithmatic.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1212 #include #include using namespace std; int main() { long long int n1, n2; cin >> n1 >> n2; while (n1 + n2 != 0) { vector v1, v2; int counter = 0; while (n1 > 0) { v1.push_back(n1 % 10); n1 /= 10; } while (n2 > 0) { v2.push_back(n2 % 10); n2 /= 10; } if (v1.size() > v2.size()) { for (int i = 0; i < v2.size(); i++) if (v1[i] + v2[i] >= 10) counter++; } else { for (int i = 0; i < v1.size(); i++) if (v1[i] + v2[i] >= 10) counter++; } if (counter == 1) cout << counter << " carry operation." << endl; else if (counter > 1) cout << counter << " carry operations." << endl; else cout << "No carry operation." << endl; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/prime_number.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1165 #include #include using namespace std; int is_prime(int n) { if (n == 2) return 1; if ((n % 2) == 0) return 0; int s = sqrt(n); for (int i = 3; i <= s; i += 2) if (n % i == 0) return 0; return 1; } int main() { int n, x; cin >> n; while (n--) { cin >> x; if (is_prime(x)) cout << x << " eh primo" << endl; else cout << x << " nao eh primo" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/pum.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1142 #include using namespace std; int main() { int n, pum=1; cin >> n; while (n--) { int a = pum + 3; for (int i = pum; i < a; i++) { cout << i << " "; pum++; } cout << "PUM" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/quadrant.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1115 #include using namespace std; int main() { int x, y; cin >> x >> y; while (x != 0 && y != 0) { if (x > 0 && y > 0) cout << "primeiro" << endl; else if (x < 0 && y > 0) cout << "segundo" << endl; else if (x < 0 && y < 0) cout << "terceiro" << endl; else if (x > 0 && y < 0) cout << "quarto" << endl; cin >> x >> y; } return 0; } ================================================ FILE: competitive-programming/uri/queen.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1087 #include using namespace std; int main() { int x1, x2, y1, y2, found=0; cin >> x1 >> y1 >> x2 >> y2; while (x1 + x2 + y1 + y2 != 0) { int x = x1, y = y1; while (x != 0 && y != 0) { if (x == x2 && y == y2) found = 1; x--; y--; } x = x1, y = y1; while (x != 9 && y != 0) { if (x == x2 && y == y2) found = 1; x++; y--; } x = x1, y = y1; while (x != 0 && y != 9) { if (x == x2 && y == y2) found = 1; x--; y++; } x = x1, y = y1; while (x != 9 && y != 9) { if (x == x2 && y == y2) found = 1; x++; y++; } if (x1 == x2 && y1 == y2) cout << 0 << endl; else if (x1 == x2 || y1 == y2 || found) cout << 1 << endl; else cout << 2 << endl; cin >> x1 >> y1 >> x2 >> y2; found = 0; } return 0; } ================================================ FILE: competitive-programming/uri/radares.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2598 #include using namespace std; int main() { int C, N, M, result; cin >> C; while (C--) { cin >> N >> M; result = N / M; if (N % M > 0) result++; cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/rails.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1062 #include #include #include using namespace std; void clear(queue &q) { queue empty; swap(q, empty); } bool canMarshalInTheRequiredOrder(queue &train) { stack order; order.push(1); int max = train.size(), wagonNumber = 2; while (true) { if (!train.empty() && !order.empty() && train.front() == order.top()) { train.pop(); order.pop(); } else if (wagonNumber <= max) { order.push(wagonNumber); wagonNumber++; } else { return false; } if (train.empty()) return true; } } int main() { int n, x; queue train; while (cin >> n && n != 0) { while (cin >> x && x != 0) { train.push(x); for (int i = 1; i < n; i++) { cin >> x; train.push(x); } if (canMarshalInTheRequiredOrder(train)) cout << "Yes" << endl; else cout << "No" << endl; clear(train); } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/rails_again.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1062 #include #include #include #include using namespace std; string requiredOrder(queue &t, queue &order) { stack train; int max = t.size(), wagonNumber = 1; string result = ""; while (true) { if (!train.empty() && !order.empty() && train.top() == order.front()) { train.pop(); order.pop(); result += "R"; } else if (wagonNumber <= max) { wagonNumber++; train.push(t.front()); t.pop(); result += "I"; } else { return result + " Impossible"; } if (order.empty()) return result; } } int main() { int n; char el; while (cin >> n && n != 0) { queue train; queue order; for (int i = 0; i < n; i++) { cin >> el; train.push(el); } for (int i = 0; i < n; i++) { cin >> el; order.push(el); } cout << requiredOrder(train, order) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/reading_books.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1542 #include using namespace std; int main() { int n1, n2, n3, result; while (cin >> n1 && n1 != 0) { cin >> n2 >> n3; result = n1 * (n2 * n3) / (n3 - n1); if (result <= 1) cout << result << " pagina" << endl; else cout << result << " paginas" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/regular_simple_polygon.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1959 #include using namespace std; int main() { long long int n1, n2; cin >> n1 >> n2; cout << n1 * n2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/remaining2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1075 #include using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { if (i % n == 2) { cout << i << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/removing_letter.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1556 #include #include #include using namespace std; int main() { string s; while (cin >> s) { vector v; for (int i = 0; i < s.size(); i++) { string new_s = ""; for (int j = i; j < s.size(); j++) { new_s += s[j]; v.push_back(new_s); cout << new_s << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/rest_of_a_division.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1133 #include using namespace std; int main() { int x, y; cin >> x >> y; if (x < y) { for (int i = x+1; i < y; i++) { if (i % 5 == 2 || i % 5 == 3) { cout << i << endl; } } } else { for (int i = y+1; i < x; i++) { if (i % 5 == 2 || i % 5 == 3) { cout << i << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/right_area.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1190 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter1=11, count = 0; for (int i = 1; i < 11; i++) { for (int j = counter1; j < 12; j++) { total += v1[i][j]; count++; } if (i < 5) counter1--; else if (i > 5) counter1++; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/rlj.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2557 #include #include #include using namespace std; int to_digit(char c) { return c - '0'; } int string_to_int(string num) { int n = 0; for (int i = num.size()-1, j = 0; i >= 0; i--, j++) n += to_digit(num[i]) * pow(10, j); return n; } int parse_eq(string eq, int start, int size) { string j = eq.substr(start, size); return string_to_int(j); } int main() { string eq; while (getline(cin, eq)) { if (eq[0] == 'R') { cout << parse_eq(eq, eq.find("=")+1, eq.size() - eq.find("=") - 1) - parse_eq(eq, eq.find("+")+1, eq.find("=") - eq.find("+") - 1) << endl; } else if (eq[eq.size()-1] == 'J') { cout << parse_eq(eq, 0, eq.find("+")) + parse_eq(eq, eq.find("+")+1, eq.find("=") - eq.find("+") - 1) << endl; } else { cout << parse_eq(eq, eq.find("=")+1, eq.size() - eq.find("=") - 1) - parse_eq(eq, 0, eq.find("+")) << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/robot_instructions.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1574 #include #include #include #include using namespace std; string parse_string(string line) { vector v; string word = ""; for (int i = 0; i < line.size(); i++) { if (line[i] == ' ') { v.push_back(word); word.clear(); } else if (i == line.size() - 1) { word += line[i]; v.push_back(word); word.clear(); } else { word += line[i]; } } return v.back(); } int to_digit(char digit) { return digit - '0'; } int string_to_number(string n) { if (n == "") { return -1; } else { int num = 0; for (int i = 0; i < n.size(); i++) { num = num * 10 + to_digit(n[i]); } return num; } } int main() { int n, tests; cin >> n; string command; while (n--) { cin >> tests; cin.ignore(); map m; getline(cin, command); if (command == "LEFT") m[1] = -1; else m[1] = 1; for (int i = 2; i <= tests; i++) { getline(cin, command); command = parse_string(command); if (command == "LEFT") m[i] = -1; else if (command == "RIGHT") m[i] = 1; else { int key = string_to_number(command); m[i] = m[key]; } } map::iterator it; int position = 0; for (it = m.begin(); it != m.end(); it++) { position += it->second; } cout << position << endl; } return 0; } ================================================ FILE: competitive-programming/uri/rock_paper_airstrike.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2031 #include #include using namespace std; int main() { int n; cin >> n; string player1, player2; while (n--) { cin >> player1 >> player2; if (player1 == player2) { if (player1 == "ataque") cout << "Aniquilacao mutua" << endl; else if (player1 == "pedra") cout << "Sem ganhador" << endl; else cout << "Ambos venceram" << endl; } else { if (player1 == "ataque" && player2 == "pedra") cout << "Jogador 1 venceu" << endl; else if (player2 == "ataque" && player1 == "pedra") cout << "Jogador 2 venceu" << endl; else if (player1 == "pedra" && player2 == "papel") cout << "Jogador 1 venceu" << endl; else if (player2 == "pedra" && player1 == "papel") cout << "Jogador 2 venceu" << endl; else if (player1 == "ataque" && player2 == "papel") cout << "Jogador 1 venceu" << endl; else if (player2 == "ataque" && player1 == "papel") cout << "Jogador 2 venceu" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/rock_paper_scissors_lizard_spock.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1873 #include #include using namespace std; string get_winner(string type1, string type2) { if (type1 == "tesoura" && type2 == "papel") return "rajesh"; else if (type1 == "papel" && type2 == "pedra") return "rajesh"; else if (type1 == "pedra" && type2 == "lagarto") return "rajesh"; else if (type1 == "lagarto" && type2 == "spock") return "rajesh"; else if (type1 == "spock" && type2 == "tesoura") return "rajesh"; else if (type1 == "tesoura" && type2 == "lagarto") return "rajesh"; else if (type1 == "lagarto" && type2 == "papel") return "rajesh"; else if (type1 == "papel" && type2 == "spock") return "rajesh"; else if (type1 == "spock" && type2 == "pedra") return "rajesh"; else if (type1 == "pedra" && type2 == "tesoura") return "rajesh"; else if (type1 == type2) return "empate"; else return "sheldon"; } int main() { int n; string rajesh, sheldon; cin >> n; while (n--) { cin >> rajesh >> sheldon; cout << get_winner(rajesh, sheldon) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/roman_numerals_for_page_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1960 #include #include #include using namespace std; int main() { int n, remainder, integer; string c[] = { "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; string d[] = { "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; string u[] = { "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; cin >> n; integer = n / 100; remainder = n % 100; switch(integer) { case 1: cout << c[0]; break; case 2: cout << c[1]; break; case 3: cout << c[2]; break; case 4: cout << c[3]; break; case 5: cout << c[4]; break; case 6: cout << c[5]; break; case 7: cout << c[6]; break; case 8: cout << c[7]; break; case 9: cout << c[8]; break; } integer = remainder / 10; remainder = remainder % 10; switch(integer) { case 1: cout << d[0]; break; case 2: cout << d[1]; break; case 3: cout << d[2]; break; case 4: cout << d[3]; break; case 5: cout << d[4]; break; case 6: cout << d[5]; break; case 7: cout << d[6]; break; case 8: cout << d[7]; break; case 9: cout << d[8]; break; } integer = remainder / 1; switch(integer) { case 1: cout << u[0]; break; case 2: cout << u[1]; break; case 3: cout << u[2]; break; case 4: cout << u[3]; break; case 5: cout << u[4]; break; case 6: cout << u[5]; break; case 7: cout << u[6]; break; case 8: cout << u[7]; break; case 9: cout << u[8]; break; } return 0; } ================================================ FILE: competitive-programming/uri/rot13.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1249 #include #include using namespace std; int main() { string word; string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; while (getline(cin, word)) { string new_word = ""; for (int i = 0; i < word.size(); i++) { int index = alphabet.find(word[i]); if (index != -1) { index += 13; new_word += alphabet[index]; } else { new_word += word[i]; } } cout << new_word << endl; } return 0; } ================================================ FILE: competitive-programming/uri/s_sequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1155 #include #include using namespace std; int main() { int n = 1; double total = 0; for (int i = 1; i <= 100; i++) { total += (1.0 / i); } cout << fixed << setprecision(2) << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/s_sequence_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1156 #include #include using namespace std; int main() { double n = 1; double total = 0; for (int i = 1; i <= 39; i += 2) { total += (i / n); n *= 2; } cout << fixed << setprecision(2) << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/salary.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1008 #include #include using namespace std; int main() { int n1, n2; float num; cin >> n1 >> n2 >> num; cout << "NUMBER = " << n1 << endl; cout << fixed << setprecision(2) << "SALARY = U$ " << n2 * num << endl; return 0; } ================================================ FILE: competitive-programming/uri/salary_with_bonus.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1009 #include #include using namespace std; int main() { string name; float n1, n2; cin >> name; cin >> n1 >> n2; cout << fixed << setprecision(2) << "TOTAL = R$ " << n1 + n2 * 0.15 << endl; return 0; } ================================================ FILE: competitive-programming/uri/santas_translator.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1763 #include #include #include using namespace std; int main() { map Dictionary; Dictionary["brasil"] = "Feliz Natal!"; Dictionary["alemanha"] = "Frohliche Weihnachten!"; Dictionary["austria"] = "Frohe Weihnacht!"; Dictionary["coreia"] = "Chuk Sung Tan!"; Dictionary["espanha"] = "Feliz Navidad!"; Dictionary["grecia"] = "Kala Christougena!"; Dictionary["estados-unidos"] = "Merry Christmas!"; Dictionary["inglaterra"] = "Merry Christmas!"; Dictionary["australia"] = "Merry Christmas!"; Dictionary["portugal"] = "Feliz Natal!"; Dictionary["suecia"] = "God Jul!"; Dictionary["turquia"] = "Mutlu Noeller"; Dictionary["argentina"] = "Feliz Navidad!"; Dictionary["chile"] = "Feliz Navidad!"; Dictionary["mexico"] = "Feliz Navidad!"; Dictionary["antardida"] = "Merry Christmas!"; Dictionary["canada"] = "Merry Christmas!"; Dictionary["irlanda"] = "Nollaig Shona Dhuit!"; Dictionary["belgica"] = "Zalig Kerstfeest!"; Dictionary["italia"] = "Buon Natale!"; Dictionary["libia"] = "Buon Natale!"; Dictionary["siria"] = "Milad Mubarak!"; Dictionary["marrocos"] = "Milad Mubarak!"; Dictionary["japao"] = "Merii Kurisumasu!"; string country, result; bool found = false; while (cin >> country) { if (Dictionary.find(country) == Dictionary.end()) cout << "--- NOT FOUND ---" << endl; else cout << Dictionary[country] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/scientific_notation.cpp ================================================ #include #include using namespace std; int main() { long double X; cin >> X; cout << showpos << uppercase << scientific << setprecision(4) << X << endl; return 0; } ================================================ FILE: competitive-programming/uri/score_validation.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1117 #include #include using namespace std; int main() { int total=0; double n, media=0; cin >> n; while (total < 2) { if (n >= 0 && n <= 10) { media += n; total++; } else { cout << "nota invalida" << endl; } cin >> n; } cout << fixed << setprecision(2) << "media = " << media / 2.0 << endl; return 0; } ================================================ FILE: competitive-programming/uri/searching_for_nessy.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1428 #include using namespace std; int main() { int n, n1, n2, num, num1, num2; float aux1, aux2; cin >> n; while (n--) { cin >> n1 >> n2; aux1 = (n1 - 2) / 3.0; num1 = aux1; if (aux1 - num1 > 0.0) num1++; aux2 = (n2 - 2) / 3.0; num2 = aux2; if (aux2 - num2 > 0.0) num2++; num = num1 * num2; cout << num << endl; } return 0; } ================================================ FILE: competitive-programming/uri/searching_subsequences.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2126 #include #include using namespace std; int main() { string subs, s; int pos, qtd, casy = 1; while (cin >> subs && cin >> s) { qtd = 0; pos = -1; for (int i = 0; i < s.size() - subs.size() + 1; i++) { if (subs == s.substr(i, subs.size())) { qtd++; pos = i+1; } } cout << "Caso #" << casy << ":" << endl; if (pos == -1) cout << "Nao existe subsequencia" << endl; else cout << "Qtd.Subsequencias: " << qtd << endl << "Pos: " << pos << endl; cout << endl; casy++; } return 0; } ================================================ FILE: competitive-programming/uri/selection_test_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1035 #include using namespace std; int main() { int n1, n2, n3, n4; cin >> n1 >> n2 >> n3 >> n4; // Then if B is greater than C and D is greater than A and // if the sum of C and D is greater than the sum of A and B and // if C and D were positives values and if A is even if (n2 > n3 && n4 > n1 && n3 + n4 > n1 + n2 && n3 > 0 && n4 > 0 && n1 % 2 == 0) cout << "Valores aceitos" << endl; else cout << "Valores nao aceitos" << endl; return 0; } ================================================ FILE: competitive-programming/uri/sequence_ij_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1095 #include using namespace std; int main() { int j = 1; for (int i = 60; i >= 0; i -= 5, j += 3) { cout << "I=" << j << " J=" << i << endl; } return 0; } ================================================ FILE: competitive-programming/uri/sequence_ij_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1096 #include using namespace std; int main() { int i = 1, j = 7, counter=0; while (i != 9 || j != 5) { cout << "I=" << i << " J=" << j << endl; counter++; j--; if (counter == 3) { i += 2; j = 7; counter = 0; } } cout << "I=" << i << " J=" << j << endl; return 0; } ================================================ FILE: competitive-programming/uri/sequence_ij_3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1097 #include using namespace std; int main() { int i = 1, j = 7, counter=0; while (true) { cout << "I=" << i << " J=" << j << endl; counter++; j--; if (counter == 3) { i += 2; j += 5; counter = 0; } if (i == 9 && j == 13) { cout << "I=" << i << " J=" << j << endl; break; } } return 0; } ================================================ FILE: competitive-programming/uri/sequence_ij_4.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1098 #include #include using namespace std; int main() { float i = 0; vector v; v.push_back(1); v.push_back(2); v.push_back(3); while (i < 2.1) { for (int a = 0; a < 3; a++) cout << "I=" << i << " J=" << v[a] << endl; for (int j = 0; j < 3; j++) v[j] += 0.2; i += 0.2; } return 0; } ================================================ FILE: competitive-programming/uri/sequence_of_numbers_and_sum.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1101 #include using namespace std; int main() { int n1, n2, total=0; cin >> n1 >> n2; while (n1 > 0 && n2 > 0) { if (n1 > n2) { for (int i = n2; i <= n1; i++) { cout << i << " "; total += i; } cout << "Sum=" << total << endl; } else if (n2 > n1) { for (int i = n1; i <= n2; i++) { cout << i << " "; total += i; } cout << "Sum=" << total << endl; } else { cout << n1 << " Sum=" << n1 << endl; } total = 0; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/sequence_of_sequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2028 #include #include using namespace std; int main() { int n, counter=1, size, num; while (scanf("%i", &n) != EOF) { if (n == 0) { cout << "Caso " << counter << ": " << 1 << " numero" << endl; cout << 0; } else { size = ((n * (1 + n)) / 2) + 1; cout << "Caso " << counter << ": "; if (size == 1) cout << size << " numero" << endl; else cout << size << " numeros" << endl; for (int i = 0; i <= n; i++) { if (i == 0) num = 1; else num = i; for (int j = 0; j < num; j++) { cout << i; if (i != n || j != num - 1) cout << " "; } } } cout << endl << endl; counter++; } return 0; } ================================================ FILE: competitive-programming/uri/seven.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2590 #include using namespace std; int main() { cin.tie(NULL); cout.sync_with_stdio(false); long long int N, num; cin >> N; while (N--) { cin >> num; switch (num & 3) { case 0: cout << 1 << '\n'; break; case 1: cout << 7 << '\n'; break; case 2: cout << 9 << '\n'; break; case 3: cout << 3 << '\n'; break; } } return 0; } ================================================ FILE: competitive-programming/uri/several_scores_with_validation.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1118 #include #include using namespace std; int main() { int response = 1; float grade1, grade2; while (response != 2) { while (true) { cin >> grade1; if (grade1 >= 0 && grade1 <= 10) break; else cout << "nota invalida" << endl; } while (true) { cin >> grade2; if (grade2 >= 0 && grade2 <= 10) break; else cout << "nota invalida" << endl; } cout << fixed << setprecision(2) << "media = " << (grade1 + grade2) / 2 << endl; cout << "novo calculo (1-sim 2-nao)" << endl; cin >> response; while (response != 1 && response != 2) { cout << "novo calculo (1-sim 2-nao)" << endl; cin >> response; } } return 0; } ================================================ FILE: competitive-programming/uri/short_attendance.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1277 #include #include #include using namespace std; bool need_attendance(string attendance) { double total = attendance.size(), present = 0.0, medical = 0.0; for (double i = 0; i < attendance.size(); i++) { if (attendance[i] == 'P') present++; else if (attendance[i] == 'M') medical++; } total -= medical; if (present / total >= 0.75) return false; else return true; } int main() { int n, num; cin >> n; while (n--) { cin >> num; if (num) { string name, attendance; bool first_name = true; vector students, stud; vector attendances; for (int i = 0; i < num; i++) { cin >> name; students.push_back(name); } for (int i = 0; i < num; i++) { cin >> attendance; if (need_attendance(attendance)) stud.push_back(students[i]); } for (int i = 0; i < stud.size(); i++) { if (first_name) { cout << stud[i]; first_name = false; } else { cout << " " << stud[i]; } } cout << endl; } else { cout << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/short_story.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1222 #include #include #include using namespace std; int main() { int num_words, max_char_per_line, max_line_per_page, counter_char = 0, counter_lines = 0, counter_pages = 0; string word; vector words; while (cin >> num_words >> max_line_per_page >> max_char_per_line) { for (int i = 0; i < num_words; i++) { cin >> word; words.push_back(word); } for (int i = 0; i < num_words; i++) { counter_char += words[i].size(); if (i+1 < num_words && counter_char < max_char_per_line) counter_char++; if (counter_char > max_char_per_line) { counter_lines++; counter_char = 0; i--; } else if (counter_char == max_char_per_line) { counter_lines++; counter_char = 0; } if (counter_lines >= max_line_per_page) { counter_pages++; counter_lines = 0; } } counter_pages++; cout << counter_pages << endl; counter_char = 0; counter_lines = 0; counter_pages = 0; words.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/simple_calculate.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1010 #include #include using namespace std; int main() { int code1, code2, unit1, unit2; float price_per_unit1, price_per_unit2; cin >> code1 >> unit1 >> price_per_unit1; cin >> code2 >> unit2 >> price_per_unit2; cout << fixed << setprecision(2) << "VALOR A PAGAR: R$ " << unit1 * price_per_unit1 + unit2 * price_per_unit2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/simple_factorial.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1153 #include using namespace std; int fatorial(int n) { if (n == 1) return 1; return n * fatorial(n - 1); } int main() { int n; cin >> n; cout << fatorial(n) << endl; return 0; } ================================================ FILE: competitive-programming/uri/simple_prod.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1004 #include using namespace std; int main() { int a, b; cin >> a >> b; cout << "PROD = " << a * b << endl; return 0; } ================================================ FILE: competitive-programming/uri/simple_sort.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1042 #include using namespace std; int main() { int n1, n2, n3; cin >> n1 >> n2 >> n3; if (n1 < n2 && n1 < n3) { cout << n1 << endl; if (n2 < n3) { cout << n2 << endl; cout << n3 << endl; } else { cout << n3 << endl; cout << n2 << endl; } } else if (n2 < n3) { cout << n2 << endl; if (n1 < n3) { cout << n1 << endl; cout << n3 << endl; } else { cout << n3 << endl; cout << n1 << endl; } } else { cout << n3 << endl; if (n1 < n2) { cout << n1 << endl; cout << n2 << endl; } else { cout << n2 << endl; cout << n1 << endl; } } cout << endl << n1 << endl << n2 << endl << n3 << endl; return 0; } ================================================ FILE: competitive-programming/uri/simple_sum.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1003 #include using namespace std; int main() { int a, b; cin >> a >> b; cout << "SOMA = " << a + b << endl; return 0; } ================================================ FILE: competitive-programming/uri/simulator.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2368 #include #include #include using namespace std; int main() { int n1, n2, x, y; string v; vector nums; cin >> n1 >> n2; for (int i = 1; i <= n1; i++) nums.push_back(i); while (n2--) { cin >> v >> x >> y; if (v == "I") { while (x < y) { iter_swap(nums.begin() + x-1, nums.begin() + y-1); x++; y--; } } else { int sum = 0; for (int i = x-1; i < y; i++) sum += nums[i]; cout << sum << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/six_odd_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1070 #include using namespace std; int main() { int n, times=0; cin >> n; while (times < 6) { if (n % 2 != 0) { cout << n << endl; times++; } n++; } return 0; } ================================================ FILE: competitive-programming/uri/snack.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1038 #include #include #include using namespace std; int main() { vector ar; ar.push_back(4.0); ar.push_back(4.5); ar.push_back(5.0); ar.push_back(2.0); ar.push_back(1.5); int n1, n2; cin >> n1 >> n2; cout << fixed << setprecision(2) << "Total: R$ " << ar[n1-1] * n2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/sort_by_length.cpp ================================================ #include #include #include using namespace std; vector parse_string(string line) { vector v; string word = ""; for (int i = 0; i < line.size(); i++) { if (line[i] == ' ') { v.push_back(word); word.clear(); } else if (i == line.size() - 1) { word += line[i]; v.push_back(word); word.clear(); } else { word += line[i]; } } return v; } vector sort_by_size(vector &v) { vector new_v; int size = v.size(); while (size--) { int max_size = v[0].size(), index = 0; for (int i = 1; i < v.size(); i++) { if (v[i].size() > max_size) { index = i; max_size = v[i].size(); } } new_v.push_back(v[index]); v.erase(v.begin() + index); } return new_v; } int main() { string s; int n; cin >> n; cin.ignore(); while (n--) { getline(cin, s); vector strings = parse_string(s); vector sorted_strings = sort_by_size(strings); for (int i = 0; i < sorted_strings.size()-1; i++) cout << sorted_strings[i] << " "; cout << sorted_strings[sorted_strings.size()-1] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/sort_sort_and_sort.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1252 #include #include #include using namespace std; bool sortBy(const pair &pair1, const pair &pair2) { if (pair1.first > pair2.first) { return false; } else if (pair1.first < pair2.first) { return true; } else { if (pair1.second % 2 == 0 && pair2.second % 2 == 0) { return pair1.second < pair2.second; } else if (pair1.second % 2 != 0 && pair2.second % 2 != 0) { return pair1.second > pair2.second; } else if (pair1.second % 2 != 0 && pair2.second % 2 == 0) { return true; } else { return false; } } } int main() { int n, m, x; while (cin >> n >> m && n + m != 0) { vector< pair > v; for (int i = 0; i < n; i++) { cin >> x; v.push_back(make_pair(x % m, x)); } sort(v.begin(), v.end(), sortBy); cout << n << " " << m << endl; for (int i = 0; i < v.size(); i++) cout << v[i].second << endl; } cout << 0 << " " << 0 << endl; return 0; } ================================================ FILE: competitive-programming/uri/sphere.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1011 #include #include #include using namespace std; int main() { const double PI = 3.14159; int n; cin >> n; cout << fixed << setprecision(3) << "VOLUME = " << (4.0 / 3) * PI * pow(n, 3) << endl; return 0; } ================================================ FILE: competitive-programming/uri/spurs_rock.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1303 #include #include #include #include using namespace std; struct team { int id; int points; float scores; float scoresConceded; int games; }; bool untie(const team &t1, const team &t2) { if (t1.points > t2.points) return true; else if (t1.points < t2.points) return false; else { float team1AverageBasket, team2AverageBasket; if (t1.scoresConceded) team1AverageBasket = t1.scores / t1.scoresConceded; else team1AverageBasket = t1.scores; if (t2.scoresConceded) team2AverageBasket = t2.scores / t2.scoresConceded; else team2AverageBasket = t2.scores; if (team1AverageBasket > team2AverageBasket) return true; else if (team1AverageBasket < team2AverageBasket) return false; else { if (t1.points > t2.points) return true; else if (t1.points < t2.points) return false; else { if (t1.games < t2.games) return true; else if (t1.games > t2.games) return false; } } } } int main() { int n, p1, p2, instance=1; float score1, score2; cin >> n; while (n) { vector teams; map t; for (int i = 0; i < n * (n-1) / 2; i++) { cin >> p1 >> score1 >> p2 >> score2; if (score1 > score2) { if (t.find(p1) != t.end()) { t[p1].points += 2; t[p1].scores += score1; t[p1].scoresConceded += score2; t[p1].games++; if (t.find(p2) != t.end()) { t[p2].points++; t[p2].scores += score2; t[p2].scoresConceded += score1; t[p2].games++; } else { team te; te.id = p2; te.points = 1; te.scores = score2; te.scoresConceded = score1; te.games = 1; t[p2] = te; } } else { team te; te.id = p1; te.points = 2; te.scores = score1; te.scoresConceded = score2; te.games = 1; t[p1] = te; if (t.find(p2) != t.end()) { t[p2].points++; t[p2].scores += score2; t[p2].scoresConceded += score1; t[p2].games++; } else { team te; te.id = p2; te.points = 1; te.scores = score2; te.scoresConceded = score1; te.games = 1; t[p2] = te; } } } else if (score1 < score2) { if (t.find(p1) != t.end()) { t[p1].points++; t[p1].scores += score1; t[p1].scoresConceded += score2; t[p1].games++; if (t.find(p2) != t.end()) { t[p2].points += 2; t[p2].scores += score2; t[p2].scoresConceded += score1; t[p2].games++; } else { team te; te.id = p2; te.points = 2; te.scores = score2; te.scoresConceded = score1; te.games = 1; t[p2] = te; } } else { team te; te.id = p1; te.points = 1; te.scores = score1; te.scoresConceded = score2; te.games = 1; t[p1] = te; if (t.find(p2) != t.end()) { t[p2].points += 2; t[p2].scores += score2; t[p2].scoresConceded += score1; t[p2].games++; } else { team te; te.id = p2; te.points = 2; te.scores = score2; te.scoresConceded += score1; te.games = 1; t[p2] = te; } } } } for (map::iterator it = t.begin(); it != t.end(); ++it) { teams.push_back(it->second); } sort(teams.begin(), teams.end(), untie); cout << "Instancia " << instance << endl; cout << teams[0].id; for (int i = 1; i < teams.size(); i++) { cout << " " << teams[i].id; } cout << endl; instance++; cin >> n; if (n) cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/square_array_4.cpp ================================================ #include #include using namespace std; void generateFirstStep(int n, int x) { for (int i = 0; i < x; i++) { for (int j = 0; j < n; j++) { if (i == j) cout << "2"; else if (n-i-1 == j) cout << "3"; else cout << "0"; } cout << endl; } } void generateSecondStep(int n, int x) { int medi = (n-x-x) / 2; int medj = n / 2; for (int i = 0; i < n-x-x; i++) { for (int j = 0; j < n; j++) { if (medi == i && medj == j) cout << "4"; else if (j >= x && j < n-x) cout << "1"; else cout << "0"; } cout << endl; } } void generateThirdStep(int n, int x) { for (int i = n-x; i < n; i++) { for (int j = 0; j < n; j++) { if (i == j) cout << "2"; else if (n-i-1 == j) cout << "3"; else cout << "0"; } cout << endl; } } int main() { int n, x; while (cin >> n) { x = n / 3; generateFirstStep(n, x); generateSecondStep(n, x); generateThirdStep(n, x); cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/square_game.cpp ================================================ #include using namespace std; int main() { int n, m, q, t, greatest = 0; int grid[205][205]; int dp[205][205]; memset(dp, 0, sizeof dp); cin >> n >> m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { cin >> grid[i][j]; if (grid[i][j] == 0) dp[i][j] = 0; else { dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j], dp[i][j-1])) + 1; greatest = max(greatest, dp[i][j]); } } } cin >> q; while (q--) { cin >> t; if (t <= greatest) cout << "yes" << endl; else cout << "no" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/square_matrix_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1435 #include #include using namespace std; int get_limit(int n) { int limit = 0; for (int i = 0; i < n; i += 2) limit++; return limit; } int main() { int n; cin >> n; while (n != 0) { vector v; vector< vector > table; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) v.push_back(0); table.push_back(v); } int start = 0; int limit = get_limit(n); while (start < limit) { for (int i = start; i < n-start; i++) { for (int j = start; j < n-start; j++) table[i][j]++; } start++; } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (table[i][j] <= 9) cout << " "; else if (table[i][j] <= 99) cout << " "; cout << table[i][j]; if (j < n-1) cout << " "; } cout << endl; } cout << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/square_matrix_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1478 #include using namespace std; string generateSpaces(int n) { if (n >= 1 && n <= 9) return " "; else if (n >= 10 && n <= 99) return " "; else return ""; } int main() { int n, startIndex, des; while (cin >> n && n) { for (int i = 1; i <= n; i++) { des = i; startIndex = 1; for (int j = 1; j <= n; j++) { if (des >= 2) { if (j != 1) cout << " "; cout << generateSpaces(des) << des; des--; } else { if (j != 1) cout << " "; cout << generateSpaces(startIndex) << startIndex; startIndex++; } } cout << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/square_matrix_3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1557 #include #include #include using namespace std; int getNumberOfDigits(int n) { int counter = 0; while (n) { counter++; n /= 10; } return counter; } string generateSpaces(int n, int t) { int diff = t - getNumberOfDigits(n); string s = ""; for (int i = 0; i < diff; i++) s += " "; return s; } int main() { int n, num, t; while (cin >> n && n) { vector v; vector< vector > matrix; for (int i = 0; i < n; i++) { num = pow(2, i); v.push_back(num); for (int j = 1; j < n; j++) { num *= 2; v.push_back(num); } matrix.push_back(v); v.clear(); } t = getNumberOfDigits(matrix[n-1][n-1]); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j == n-1) cout << generateSpaces(matrix[i][j], t) << matrix[i][j]; else cout << generateSpaces(matrix[i][j], t) << matrix[i][j] << " "; } cout << endl; } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/square_root_of_10.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2161 #include #include using namespace std; double rootNumber(int n1, int n2) { if (n1 == n2) return 6.0; return 6 + 1.0 / rootNumber(n1+1, n2); } int main() { int n; cin >> n; if (n) cout << fixed << setprecision(10) << 3.0 + 1.0 / rootNumber(1, n) << endl; else cout << fixed << setprecision(10) << 3.0 << endl; return 0; } ================================================ FILE: competitive-programming/uri/square_root_of_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2166 #include #include using namespace std; double rootNumber(int n1, int n2) { if (n1 == n2) return 2.0; return 2 + 1.0 / rootNumber(n1+1, n2); } int main() { int n; cin >> n; if (n) cout << fixed << setprecision(10) << 1.0 + 1.0 / rootNumber(1, n) << endl; else cout << fixed << setprecision(10) << 1.0 << endl; return 0; } ================================================ FILE: competitive-programming/uri/square_spiral.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1868 #include #include #include using namespace std; int main() { int n, x, y, num; cin >> n; while (n != 0) { string s; vector v; for (int i = 0; i < n; i++) s += "O"; for (int j = 0; j < n; j++) v.push_back(s); x = (n / 2); y = x; num = (n * n) - 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == x && j == y) cout << "X"; else cout << "O"; } cout << endl; } cout << "@" << endl; y++; int direction = 2; // up int counter = 0, dist = 1, count = 0; while (num--) { counter++; count++; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == x && j == y) cout << "X"; else cout << "O"; } cout << endl; } cout << "@" << endl; if (counter == dist * 2) { counter = 0; dist++; } if (direction == 1) y++; else if (direction == 2) x--; else if (direction == 3) y--; else x++; if (count == dist) { count = 0; if (direction == 1) direction = 2; // up else if (direction == 2) direction = 3; // left else if (direction == 3) direction = 4; // down else direction = 1; // right } } cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/squared_and_cubic.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1143 #include using namespace std; int main() { int n; cin >> n; for (int i = 1; i <= n; i++) { cout << i << " " << i * i << " " << i * i * i << endl; } return 0; } ================================================ FILE: competitive-programming/uri/ssn_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1769 #include #include using namespace std; int to_digit(char num) { return num - '0'; } int main() { string cpf; while (cin >> cpf) { int total1 = 0, num, total2 = 0, c1 = 1, c2 = 9; for (int i = 0; i < 11; i++) { if (cpf[i] != '.') { num = to_digit(cpf[i]); total1 += num * c1; total2 += num * c2; c1++; c2--; } } int rem1 = total1 % 11; int rem2 = total2 % 11; if (rem1 == 10 && rem2 == 10) { if (cpf[12] == '0' && cpf[13] == '0') cout << "CPF valido" << endl; else cout << "CPF invalido" << endl; } else if (rem1 == 10) { if (cpf[12] == '0' && rem2 == to_digit(cpf[13])) cout << "CPF valido" << endl; else cout << "CPF invalido" << endl; } else if (rem2 == 10) { if (rem1 == to_digit(cpf[12]) && cpf[13] == '0') cout << "CPF valido" << endl; else cout << "CPF invalido" << endl; } else if (rem1 == to_digit(cpf[12]) && rem2 == to_digit(cpf[13])) { cout << "CPF valido" << endl; } else { cout << "CPF invalido" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/star_trek.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1973 #include #include using namespace std; int main() { long long int n, x, total=0, total_capture=0, start_counter=0; cin >> n; vector v; vector v1; for (int i = 1; i <= n; i++) { cin >> x; total += x; v.push_back(x); v1.push_back(1); } int i = 0; while (true) { cout << v[i] << endl; if (v[i] == 0 || i < 0 || i >= n) break; v1.at(i) = 0; int j = i; if (v[i] % 2 == 0) i--; else i++; v[j]--; total_capture++; j = i; } for (int i = 0; i < n; i++) if (v1[i] == 0) start_counter++; cout << start_counter << " " << total - total_capture << endl; return 0; } ================================================ FILE: competitive-programming/uri/start_grid.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1228 #include #define swap(a, b) { int x=a; a=b; b=x; } using namespace std; int main() { int n, num, passing; int start[25], finish[25], mapper[25]; while (cin >> n) { passing = 0; for (int i = 1; i <= n; i++) { cin >> num; start[i] = num; } for (int i = 1; i <= n; i++) { cin >> num; finish[i] = num; } for (int i = 1; i <= n; i++) mapper[finish[i]] = i; for (int i = 1; i <= n; i++) { for (int j = i+1; j <= n; j++) { if (mapper[start[i]] > mapper[start[j]]) { swap(mapper[start[i]], mapper[start[j]]); passing++; } } } cout << passing << endl; } return 0; } ================================================ FILE: competitive-programming/uri/stick_collector_robot.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1121 #include #include #include using namespace std; bool isInsideGrid(int x, int y, int lines, int columns) { if (x < 0 || y < 0 || x >= columns || y >= lines) return false; return true; } int main() { int lines, columns, instructionsNumber, x, y; string instructions; char orientation; while (cin >> lines >> columns >> instructionsNumber && lines + columns + instructionsNumber != 0) { vector grid; string line; cin.ignore(); for (int i = 0; i < lines; i++) { getline(cin, line); grid.push_back(line); } getline(cin, instructions); for (int i = 0; i < lines; i++) { for (int j = 0; j < columns; j++) { if (grid[i][j] == 'N') { orientation = 'N'; x = j; y = i; } else if (grid[i][j] == 'S') { orientation = 'S'; x = j; y = i; } else if (grid[i][j] == 'L') { orientation = 'L'; x = j; y = i; } else if (grid[i][j] == 'O') { orientation = 'O'; x = j; y = i; } } } int figuresNumber = 0; grid[y][x] = '.'; for (int i = 0; i < instructions.size(); i++) { if (orientation == 'N') { if (instructions[i] == 'D') orientation = 'L'; else if (instructions[i] == 'E') orientation = 'O'; else { if (isInsideGrid(x, y-1, lines, columns)) { if (grid[y-1][x] == '.') y--; else if (grid[y-1][x] == '*') { grid[y-1][x] = '.'; y--; figuresNumber++; } } } } else if (orientation == 'S') { if (instructions[i] == 'D') orientation = 'O'; else if (instructions[i] == 'E') orientation = 'L'; else { if (isInsideGrid(x, y+1, lines, columns)) { if (grid[y+1][x] == '.') y++; else if (grid[y+1][x] == '*') { grid[y+1][x] = '.'; y++; figuresNumber++; } } } } else if (orientation == 'L') { if (instructions[i] == 'D') orientation = 'S'; else if (instructions[i] == 'E') orientation = 'N'; else { if (isInsideGrid(x+1, y, lines, columns)) { if (grid[y][x+1] == '.') x++; else if (grid[y][x+1] == '*') { grid[y][x+1] = '.'; x++; figuresNumber++; } } } } else { if (instructions[i] == 'D') orientation = 'N'; else if (instructions[i] == 'E') orientation = 'S'; else { if (isInsideGrid(x-1, y, lines, columns)) { if (grid[y][x-1] == '.') x--; else if (grid[y][x-1] == '*') { grid[y][x-1] = '.'; x--; figuresNumber++; } } } } } cout << figuresNumber << endl; } return 0; } ================================================ FILE: competitive-programming/uri/sticks_game.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1366 #include #include using namespace std; int main() { int n, size, quant, total, result; while (cin >> n && n != 0) { total = 0; for (int i = 0; i < n; i++) { cin >> size >> quant; if (quant % 2 != 0) quant--; total += quant; } result = total / 4; cout << result << endl; } return 0; } ================================================ FILE: competitive-programming/uri/strategy_game.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1940 #include #include using namespace std; int main() { vector v; int players, rounds, temp; cin >> players >> rounds; for (int i = 0; i < players; i++) v.push_back(0); for (int i = 0; i < rounds; i++) { for (int j = 0; j < players; j++) { cin >> temp; v[j] += temp; } } int winner = 1, greater = v[0]; for (int i = 1; i < players; i++) { if (v[i] >= greater) { greater = v[i]; winner = i+1; } } cout << winner << endl; return 0; } ================================================ FILE: competitive-programming/uri/subprime.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1105 #include #include using namespace std; struct bank { int code; int money; int owing; }; int main() { int n1, n2, m, debtor, creditor, value; cin >> n1 >> n2; while (n1 + n2 != 0) { vector banks; bool pos_liqui = true; for (int i = 0; i < n1; i++) { cin >> m; bank b; b.code = i; b.money = m; banks.push_back(b); } for (int j = 0; j < n2; j++) { cin >> debtor >> creditor >> value; banks[debtor-1].owing += value; banks[creditor-1].money += value; } for (int k = 0; k < n1; k++) { cout << "Money: " << banks[k].money << " | Owing: " << banks[k].owing << endl; if (banks[k].owing > banks[k].money) { pos_liqui = true; break; } } if (pos_liqui) cout << "S" << endl; else cout << "N" << endl; cin >> n1 >> n2; } return 0; } ================================================ FILE: competitive-programming/uri/sucessor_par.cpp ================================================ #include using namespace std; int main() { long long int X; cin >> X; if (X % 2 == 0) cout << X + 2 << endl; else cout << X + 1 << endl; return 0; } ================================================ FILE: competitive-programming/uri/sudoku.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1383 #include #include #include #include using namespace std; bool correct_mini_matrix(vector< vector > &sudoku, int x, int y) { int limit_x = x + 3, limit_y = y + 3; set s; for (int i = x; i < limit_x; i++) { for (int j = y; j < limit_y; j++) { s.insert(sudoku[i][j]); } } int size = s.size(); if (size == 9) return true; return false; } bool correct_horizontal_line(vector< vector > &sudoku) { set s; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { s.insert(sudoku[i][j]); } if (s.size() != 9) return false; s.clear(); } return true; } bool correct_vertical_line(vector< vector > &sudoku) { set s; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { s.insert(sudoku[j][i]); } if (s.size() != 9) return false; s.clear(); } return true; } int main() { int instance = 1; vector v; vector< vector > sudoku; int n, temp; cin >> n; while (n--) { bool correct_sudoku = true; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { cin >> temp; v.push_back(temp); } sudoku.push_back(v); v.clear(); } for (int i = 0; i < 9; i += 3) { for (int j = 0; j < 9; j += 3) { if (!correct_mini_matrix(sudoku, i, j)) { correct_sudoku = false; break; } } } cout << "Instancia " << instance << endl; if (correct_sudoku && correct_horizontal_line(sudoku) && correct_vertical_line(sudoku)) { cout << "SIM" << endl << endl; } else { cout << "NAO" << endl << endl; } sudoku.clear(); instance++; } return 0; } ================================================ FILE: competitive-programming/uri/sum_of_consecutive_even_numbers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1159 #include using namespace std; int main() { int n, total=0, counter=0; cin >> n; while (n != 0) { while (counter < 5) { if (n % 2 == 0) { total += n; counter++; } n++; } cout << total << endl; counter = 0; total=0; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/sum_of_consecutive_odd_numbers_3.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1158 #include using namespace std; int main() { int n, n1, n2, counter=0, total=0; cin >> n; while (n--) { cin >> n1 >> n2; while (true) { if (n1 % 2 != 0) { total += n1; counter++; } if (counter == n2) { break; } n1++; } cout << total << endl; counter = 0; total = 0; } return 0; } ================================================ FILE: competitive-programming/uri/sum_of_consecutive_odd_numbers_I.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1071 #include using namespace std; int main() { int n1, n2, total=0; cin >> n1 >> n2; if (n1 == n2) { cout << 0 << endl; } else if (n1 > n2) { for (int i = n2; i < n1; i++) { if (i < 0) i = i * (-1); if (i % 2 != 0) total++; } cout << total << endl; } else { for (int i = n1; i < n2; i++) { if (i < 0) i = i * (-1); if (i % 2 != 0) total++; } cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/sum_of_consecutive_odd_numbers_II.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1099 #include using namespace std; int main() { int n, x, y, total=0; cin >> n; while(n--) { cin >> x >> y; if (x > y) { for (int i = y+1; i < x; i++) { if (i % 2 != 0) { total += i; } } } else if (y > x) { for (int i = x+1; i < y; i++) { if (i % 2 != 0) { total += i; } } } if (total > 0) { cout << total << endl; } else { cout << 0 << endl; } total = 0; } return 0; } ================================================ FILE: competitive-programming/uri/sum_of_two_squares.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1558 #include #include #include #include using namespace std; bool is_int(float n) { int num = n; if (num == n) return true; return false; } int main() { int n; while (cin >> n) { unsigned int n1, n2; float res; string response = "NO"; for (int i = 1; pow(i, 2) < n; i++) { n1 = pow(i, 2); n2 = n - n1; res = sqrt(n2); if (is_int(res)) { response = "YES"; break; } } cout << response << endl; } return 0; } ================================================ FILE: competitive-programming/uri/summer_camp.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1167 #include #include #include #include using namespace std; struct student { string studentName; int tokenNumber; bool eliminated; }; int updateStartIndexOnClockWise(vector &students, int startIndex) { int maximumStudentsEliminated = students.size() - 1; if (students[startIndex].tokenNumber % 2 == 0) { while (students[startIndex].eliminated) { startIndex--; if (startIndex > maximumStudentsEliminated) startIndex = 0; } } else { while (students[startIndex].eliminated) { startIndex++; if (startIndex > maximumStudentsEliminated) startIndex = 0; } } return startIndex; } int updateStartIndexOnCounterClockWise(vector &students, int startIndex) { int maximumStudentsEliminated = students.size() - 1; if (students[startIndex].tokenNumber % 2 == 0) { while (students[startIndex].eliminated) { startIndex++; if (startIndex > maximumStudentsEliminated) startIndex = 0; } } else { while (students[startIndex].eliminated) { startIndex--; if (startIndex > maximumStudentsEliminated) startIndex = 0; } } return startIndex; } int main() { int n, tokenNumber; string studentName; while (cin >> n && n != 0) { vector students; while (n--) { cin >> studentName >> tokenNumber; student s; s.studentName = studentName; s.tokenNumber = tokenNumber; s.eliminated = false; students.push_back(s); } int counter = students[0].tokenNumber; int maximumStudentsEliminated = students.size() - 1; int studentsEliminated = 0; int startIndex = 0; bool onClockWise; if (counter % 2 != 0) onClockWise = true; else onClockWise = false; while (studentsEliminated < maximumStudentsEliminated) { while (counter--) { if (onClockWise) startIndex++; else startIndex--; if (startIndex > maximumStudentsEliminated) startIndex = 0; else if (startIndex < 0) startIndex = students.size() - 1; while (students[startIndex].eliminated) { if (onClockWise) startIndex++; else startIndex--; if (startIndex > maximumStudentsEliminated) startIndex = 0; else if (startIndex < 0) startIndex = students.size() - 1; } } students[startIndex].eliminated = true; counter = students[startIndex].tokenNumber; studentsEliminated++; if (counter % 2 != 0) onClockWise = true; else onClockWise = false; } for (int i = 0; i < students.size(); i++) { if (!students[i].eliminated) cout << "Vencedor(a): " << students[i].studentName << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/summing_consecutive_integers.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1149 #include using namespace std; int main() { int n1, n2, total=0; cin >> n1 >> n2; while (n2 <= 0) { cin >> n2; } while (n2--) { total += n1; n1++; } cout << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/sunday_morning.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2003 #include #include using namespace std; int get_minutes(string minutes) { string numbers = "0123456789"; int min = 0; min += 10 * numbers.find(minutes[0]); min += numbers.find(minutes[1]); return min; } int main() { string hour, minutes, s; while (cin >> s) { hour = s.substr(0, 1); minutes = s.substr(2, 2); if (hour == "5" || hour == "6" || (hour == "7" && minutes == "00")) { cout << "Atraso maximo: 0" << endl; } else { if (hour == "7") { cout << "Atraso maximo: " << get_minutes(minutes) << endl; } else if (hour == "8") { cout << "Atraso maximo: " << 60 + get_minutes(minutes) << endl; } else if (hour == "9") { cout << "Atraso maximo: 120" << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/superior_area.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1187 #include #include #include #include using namespace std; int main() { vector< vector > v1; double n, total=0; string operation; cin >> operation; for (int i = 0; i < 12; i++) { vector v; for (int j = 0; j < 12; j++) { cin >> n; v.push_back(n); } v1.push_back(v); } int counter1=1, counter2=11, count = 0; for (int i = 0; i < 5; i++) { for (int j = counter1; j < counter2; j++) { total += v1[i][j]; count++; } counter1++; counter2--; } if (operation == "S") cout << fixed << setprecision(1) << total << endl; else cout << fixed << setprecision(1) << total / count << endl; return 0; } ================================================ FILE: competitive-programming/uri/system_of_download.cpp ================================================ #include #include #include using namespace std; int main() { int N, X, Y; vector V; cin >> N; V.push_back("PROXYCITY"); V.push_back("P.Y.N.G."); V.push_back("DNSUEY!"); V.push_back("SERVERS"); V.push_back("HOST!"); V.push_back("CRIPTONIZE"); V.push_back("OFFLINE DAY"); V.push_back("SALT"); V.push_back("ANSWER!"); V.push_back("RAR?"); V.push_back("WIFI ANTENNAS"); while (N--) { cin >> X >> Y; cout << V[X+Y] << endl; } return 0; } ================================================ FILE: competitive-programming/uri/taxes_of_project.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2170 #include #include using namespace std; int main() { int project = 1; double n1, n2, result; while (cin >> n1 >> n2) { result = ((n2 - n1) / n1) * 100.00; cout << fixed << setprecision(2) << "Projeto " << project << ":" << endl << "Percentual dos juros da aplicacao: " << result << " %" << endl << endl; project++; } return 0; } ================================================ FILE: competitive-programming/uri/tda_rational_1.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1022 #include using namespace std; int lcm(int num1, int num2) { int n1 = num1, n2 = num2, remainder; do { remainder = n1 % n2; n1 = n2; n2 = remainder; } while (remainder != 0) return (num1 * num2) / n1; } int new_num(int num1, int num2, char op) { if (op == '+') return num1 + num2; else if (op == '-') return num1 - num2; else if (op == '*') return num1 * num2; else return num1 / num2; } int main() { char operator, op; int n, num, num1, num2, den1, den2, nden1, nden2; cin >> n; while (n--) { cin >> num1 >> op >> den1 >> operator >> num2 >> op >> den2; nden1 = lcm(den1, den2); nden2 = lcm(den1, den2); num1 *= nden1 / den1; num2 *= nden2 / den2; num = new_num(num1, num2, operator); // continue } return 0; } ================================================ FILE: competitive-programming/uri/tda_rational_2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1022 #include #include using namespace std; int mdc(int num1, int num2) { int remainder; do { remainder = num1 % num2; num1 = num2; num2 = remainder; } while (remainder != 0); return num1; } int main() { string ope, op; int n, num, num1, num2, den, den1, den2, div; cin >> n; while (n--) { cin >> num1 >> op >> den1 >> ope >> num2 >> op >> den2; den = den1 * den2; if (ope == "+") num = num1 * den2 + num2 * den1; else if (ope == "-") num = num1 * den2 - num2 * den1; else if (ope == "*") num = num1 * num2; else { num = num1 * den2; den = num2 * den1; } div = mdc(num, den); if (div < 0) div *= -1; cout << num << "/" << den << " = " << num/div << "/" << den/div << endl; } return 0; } ================================================ FILE: competitive-programming/uri/tell_me_the_frequencies.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1251 #include #include #include #include #include using namespace std; int toASCII(char charac) { int newCharac = int(charac); return newCharac; } bool compareByFrequency(const pair &item1, const pair &item2) { if (item1.second < item2.second) return true; else if (item1.second == item2.second) return item1.first > item2.first; else return false; } int main() { char charac; string text; bool first = true; while (getline(cin, text)) { map m; if (first) first = false; else cout << endl; for (int i = 0; i < text.size(); i++) { charac = toASCII(text[i]); if (m.find(charac) != m.end()) m[charac]++; else m[charac] = 1; } vector< pair > vec(m.begin(), m.end()); sort(vec.begin(), vec.end(), compareByFrequency); for (int i = 0; i < vec.size(); ++i) { cout << vec[i].first << " " << vec[i].second << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/the_chosen.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1983 #include using namespace std; int main() { int n, final, code; double greater = 7.9, note; cin >> n; while (n--) { cin >> code >> note; if (note > greater) { greater = note; final = code; } } if (greater == 7.9) cout << "Minimum note not reached" << endl; else cout << final << endl; return 0; } ================================================ FILE: competitive-programming/uri/the_force_awakens.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2163 #include using namespace std; bool surroundedBySevens(int matrix[1001][1001], int y, int x) { int sum = 0; for (int i = y-1; i <= y+1; i++) { for (int j = x-1; j <= x+1; j++) { if (y != i || x != j) sum += matrix[i][j]; } } return sum == 56; } int main() { int n1, n2, y = 0, x = 0; cin >> n1 >> n2; int matrix[1001][1001]; for (int i = 0; i < n1; i++) { for (int j = 0; j < n2; j++) { cin >> matrix[i][j]; } } for (int i = 1; i < n1-1; i++) { for (int j = 1; j < n2-1; j++) { if (matrix[i][j] == 42 && surroundedBySevens(matrix, i, j)) { y = i+1; x = j+1; } } } cout << y << " " << x << endl; return 0; } ================================================ FILE: competitive-programming/uri/the_greater_one_digit_number.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1867 #include #include #include #include using namespace std; bool is_one_digit(int n) { if (n >= 0 && n <= 9) return true; return false; } int sum_digits_1(string n) { int sum = 0, digit; for (int i = 0; i < n.size(); i++) { digit = n[i] - 48; sum += digit; } return sum; } int sum_digits_2(int n) { int sum = 0, digit; while (n) { digit = n % 10; sum += digit; n /= 10; } return sum; } int main() { string n, m; cin >> n >> m; while (n != "0" || m != "0") { int n1 = sum_digits_1(n); int n2 = sum_digits_1(m); while (!is_one_digit(n1)) n1 = sum_digits_2(n1); while (!is_one_digit(n2)) n2 = sum_digits_2(n2); if (n1 == n2) cout << 0 << endl; else if (n1 > n2) cout << 1 << endl; else cout << 2 << endl; cin >> n >> m; } return 0; } ================================================ FILE: competitive-programming/uri/the_greatest.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1013 #include using namespace std; int abs(int a, int b) { if (a > b) return a - b; else if (a < b) return b - a; else return 0; } int main() { int n1, n2, n3; cin >> n1 >> n2 >> n3; int maior = ((n1 + n2) + abs(n1, n2)) / 2; maior = ((maior + n3) + abs(maior, n3)) / 2; cout << maior << " eh o maior" << endl; return 0; } ================================================ FILE: competitive-programming/uri/the_library_of_mr_severino.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2137 #include #include #include #include using namespace std; int main() { int n; string s; vector ss; while (cin >> n) { while (n--) { cin >> s; ss.push_back(s); } sort(ss.begin(), ss.end()); for (int i = 0; i < ss.size(); i++) { cout << ss[i] << endl; } ss.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/the_motion_picture.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1963 #include #include using namespace std; int main() { double n1, n2; cin >> n1 >> n2; cout << fixed << setprecision(2) << ((n2 - n1) / n1) * 100 << "%" << endl; return 0; } ================================================ FILE: competitive-programming/uri/the_pythagorean_theorem.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1582 #include #include #include using namespace std; #define min(m,n) ((m) < (n) ? (m) : (n)) int mdc(int m, int n){ int a = min(abs(m), abs(n));; while (m % a != 0 || n % a != 0) a--; return a; } int main(){ int x, y, z; while(cin >> x >> y >> z) { int hip, c1, c2; if(z >= y && z >= x) { hip = z; c1 = y; c2 = x; } else if (y >= z && y >= x) { hip = y; c1 = z; c2 = x; } else if (x >= z && x >= y) { hip = x; c1 = z; c2 = y; } printf("tripla"); if(hip * hip == (c1 * c1 + c2 * c2)) { printf(" pitagorica"); if(mdc(mdc(x,y), z) == 1) printf(" primitiva"); } cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/the_race_of_slugs.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1789 #include using namespace std; int main() { int n, x, faster = 0; while (scanf("%d", &n) != EOF) { while (n--) { cin >> x; if (x > faster) faster = x; } if (faster < 10) cout << 1 << endl; else if (faster < 20) cout << 2 << endl; else cout << 3 << endl; faster = 0; } return 0; } ================================================ FILE: competitive-programming/uri/the_return_of_radar.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2143 #include using namespace std; int main() { int n, x; while (cin >> n && n != 0) { while (n--) { cin >> x; if (x % 2 == 0) { cout << (x-2) * 2 + 2 << endl; } else { cout << (x-1) * 2 + 1 << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/the_return_of_the_king.cpp ================================================ #include #include #include using namespace std; int to_digit(char digit) { return digit - '0'; } int string_to_number(string n) { if (n == "") { return -1; } else { int num = 0; for (int i = 0; i < n.size(); i++) { num = num * 10 + to_digit(n[i]); } return num; } } int main() { string num; cin >> num; float total = 0, total_num = 0; for (int i = 0; i < num.size(); i++) { if (num[i] != '1') { total += to_digit(num[i]); } else { if (num[i+1] == '0') total += 10; else total += 1; } if (num[i] != '0') total_num++; } cout << fixed << setprecision(2) << total / total_num << endl; return 0; } ================================================ FILE: competitive-programming/uri/the_square_game.cpp ================================================ #include #include #include using namespace std; string findSquare(vector< vector > &matrix, int x, int n, int m) { int total = 1; for (int i = 0; i < n+1-x; i++) { for (int j = 0; j < m+1-x; j++) { for (int k = i; k < i+x; k++) { for (int l = j; l < j+x; l++) { total *= matrix[k][l]; } } if (total) return "yes"; total = 1; } } return "no"; } main() { vector v; vector< vector > matrix; int n, m, q, x; cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> x; v.push_back(x); } matrix.push_back(v); v.clear(); } cin >> q; int greater; while (q--) { cin >> x; if (x <= greater) { cout << "yes" << endl; } else if (findSquare(matrix, x, n, m) == "yes") { cout << "yes" << endl; greater = x; } else { cout << "no" << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/the_wrath_of_khan.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1964 #include using namespace std; int main() { int c, va, vb, t, d, da, db; cin >> c >> va >> vb >> t >> d; va /= 100; va *= 60; vb /= 100; vb *= 60; da = va * t; db = vb * t; if () return 0; } ================================================ FILE: competitive-programming/uri/theons_answer.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1858 #include using namespace std; int main() { int n, x, smaller=21, index; cin >> n; for (int i = 1; i <= n; i++) { cin >> x; if (x < smaller) { smaller = x; index = i; } } cout << index << endl; return 0; } ================================================ FILE: competitive-programming/uri/threebonacci_sequence.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1739 #include #include using namespace std; bool hasDigitThree(unsigned long long int n) { bool has = false; while (n) { if (n % 10 == 3) { has = true; break; } n /= 10; } return has; } unsigned long long int fibonacci(int n) { map ar, threebonacci; ar[1] = 1; ar[2] = 1; int counter = 1; for (int i = 3; counter <= 60; i++) { ar[i] = ar[i-1] + ar[i-2]; if ((ar[i] % 3 == 0 || hasDigitThree(ar[i]))) { threebonacci[counter] = ar[i]; counter++; } if (counter > n) break; } return threebonacci[n]; } int main() { int n; while (cin >> n) { cout << fibonacci(n) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/throwing_cards_away.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1110 #include #include using namespace std; struct num { int number; bool discarded; }; int main() { int n; while (cin >> n && n != 0) { vector numbers; vector discardedNumbers; for (int i = 1; i <= n; i++) { num k; k.number = i; k.discarded = false; numbers.push_back(k); } int numberOfDiscardedNum = 0; int startIndex = 0; int counter; while (numberOfDiscardedNum < n - 1) { counter = 2; numbers[startIndex].discarded = true; discardedNumbers.push_back(numbers[startIndex].number); while (counter--) { startIndex++; if (startIndex >= n) startIndex = 0; while (numbers[startIndex].discarded) { startIndex++; if (startIndex >= n) startIndex = 0; } } numberOfDiscardedNum++; } cout << "Discarded cards: " << discardedNumbers[0]; for (int i = 1; i < discardedNumbers.size(); i++) { cout << ", " << discardedNumbers[i]; } cout << endl << "Remaining card: "; for (int i = 1; i < n; i++) { if (!numbers[i].discarded) cout << numbers[i].number << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/time_conversion.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1019 #include #include using namespace std; int main() { int time, hours=0, minutes=0, seconds=0; cin >> time; while (time >= 3600) { time -= 3600; hours++; } while (time >= 60) { time -= 60; minutes++; } while (time >= 1) { time -= 1; seconds++; } cout << hours << ":" << minutes << ":" << seconds << endl; return 0; } ================================================ FILE: competitive-programming/uri/time_zone.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2057 #include using namespace std; int main() { int n1, n2, n3; cin >> n1 >> n2 >> n3; int total = n1 + n2 + n3; if (total >= 24) total -= 24; else if (total < 0) total += 24; cout << total << endl; return 0; } ================================================ FILE: competitive-programming/uri/to_care_or_not_to_care.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1026 #include #include #include #include using namespace std; void add_zero_values(vector &v1, vector &v2) { int v1_size = v1.size(), v2_size = v2.size(), difference; if (v1_size > v2_size) { difference = v1_size - v2_size; for (int j = 0; j < difference; j++) v2.push_back(0); } else if (v1_size < v2_size) { difference = v2_size - v1_size; for (int j = 0; j < difference; j++) v1.push_back(0); } if (v1.size() % 4 != 0) { int total_num_of_values = v1.size(); int num_needed = total_num_of_values % 4; difference = 4 - num_needed; for (int j = 0; j < difference; j++) v1.push_back(0); for (int j = 0; j < difference; j++) v2.push_back(0); } } vector to_binary_number(int n) { vector v; while (n > 0) { v.push_back(n % 2); n /= 2; } return v; } unsigned int to_decimal(vector &v) { unsigned int decimal_num = 0; int size = v.size(); for (int i = 0; i < size; i++) if (v[i] == 1) decimal_num += pow(2, size-i-1); return decimal_num; } int main() { int num1, num2; while (scanf("%i %i", &num1, &num2) != EOF) { vector binary_num1 = to_binary_number(num1); vector binary_num2 = to_binary_number(num2); for (int j = 0; j < binary_num1.size(); j++) cout << binary_num1[j]; cout << endl; for (int j = 0; j < binary_num2.size(); j++) cout << binary_num2[j]; cout << endl; reverse(binary_num1.begin(), binary_num1.end()); reverse(binary_num2.begin(), binary_num2.end()); add_zero_values(binary_num1, binary_num2); vector new_vec; for (int j = 0; j < binary_num1.size(); j++) cout << binary_num1[j]; cout << endl; for (int j = 0; j < binary_num2.size(); j++) cout << binary_num2[j]; cout << endl; for (int i = 0; i < binary_num2.size(); i++) { if (binary_num1[i] == binary_num2[i]) new_vec.push_back(0); else new_vec.push_back(1); } cout << to_decimal(new_vec) << endl; } return 0; } ================================================ FILE: competitive-programming/uri/to_care_or_not_to_care2.cpp ================================================ #include using namespace std; int main() { unsigned long int a, b, i; while(cin >> a >> b){ i = a ^ b; cout << i << endl; } return 0; } ================================================ FILE: competitive-programming/uri/top_n.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1943 #include using namespace std; int main() { int n; cin >> n; if (n <= 1) { cout << "Top 1" << endl; } else if (n <= 3) { cout << "Top 3" << endl; } else if (n <= 5) { cout << "Top 5" << endl; } else if (n <= 10) { cout << "Top 10" << endl; } else if (n <= 25) { cout << "Top 25" << endl; } else if (n <= 50) { cout << "Top 50" << endl; } else if (n <= 100) { cout << "Top 100" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/tornado.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1266 #include using namespace std; int main() { int n; char post; while (cin >> n && n != 0) { int neededPostsNumber = 0, sum = 0, x, numberOfBrokenPosts = 0, firstZeros = 0; bool finishedFirstZerosLot = false; for (int i = 0; i < n; i++) { cin >> post; if (i == 0 && post == '1') finishedFirstZerosLot = true; x = post - '0'; sum += x; if (sum > 0) { if (numberOfBrokenPosts % 2 == 0) neededPostsNumber += numberOfBrokenPosts / 2; else neededPostsNumber += (numberOfBrokenPosts-1) / 2; numberOfBrokenPosts = 0; sum = 0; finishedFirstZerosLot = true; } else { numberOfBrokenPosts++; if (!finishedFirstZerosLot) firstZeros++; } } if (numberOfBrokenPosts % 2 == 0) neededPostsNumber += numberOfBrokenPosts / 2; else neededPostsNumber += (numberOfBrokenPosts-1) / 2; if (firstZeros + numberOfBrokenPosts != 0 && (firstZeros + numberOfBrokenPosts) % 2 == 0) neededPostsNumber++; cout << neededPostsNumber << endl; } return 0; } ================================================ FILE: competitive-programming/uri/train_swaping.cpp ================================================ #include using namespace std; #define swap(a, b) { int x=a; a=b; b=x; } int numberOfSwaps(int v[], int n) { int swapNumber = 0; for (int i = 1; i <= n - 1; i++) { for (int j = 0; j < n - i; j++) { if (v[j] > v[j+1]) { swap(v[j], v[j+1]); swapNumber++; } } } return swapNumber; } int main() { int n, x, c; cin >> n; while (n--) { int num = 0; cin >> c; int ar[51]; for (int i = 0; i < c; i++) { cin >> x; ar[i] = x; num++; } cout << "Optimal train swapping takes " << numberOfSwaps(ar, num) << " swaps." << endl; } return 0; } ================================================ FILE: competitive-programming/uri/tri-du.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1933 #include using namespace std; int main() { int n1, n2, n3; cin >> n1 >> n2; if (n1 >= n2) cout << n1 << endl; else if (n2 > n1) cout << n2 << endl; return 0; } ================================================ FILE: competitive-programming/uri/triangle.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1043 #include #include using namespace std; int is_triangle(double a, double b, double c) { if ((a < b + c) && (b < a + c) && (c < a + b)) return 1; else return 0; } int main() { double a, b, c; cin >> a >> b >> c; if (is_triangle(a, b, c)) { cout << fixed << setprecision(1) << "Perimetro = " << a + b + c << endl; } else { cout << fixed << setprecision(1) << "Area = " << (a + b) * c / 2 << endl; } return 0; } ================================================ FILE: competitive-programming/uri/triangle_types.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1045 #include #include #include #include using namespace std; int is_triangle(double a, double b, double c) { if ((a < b + c) && (b < a + c) && (c < a + b)) return 1; else return 0; } int main() { double a, b, c, n; cin >> a >> b >> c; if (b > a && b >= c) { n = b; b = a; a = n; } else if (c > a && c >= b) { n = c; c = a; a = n; } if (is_triangle(a, b, c)) { if (pow(a, 2) == pow(b, 2) + pow(c, 2)) { cout << "TRIANGULO RETANGULO" << endl; } else if (pow(a, 2) > pow(b, 2) + pow(c, 2)) { cout << "TRIANGULO OBTUSANGULO" << endl; } else if (pow(a, 2) < pow(b, 2) + pow(c, 2)) { cout << "TRIANGULO ACUTANGULO" << endl; } if (a == b && a != c || a == c && a != b || b == c && a != c) cout << "TRIANGULO ISOSCELES" << endl; else if (a == b && a == c) cout << "TRIANGULO EQUILATERO" << endl; } else { cout << "NAO FORMA TRIANGULO" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/triangles.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1472 #include #include using namespace std; int main() { int n, x, num, sum, partOfArc; while (cin >> n) { vector nums; sum = 0; for (int i = 0; i < n; i++) { cin >> x; sum += x; nums.push_back(x); } if (sum % 3 == 0) { partOfArc = sum / 3; } else { cout << 0 << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/tribol.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1875 #include #include #include using namespace std; int main() { int n, m; string p1, p2; cin >> n; while (n--) { int b = 0, g = 0, r = 0; cin >> m; while (m--) { cin >> p1 >> p2; if (p1 == "G") { if (p2 == "B") g += 2; else g++; } else if (p1 == "R") { if (p2 == "G") r += 2; else r++; } else { if (p2 == "R") b += 2; else b++; } } if (b == g && b == r) cout << "trempate" << endl; else if (b > g && b == r) cout << "empate" << endl; else if (g > b && g == r) cout << "empate" << endl; else if (g > r && g == b) cout << "empate" << endl; else if (g > r && g > b) cout << "green" << endl; else if (b > r && b > g) cout << "blue" << endl; else if (r > g && r > b) cout << "red" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/trinomial_triangle.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1795 #include #include using namespace std; int main() { int n; cin >> n; long long int result = pow(3, n); cout << result << endl; return 0; } ================================================ FILE: competitive-programming/uri/tshirt2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1258 #include #include #include #include using namespace std; struct tshirt { string color; string tshirtSize; }; int clothesFound(vector< pair< tshirt, vector > > &clothes, string tshirtSize, string color) { for (int i = 0; i < clothes.size(); i++) { if (clothes[i].first.tshirtSize == tshirtSize && clothes[i].first.color == color) return i; } return -1; } bool compareClothes(const pair< tshirt, vector > &p1, const pair< tshirt, vector > &p2) { if (p1.first.color < p2.first.color) return true; else if (p1.first.color > p2.first.color) return false; else { if (p1.first.tshirtSize >= p2.first.tshirtSize) return true; else return false; } } int main() { int n, found; string name, tshirtSize, color; cin >> n; while (n != 0) { vector< pair< tshirt, vector > > clothes; vector v; while (n--) { cin.ignore(); getline(cin, name); cin >> color >> tshirtSize; tshirt t; t.tshirtSize = tshirtSize; t.color = color; found = clothesFound(clothes, tshirtSize, color); if (found != -1) { clothes[found].second.push_back(name); } else { vector names; names.push_back(name); clothes.push_back(make_pair(t, names)); } } sort(clothes.begin(), clothes.end(), compareClothes); for (int i = 0; i < clothes.size(); i++) { sort(clothes[i].second.begin(), clothes[i].second.end()); for (int j = 0; j < clothes[i].second.size(); j++) { cout << clothes[i].first.color << " " << clothes[i].first.tshirtSize << " " << clothes[i].second[j] << endl; } } cin >> n; if (n) cout << endl; } return 0; } ================================================ FILE: competitive-programming/uri/tshirts.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1258 #include #include #include #include using namespace std; int main() { int n; string name, tshirt, size; while (cin >> n && n != 0) { cin.ignore(); map < string, pair< string, vector > > m; vector v; while (n--) { getline(cin, name); cin >> tshirt >> size; if (m.find(tshirt) != m.end()) { m[tshirt].second.push_back(name); } else { v.push_back(name); m[tshirt] = make_pair(size, v); v.clear(); } } for (map < string, pair< string, vector > >::iterator it = m.begin(); it != m.end(); ++it) { for (int i = 0; i < it->second.size(); i++) { cout << it->first << " " << it->second[i] << endl; } } } return 0; } ================================================ FILE: competitive-programming/uri/tug_of_war.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1586 #include #include using namespace std; int main() { int n; string names; while (cin >> n && n != 0) { } return 0; } ================================================ FILE: competitive-programming/uri/turma_jb6.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2626 #include #include using namespace std; int main() { string j1, j2, j3; while (cin >> j1 >> j2 >> j3) { if (j1 == "papel" && j2 == "pedra" && j3 == j2 || j1 == "pedra" && j2 == "tesoura" && j3 == j2 || j1 == "tesoura" && j2 == "papel" && j3 == j2) { cout << "Os atributos dos monstros vao ser inteligencia, sabedoria..." << endl; } else if (j2 == "papel" && j1 == "pedra" && j3 == j1 || j2 == "pedra" && j1 == "tesoura" && j3 == j1 || j2 == "tesoura" && j1 == "papel" && j3 == j1) { cout << "Iron Maiden's gonna get you, no matter how far!" << endl; } else if (j3 == "papel" && j1 == "pedra" && j2 == j1 || j3 == "pedra" && j1 == "tesoura" && j2 == j1 || j3 == "tesoura" && j1 == "papel" && j2 == j1) { cout << "Urano perdeu algo muito precioso..." << endl; } else { cout << "Putz vei, o Leo ta demorando muito pra jogar..." << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/turn_left.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1437 #include #include using namespace std; int main() { int n; cin >> n; string s; while (n) { getline(cin, s); char dir[1] = 'N'; for (int i = 0; i < n; i++) { if (s[i] == 'D') { if (dir == 'N') dir = 'L'; else if (dir == 'L') dir = 'S'; else if (dir == 'S') dir = 'O'; else if (dir == 'O') dir = 'N'; } else { if (dir == 'N') dir = 'O'; else if (dir == 'O') dir = 'S'; else if (dir == 'S') dir = 'L'; else if (dir == 'L') dir = 'N'; } } cout << dir << endl; cin.ignore(); cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/turn_left2.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1437 #include #include #include using namespace std; int main() { int n; cin >> n; string directions; char ar[] = { 'N', 'L', 'S', 'O' }; while (n) { int num = 0; cin >> directions; for (int i = 0; i < directions.size(); i++) { if (directions[i] == 'D') { if (num >= 3) num = 0; else num++; } else { if (num <= 0) num = 3; else num--; } } cout << ar[num] << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/tustin_and_his_new_die.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2600 #include #include #include using namespace std; int main() { long long int N, n1, n2, n3, n4, n5, n6, total; vector V; cin >> N; while (N--) { cin >> n1 >> n2 >> n3 >> n4 >> n5 >> n6; V.push_back(n1); V.push_back(n2); V.push_back(n3); V.push_back(n4); V.push_back(n5); V.push_back(n6); sort(V.begin(), V.end()); if (n1 + n6 == 7 && n2 + n4 == 7 && n3 + n5 == 7 && V[0] == 1 && V[1] == 2 && V[2] == 3 && V[3] == 4 && V[4] == 5 && V[5] == 6) cout << "SIM" << endl; else cout << "NAO" << endl; V.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/twilight_at_portland.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2168 #include using namespace std; bool isSecure(int matrix[101][101], int i, int j) { int numOfCameras = 0; numOfCameras += matrix[i][j]; numOfCameras += matrix[i][j+1]; numOfCameras += matrix[i+1][j]; numOfCameras += matrix[i+1][j+1]; return numOfCameras >= 2; } int main() { int n; int matrix[101][101]; string line; cin >> n; for (int i = 0; i < n+1; i++) { for (int j = 0; j < n+1; j++) { cin >> matrix[i][j]; } } for (int i = 0; i < n; i++) { line = ""; for (int j = 0; j < n; j++) { if (isSecure(matrix, i, j)) line += "S"; else line += "U"; } cout << line << endl; } return 0; } ================================================ FILE: competitive-programming/uri/twitting.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2165 #include #include using namespace std; int main() { string tweet; getline(cin, tweet); if (tweet.size() <= 140) cout << "TWEET" << endl; else cout << "MUTE" << endl; return 0; } ================================================ FILE: competitive-programming/uri/two_bills.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2140 #include using namespace std; int getMaximumBill(int diff) { if (diff >= 100) return 100; else if (diff >= 50) return 50; else if (diff >= 20) return 20; else if (diff >= 10) return 10; else if (diff >= 5) return 5; else return 2; } int main() { int n1, n2, diff, firstBill, counter; while (cin >> n1 >> n2 && n1 + n2 != 0) { counter = 0; diff = n2 - n1; while (diff > 0 && counter < 2) { firstBill = getMaximumBill(diff); diff -= firstBill; counter++; } if (counter == 2 && diff == 0) cout << "possible" << endl; else cout << "impossible" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/type_of_fuel.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1134 #include using namespace std; int main() { int total_of_alcool=0, total_of_gas=0, total_of_diesel=0, n; cin >> n; while (n != 4) { if (n == 1) { total_of_alcool++; } else if (n == 2) { total_of_gas++; } else if (n == 3) { total_of_diesel++; } cin >> n; } cout << "MUITO OBRIGADO" << endl; cout << "Alcool: " << total_of_alcool << endl; cout << "Gasolina: " << total_of_gas << endl; cout << "Diesel: " << total_of_diesel << endl; return 0; } ================================================ FILE: competitive-programming/uri/upset_fracil.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2005 #include #include #include using namespace std; struct msComparator { bool operator() (const int &lhs, const int &rhs) const { return lhs > rhs; } }; int main() { int n1, n2, temp, food, decremented; while (cin >> n1 >> n2) { multiset ms; multiset::iterator it; for (int i = 0; i < n1; i++) { cin >> temp; ms.insert(temp); } int counter = 0; while (n2--) { cin >> food; bool hunger_satisfied = false; for (it = ms.begin(); it != ms.end(); ++it) { if (food >= *it && *it > 0) { counter++; ms.erase(*it); hunger_satisfied = true; break; } } if (!hunger_satisfied) { multiset::iterator first = ms.begin(); decremented = *first; ms.erase(first); ms.insert(decremented - food); } } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/uri.cpp ================================================ #include #include #include #include using namespace std; bool is_power_of_two(int n) { for (int i = 2; i <= n; i *= 2) if (i == n) return true; return false; } string get_winner(vector &points) { int bigger = -1, index = -1; for (int i = 0; i < points.size(); i++) { if (points[i] > bigger) { index = i; bigger = points[i]; } } for (int i = 0; i < points.size(); i++) cout << points[i] << " "; cout << endl; sort(points.begin(), points.end()); int last = points.back(), penultimate = points.end()[-2]; if (last == penultimate) return "URI"; else if (index == 0) return "Uilton"; else if (index == 1) return "Rita"; else return "Ingred"; } int main() { int n, x; cin >> n; while (n != 0) { vector points(3, 0); while (n--) { int greater = 0, index = -1; for (int i = 0; i < 3; i++) { cin >> x; if (is_power_of_two(x)) { points[i]++; if (x > greater) { greater = x; index = i; } } } if (index != -1) points[index]++; } string winner = get_winner(points); cout << winner << endl; cin >> n; } return 0; } ================================================ FILE: competitive-programming/uri/vai_na_sort.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2592 #include using namespace std; int main() { int N, num, counter, count; bool right; while (cin >> N && N != 0) { right = false; counter = 0; while (!right) { count = 0; for (int i = 1; i <= N; i++) { cin >> num; if (num == i) count++; } right = count == N; counter++; } cout << counter << endl; } return 0; } ================================================ FILE: competitive-programming/uri/variations.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1632 #include #include using namespace std; bool in_new(char l) { if (l == 'a' || l == 'A' || l == 'e' || l == 'E' || l == 'i' || l == 'I' || l == 'o' || l == 'O' || l == 's' || l == 'S') return true; return false; } int main() { int n, total; cin >> n; string code; while (n--) { cin >> code; total = 1; for (int i = 0; i < code.size(); i++) { if (in_new(code[i])) total *= 3; else total *= 2; } cout << total << endl; } return 0; } ================================================ FILE: competitive-programming/uri/virus.cpp ================================================ // https://www.urionlinejudge.com.br/judge/pt/problems/view/2567 #include #include #include using namespace std; int main() { int N, num, level; while (cin >> N) { vector V; level = 0; while (N--) { cin >> num; V.push_back(num); } sort(V.begin(), V.end()); for (int i = 0; i < V.size() / 2; i++) { level += (V[V.size()-1] - V[i]); } cout << level << endl; } return 0; } ================================================ FILE: competitive-programming/uri/vitoria_and_her_indecision.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1924 #include #include using namespace std; int main() { int n; cin >> n; string course; while (n--) { cin >> course; } cout << "Ciencia da Computacao" << endl; return 0; } ================================================ FILE: competitive-programming/uri/volleyball.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/2310 #include #include #include using namespace std; int main() { int n, saque, bloqueio, ataque; float totalSaque = 0, totalBloqueio = 0, totalAtaque = 0; float totalSaqueOk = 0, totalBloqueioOk = 0, totalAtaqueOk = 0; string s; cin >> n; while (n--) { cin >> s; cin >> saque >> bloqueio >> ataque; totalSaque += saque; totalBloqueio += bloqueio; totalAtaque += ataque; cin >> saque >> bloqueio >> ataque; totalSaqueOk += saque; totalBloqueioOk += bloqueio; totalAtaqueOk += ataque; } cout << setprecision(2) << fixed << "Pontos de Saque: " << totalSaqueOk / totalSaque * 100 << " %." << endl; cout << setprecision(2) << fixed << "Pontos de Bloqueio: " << totalBloqueioOk / totalBloqueio * 100 << " %." << endl; cout << setprecision(2) << fixed << "Pontos de Ataque: " << totalAtaqueOk / totalAtaque * 100 << " %." << endl; return 0; } ================================================ FILE: competitive-programming/uri/weighted_averages.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1079 #include #include using namespace std; int main() { int n; double weight1, weight2, weight3, total=0; cin >> n; while (n--) { cin >> weight1; total += weight1 * 2; cin >> weight2; total += weight2 * 3; cin >> weight3; total += weight3 * 5; cout << fixed << setprecision(1) << total / 10 << endl; total = 0; } return 0; } ================================================ FILE: competitive-programming/uri/welcome_to_the_winter.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1847 #include using namespace std; int main() { int a, b, c; cin >> a >> b >> c; if (a == b && b == c) { cout << ":(" << endl; } else { if (b - a < c - b) cout << ":)" << endl; else if (b - a == c - b && b - a > 0) cout << ":)" << endl; else if (b - a == c - b && b - a < 0) cout << ":(" << endl; else cout << ":(" << endl; } return 0; } ================================================ FILE: competitive-programming/uri/wertyu.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1196 #include #include using namespace std; int main() { string s = "QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./`1234567890-="; string thing; int index; while (getline(cin, thing)) { string new_thing = ""; for (int i = 0; i < thing.size(); i++) { if (thing[i] != ' ') { index = s.find(thing[i]) - 1; new_thing += s[index]; } else { new_thing += " "; } } cout << new_thing << endl; } return 0; } ================================================ FILE: competitive-programming/uri/where_is_the_marble.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1025 #include #include #include #include using namespace std; int main() { vector v; map m; int n, q, casy = 1, x; while (cin >> n >> q && n + q != 0) { for (int i = 0; i < n; i++) { cin >> x; v.push_back(x); } sort(v.begin(), v.end()); for (int i = 0; i < n; i++) { if (m.find(v[i]) != m.end()) m[v[i]] = i+1; } cout << "CASE# " << casy << ":" << endl; while (q--) { cin >> x; if (m.find(x) != m.end()) cout << x << " found at " << m[x] << endl; else cout << x << " not found" << endl; } casy++; v.clear(); m.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/which_triangle.cpp ================================================ #include #include #include #include using namespace std; string is_rectangular(int a, int b, int c) { if (c * c == a * a + b * b) return "Retangulo: S"; return "Retangulo: N"; } int main() { vector V; int N = 3, side; while (N--) { cin >> side; V.push_back(side); } sort(V.begin(), V.end()); if (V[2] >= V[0] + V[1]) { cout << "Invalido" << endl; } else { if (V[0] == V[1] && V[1] == V[2]) { cout << "Valido-Equilatero" << endl; cout << "Retangulo: N" << endl; } else if (V[0] == V[1] || V[1] == V[2]) { cout << "Valido-Isoceles" << endl; cout << is_rectangular(V[0], V[1], V[2]) << endl; } else { cout << "Valido-Escaleno" << endl; cout << is_rectangular(V[0], V[1], V[2]) << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/who_turn_is_it.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1914 #include #include using namespace std; int main() { int n, num1, num2, total; string player1, player2, strat1, strat2; cin >> n; while (n--) { cin >> player1 >> strat1 >> player2 >> strat2; cin >> num1 >> num2; total = num1 + num2; if (total % 2 == 0) { if (strat1 == "PAR") cout << player1 << endl; else cout << player2 << endl; } else { if (strat1 == "IMPAR") cout << player1 << endl; else cout << player2 << endl; } } return 0; } ================================================ FILE: competitive-programming/uri/wills_message.cpp ================================================ #include #include using namespace std; int main() { string message, s; int N, num; while (cin >> s) { cin >> N; message = ""; while (N--) { cin >> num; message += s[num-1]; } cout << message << endl; } return 0; } ================================================ FILE: competitive-programming/uri/world_cup.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1414 #include #include using namespace std; int main() { int n1, n2, x, points=0, total; string team; while (cin >> n1 >> n2 && n1 + n2 != 0) { total = n2 * 3; while (n1--) { cin >> team >> x; points += x; } cout << total - points << endl; points = 0; } return 0; } ================================================ FILE: competitive-programming/uri/zero_means_zero.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1871 #include #include #include using namespace std; int main() { long int n1, n2, total; cin >> n1 >> n2; vector numbers; while (n1 + n2 != 0) { total = n1 + n2; while (total != 0) { numbers.push_back(total % 10); total /= 10; } long int result = 0; int aux = 0; for (int i = 0; i < numbers.size(); i++) { if (numbers[i]) { result += numbers[i] * pow(10, aux); aux++; } } cout << result << endl; cin >> n1 >> n2; numbers.clear(); } return 0; } ================================================ FILE: competitive-programming/uri/zero_or_one.cpp ================================================ // https://www.urionlinejudge.com.br/judge/en/problems/view/1467 #include using namespace std; int main() { int a, b, c; while (scanf("%d %d %d", &a, &b, &c) != EOF) { if (a == b && a == c) { cout << "*" << endl; } else { if (b == c) cout << "A" << endl; else if (a == c) cout << "B" << endl; else if (a == b) cout << "C" << endl; } } return 0; } ================================================ FILE: competitive-programming/uva/280-vertex.cpp ================================================ // https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=666&page=show_problem&problem=216 #include using namespace std; typedef pair pii; typedef vector vii; typedef vector vi; int VISITED = 1; int UNVISITED = 0; void dfs(int vertex, vector & AdjList, set & reached, int dfs_num[]) { dfs_num[vertex] = VISITED; int edge; for (int i = 0; i < AdjList[vertex].size(); i++) { edge = AdjList[vertex][i]; reached.insert(edge); if (dfs_num[edge] == UNVISITED) dfs(edge, AdjList, reached, dfs_num); } } int main() { int n, edge, starting_vertex, test, vertex; vi V; vector AdjList; while (cin >> n && n) { for (int i = 0; i <= n; i++) { AdjList.push_back(V); } while (cin >> starting_vertex && starting_vertex) { while (cin >> edge && edge) { AdjList[starting_vertex].push_back(edge); } } cin >> test; while (test--) { set reached, unreached; cin >> vertex; int dfs_num[101]; bool a = false; fill(dfs_num, dfs_num+101, 0); dfs(vertex, AdjList, reached, dfs_num); for (int i = 1; i <= n; i++) { for (set::iterator it = reached.begin(); it != reached.end(); it++) { if (*it == i) a = true; } if (!a) unreached.insert(i); a = false; } if (unreached.size()) { cout << unreached.size(); for (set::iterator it = unreached.begin(); it != unreached.end(); it++) { cout << " " << *it; } cout << endl; } else { cout << unreached.size() << endl; } } AdjList.clear(); } return 0; } ================================================ FILE: competitive-programming/weekend-code-challenge/01-object-to-array-of-objects/README.md ================================================ # Problem What if you have an object and you want to convert that to an array of objects to do whatever you need to do? ## Example data ```js const ingredients = { cheese: 0, lettuce: 0, bacon: 1, meat: 4, }; ``` ## Expected output ```js const output = [ { name: 'lettuce', count: 0 }, { name: 'bacon', count: 0 }, { name: 'cheese', count: 1 }, { name: 'meat', count: 4 }, ]; ``` ================================================ FILE: competitive-programming/weekend-code-challenge/01-object-to-array-of-objects/soluition1.js ================================================ const ingredients = { lettuce: 0, bacon: 0, cheese: 1, meat: 4 }; const output = Object.entries(ingredients).map(([name, count]) => ({ name, count, })); ================================================ FILE: competitive-programming/weekend-code-challenge/02-my-likes/README.md ================================================ # Problem Given an array of posts and an array of your likes, how could you effeciently check if you liked a particular post or not? ## Example data ```js const posts = [ { id: 5, authorId: 1, content: 'Post 5', }, { id: 6, content: 'Post 6', authorId: 12, } ... ]; const likes = [ { id: 1, postId: 5 }, { id: 2, postId: 10 }, { id: 3, postId: 124 }, ... ]; ``` ### Notes - The `posts` array may contain posts from various users - The `likes` array only contains **your** likes - It's possible that many different users can like the same post ================================================ FILE: competitive-programming/weekend-code-challenge/02-my-likes/solution1.js ================================================ const posts = [ { id: 5, authorId: 1, content: 'Post 5', }, { id: 6, content: 'Post 6', authorId: 12, }, ]; const likes = [ { id: 1, postId: 5 }, { id: 2, postId: 10 }, { id: 3, postId: 124 }, ]; const isLiked = ({ id }, myLikes) => myLikes.some((like) => like.postId === id); const likedPosts = posts.filter((post) => isLiked(post, likes)); ================================================ FILE: competitive-programming/weekend-code-challenge/02-my-likes/solution2.js ================================================ const posts = [ { id: 5, authorId: 1, content: 'Post 5', }, { id: 6, content: 'Post 6', authorId: 12, }, ]; const likes = [ { id: 1, postId: 5 }, { id: 2, postId: 10 }, { id: 3, postId: 124 }, ]; const postToLikeMapper = likes.reduce( (mapper, { id, postId }) => ({ ...mapper, [postId]: id }), {} ); posts.filter(({ id }) => postToLikeMapper[id]); ================================================ FILE: competitive-programming/weekend-code-challenge/03-ch-ch-ch-changes/README.md ================================================ # Problem This is going to be a data structure problem, the kind of problem we often encounter with the data we have: namely, that the data structure is not in the format that we want! 😡 So, what to do? Given the following data: ```js data = { something: { title: 'something', copy: 'something', link: 'something' }, another: { title: 'another', copy: 'another', link: 'another' }, }; ``` Create a **function** that will allow you to efficiently convert your data into the following format: ```js output = [ { id: 'something', title: 'something', copy: 'something', link: 'something', }, { id: 'another', title: 'another', copy: 'another', link: 'another', }, ]; ``` As you can see, the goal of this exercise is to convert your data into an array of objects where the `id` for each object in the new array maps to the keys of the original object. ## Notes - As the original data is an object, all keys will be unique, so you don't have to worry about duplicate entries. - The data could be incredibly long or short so, as always, be mindful of time complexity. ## Tips - There are various ways to solve this problem, and it is useful to explore each. - Try to think of a multitude of solutions, get each working -- and then consider the strengths and weaknesses of each. - After you have your final answer, think about how you can clean it up. That is, how can you make the code more readable while also being concise? ================================================ FILE: competitive-programming/weekend-code-challenge/03-ch-ch-ch-changes/solution.js ================================================ const convertObjToArrayOfObjects = (data) => Object.entries(data).map(([key, values]) => ({ id: key, ...values, })); ================================================ FILE: competitive-programming/weekend-code-challenge/07-zero-to-hero/README.md ================================================ # Problem This problem is a fun one because there are so many different ways to solve it. Which means you can come up with multiple answers, practice multiple techniques and compare the relative strengths and weaknesses. That's a triple bonus for a weekend code challenge problem. So, the question is this: Given an array of integers, write a function that will return an array where all the zeros in that array are moved to the back of the array. For instance, given the following array: ```js [9, 0, 133, -1, 2, 0, 9]; ``` The correct output would look like this: ```js [9, 133, -1, 2, 9, 0, 0]; ``` ## Notes - There are no limitations on what you can do to the array. Feel free to mutate it in place if you like - The best answer will be done in linear time, with constant space complexity - Consider edge cases like if all the items were zeros (e.g. `[0, 0, 0, 0, 0, 0, 0]`) or if there are zeros at the beginning and end of your array (e.g. `[0, 0, 1, 33, -2, 0, 0]`) ================================================ FILE: competitive-programming/weekend-code-challenge/07-zero-to-hero/solution1.js ================================================ function zeroToHero(numbers) { const allButZeros = numbers.filter((number) => number); const zerosCount = numbers.filter((number) => !number).length; const zeros = new Array(zerosCount).fill(0); return [...allButZeros, ...zeros]; } ================================================ FILE: competitive-programming/weekend-code-challenge/08-first-non-repeat/README.md ================================================ # Problem This is a popular string problem that is pretty fun to solve. Given a string of characters without spaces like the following: ```md aaaccceeef ``` Write a function that returns the first non-repeating character. In this case, the correct answer would be `f`, since it is the first character in the string that doesn't have a repeat. Here are a few other examples and the correct answer for your reference: ```md abc0cb // correct answer is "a" a01110abc // correct answer is "b" aaaabbbccc // -1 since all are repeating ``` ## Notes - You will always have at least 1 character in the string (i.e. don't worry about an empty string) - Characters will only consist of alphanumeric characters, aA-zZ, 0-9 - If there are no non-repeating characters in the string, return `-1` ================================================ FILE: competitive-programming/weekend-code-challenge/08-first-non-repeat/solution1.js ================================================ const getArrayOfChars = (string = '') => string.split(''); const buildCharsCounter = (arrayOfChars) => { const charsCounter = {}; arrayOfChars.forEach((char) => { if (char in charsCounter) { charsCounter[char] += 1; } else { charsCounter[char] = 1; } }); return charsCounter; }; const getFirstNonRepeatingChar = (string = '') => { const arrayOfChars = getArrayOfChars(string); const charsCounter = buildCharsCounter(arrayOfChars); const isNonRepeatingChar = (char) => char in charsCounter && charsCounter[char] === 1; return arrayOfChars.find(isNonRepeatingChar) || -1; }; ================================================ FILE: competitive-programming/weekend-code-challenge/09-big-three/README.md ================================================ # Problem This is a classic problem, and a variation on an even more classic problem, which is to find the largest value in an array. Difference here is that you need to find the 3 largest values in the array. And they need to be returned in ascending order. So, to put it clearly, given an array of integers, write a function that will return an array of the 3 largest numbers from that array. Sample input: ```js [3, -100, 199, 10, 14, 555] ``` Expected output: ```js [14, 199, 555] ``` ## Notes: - The array will not be sorted, and you cannot sort it to solve this problem -- that would be too easy ;) - There will always be at least 3 values in the input array, and they will always be integers. - There may be duplicates of the same integers. Potentially all 3 values could be the same number if those are the largest integers in the array. ================================================ FILE: competitive-programming/weekend-code-challenge/09-big-three/solution1.js ================================================ const getBigThree = (numbers) => { let largest = -Infinity; let secondLargest = -Infinity; let thirdLargest = -Infinity; numbers.forEach((number) => { if (number > largest) { thirdLargest = secondLargest; secondLargest = largest; largest = number; } else if (number > secondLargest) { thirdLargest = secondLargest; secondLargest = number; } else if (number > thirdLargest) { thirdLargest = number; } }); return [thirdLargest, secondLargest, largest]; }; getBigThree([3, -100, 199, 10, 14, 555, 133, 555, 143, 1000]); ================================================ FILE: competitive-programming/weekend-code-challenge/09-big-three/solution2.js ================================================ const getLargestAndIndex = (numbers) => { let largest = -Infinity; let index; numbers.forEach((number, numberIndex) => { if (number > largest) { largest = number; index = numberIndex; } }); return [largest, index]; }; const removeItemByIndex = (numbers, index) => { return numbers.filter((_, numberIndex) => numberIndex !== index); }; const getBigThree = (numbers) => { let largest; let secondLargest; let thirdLargest; let index; let numbersCopy; [largest, index] = getLargestAndIndex(numbers); numbersCopy = removeItemByIndex(numbers, index); [secondLargest, index] = getLargestAndIndex(numbersCopy); numbersCopy = removeItemByIndex(numbersCopy, index); [thirdLargest] = getLargestAndIndex(numbersCopy); return [thirdLargest, secondLargest, largest]; }; ================================================ FILE: competitive-programming/weekend-code-challenge/10-get-the-photo/README.md ================================================ # Problem We've focused mostly on a bunch of algorithm problems lately, so let's take a break from that for a little while. This is going to be a slightly easier problem than the past few as well, so it is a good chance to take a breather, apply some of the concepts we've learned, and as usual, to think about a number of different ways we can solve this problem to find a truly great answer. So, the problem is this: Given an array of objects containing urls to an image of various sizes, write a function that will efficiently return an array of strings containing only the urls to the `large` image. ## Example input ```js [ { tiny: '//imageurl.../50x50/image_1.png', large: '//imageurl.../1200x1600/image_1.png', }, { tiny: '//imageurl.../50x50/image_2.png', large: '//imageurl.../1200x1600/image_2.png', }, { tiny: '//imageurl.../50x50/image_3.png', large: '//imageurl.../1200x1600/image_3.png', }, { tiny: '//imageurl.../50x50/image_4.png', large: '//imageurl.../1200x1600/image_4.png', }, { tiny: '//imageurl.../50x50/image_5.png', large: '//imageurl.../1200x1600/image_5.png', }, ... ]; ``` ## Expected output ```js ['//imageurl.../1200x1600/image_1.png', '//imageurl.../1200x1600/image_2.png', ...]; ``` ## Notes - The input array could be really long or really short - The input array will always be an array and it will always have at least one object - The object will always contain the key `large`, and you can ignore other keys if they are present ## Tips As I will often say on Weekend Code Challenge, it is really important to think of multiple solutions to each problem so as to avoid using the same techniques, which can become stale over time. Apply a variety of methods and built-in functions and try to find a solution that is not only efficient, but also easy to read and understand. ================================================ FILE: competitive-programming/weekend-code-challenge/10-get-the-photo/solution1.js ================================================ const getLargeImageUrls = (images) => images.map(({ large }) => large); ================================================ FILE: competitive-programming/weekend-code-challenge/11-threes-a-crowd/README.md ================================================ # Problem This is a simple real life problem that I recently encountered. Given an array of n values, create a new array of two-value arrays containing the original values. Each two-value array will contain the largest and smallest value from the initial array, and each value will only appear once within the set. If n is an odd number, the final array will include that additional value, making it the exception to the two-value rule. ## Example input (given n = 7) ```js [3, 7, 10, 5, 4, 4, 1]; ``` ## Expected output ```js [ [10, 1], [7, 3], [5, 4, 4], ]; ``` ## Notes ## Tips ================================================ FILE: competitive-programming/weekend-code-challenge/11-threes-a-crowd/solution1.js ================================================ const buildArrayOfTwoValuesArrays = (numbers) => { numbers.sort((a, b) => a - b); const array = []; for (let i = 0; i < numbers.length; i++) { if (i + 3 === numbers.length - i) { array.push([numbers[i + 2], numbers[i + 1], numbers[i]]); break; } if (i + 2 === numbers.length - i) { array.push([numbers[i + 1], numbers[i]]); break; } array.push([numbers[numbers.length - 1 - i], numbers[i]]); } return array; }; buildArrayOfTwoValuesArrays([3, 7, 10, 5, 4, 4, 1]); buildArrayOfTwoValuesArrays([3, 7, 10, 5, 4, 4]); ================================================ FILE: computer_science/README.md ================================================ # Computer Science ## Algorithms & Data Structures - Big O Time Complexity - Linear Search - Binary Search - Bubble Sort - Linked List Data Structure - Queue Data Structure ================================================ FILE: computer_science/algorithms/binary-search/binary-search.js ================================================ function getMiddle(start, end) { return Math.floor((start + end) / 2); } export function binarySearch(numbers, target) { let start = 0; let end = numbers.length - 1; let middle = getMiddle(start, end); let found = false; while (start <= end && !found) { middle = getMiddle(start, end); const middleNumber = numbers[middle]; if (middleNumber === target) found = true; if (middleNumber > target) end = middle - 1; if (middleNumber < target) start = middle + 1; } return found; } function logResult(list, target) { console.log(binarySearch(list, target)); } ================================================ FILE: computer_science/algorithms/binary-search/tests/binary-search.test.js ================================================ import { describe, expect, it } from 'vitest'; import { binarySearch } from '../binary-search'; describe('binarySearch', () => { const list = [1, 3, 4, 69, 71, 81, 90, 99, 420, 1337, 69420]; const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; it('passes the search', () => { expect(binarySearch(list, 69)).toBeTruthy(); expect(binarySearch(list, 1336)).toBeFalsy(); expect(binarySearch(list, 69420)).toBeTruthy(); expect(binarySearch(list, 69421)).toBeFalsy(); expect(binarySearch(list, 1)).toBeTruthy(); expect(binarySearch(list, 0)).toBeFalsy(); }); it('passes the search', () => { expect(binarySearch(numbers, 5)).toBeTruthy(); expect(binarySearch(numbers, 11)).toBeFalsy(); expect(binarySearch(numbers, -1)).toBeFalsy(); expect(binarySearch(numbers, 0)).toBeFalsy(); expect(binarySearch(numbers, 9)).toBeTruthy(); expect(binarySearch(numbers, 1)).toBeTruthy(); }); }); ================================================ FILE: computer_science/algorithms/bubble-sort/bubble-sort.js ================================================ export function bubbleSort(numbers) { for (let N = 0; N < numbers.length; N++) { for (let index = 0; index < numbers.length - N - 1; index++) { if (numbers[index] > numbers[index + 1]) { let number = numbers[index]; numbers[index] = numbers[index + 1]; numbers[index + 1] = number; } } } return numbers; } ================================================ FILE: computer_science/algorithms/bubble-sort/tests/bubble-sort.test.js ================================================ import { describe, expect, it } from 'vitest'; import { bubbleSort } from '../bubble-sort'; describe('bubbleSort', () => { it('sorts', () => { expect(bubbleSort([8, 5, 2, 5, 7, 5])).toEqual([2, 5, 5, 5, 7, 8]); expect( bubbleSort([8, 33, 5, 2, 7, 8, 6, 3, 4, 99, 2, 5, 2, 5, 7, 5]) ).toEqual([2, 2, 2, 3, 4, 5, 5, 5, 5, 6, 7, 7, 8, 8, 33, 99]); }); }); ================================================ FILE: computer_science/algorithms/dynamic_programming/factorial.cpp ================================================ #include #include using namespace std; unsigned long long factorial_dp(int n) { vector v(1000000); v[0] = 1; for (int i = 1; i <= n; i++) v[i] = v[i - 1] * i; return v[n]; } int main() { cout << factorial_dp(0) << endl; cout << factorial_dp(1) << endl; cout << factorial_dp(5) << endl; cout << factorial_dp(50) << endl; return 0; } ================================================ FILE: computer_science/algorithms/dynamic_programming/fibonacci.cpp ================================================ #include #include #include using namespace std; int fibonacci(int n) { // exponation time - T(n) = T(n - 1) + T(n - 2) + const(1) --> O(2^(n/2)) if (n <= 2) return 1; return fibonacci(n - 1) + fibonacci(n - 2); } int fibonacci_dp(int n) { if (n == 0) return 0; else if (n == 1) return 1; map fib; fib[0] = 0; fib[1] = 1; for (int i = 2; i <= n; ++i) fib[i] = fib[i-1] + fib[i-2]; return fib[n]; } int main() { int n = 5, m = 5; // recursive algorithm without DP cout << fibonacci(n) << endl; // memoized DP algorithm: add in the map. If we have the element in the map, return the result for(int i = 0; i < 20; i++) cout << fibonacci_dp(i) << endl; return 0; } ================================================ FILE: computer_science/algorithms/find_kth_element/find_kth_element_1.cpp ================================================ // Finding the kth element algorithm #include #include #include using namespace std; int find_kth_element(vector &elements, int k) { sort(elements.begin(), elements.end()); return elements[k-1]; } int main() { vector elements; elements.push_back(3); elements.push_back(6); elements.push_back(5); elements.push_back(8); elements.push_back(1); elements.push_back(2); elements.push_back(0); cout << find_kth_element(elements, 1) << endl; cout << find_kth_element(elements, 5) << endl; cout << find_kth_element(elements, 7) << endl; return 0; } ================================================ FILE: computer_science/algorithms/graphs/bfs.cpp ================================================ #include using namespace std; typedef pair pii; typedef vector vii; typedef vector vi; int VISITED = 1; int UNVISITED = 0; int vertices_number = 100; int INF = -1; void bfs(vii AdjList, int s) { vi d(vertices_number, INF); d[s] = 0; queue q; q.push(s); while (!queue.empty()) { int u = q.front(); q.pop(); for (int i = 0; i < AdjList[u].size(); i++) { ii v = AdjList[u][i]; if (d[v.first] == INF) { d[v.first] = d[u] + 1; q.push(v.first); } } } } int main() { return 0; } ================================================ FILE: computer_science/algorithms/graphs/dfs.cpp ================================================ #include using namespace std; typedef pair pii; typedef vector vii; typedef vector vi; int VISITED = 1; int UNVISITED = 0; int vertices_number = 100; vi dfs_num(vertices_number, 0); void dfs(int u) { dfs_num[u] = VISITED; for (int j = 0; j < AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dfs_num[v.first] == UNVISITED) dfs(v.first); } } int main() { return 0; } ================================================ FILE: computer_science/algorithms/is-prime/is-prime.js ================================================ function isPrime(num) { for (let i = 2, s = Math.sqrt(num); i <= s; i++) { if (num % i === 0) return false; } return num > 1; } ================================================ FILE: computer_science/algorithms/kadane/kadane.js ================================================ function maxSubArray(nums) { let maxSum = nums[0]; let localSum = nums[0]; for (let index = 1; index < nums.length; index++) { localSum = Math.max(nums[index], localSum + nums[index]); maxSum = Math.max(maxSum, localSum); } return maxSum; } ================================================ FILE: computer_science/algorithms/knapsack/knapsack1.cpp ================================================ #include int max(int a, int b) { return (a > b)? a : b; } int knapsack(int totalWeight, int weights[], int values[], int n) { int K[n+1][totalWeight+1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= totalWeight; j++) { if (i == 0 || j == 0) K[i][j] = 0; else if (weights[i-1] <= j) K[i][j] = max(values[i-1] + K[i-1][j - weights[i-1]], K[i-1][j]); else K[i][j] = K[i-1][j]; } } return K[n][totalWeight]; } int main() { int values[] = { 4, 1, 2, 5 }; int weighs[] = { 100, 100, 120, 80 }; int totalWeight = 200; int n = sizeof(values) / sizeof(values[0]); printf("%d\n", knapsack(totalWeight, weighs, values, n)); return 0; } ================================================ FILE: computer_science/algorithms/knapsack/knapsack2.cpp ================================================ #include #include using namespace std; int max(int a, int b) { return (a > b)? a : b; } int knapsack(int totalWeight, vector &weights, vector &values, int n) { int K[n+1][totalWeight+1]; for (int i = 0; i <= n; i++) { for (int j = 0; j <= totalWeight; j++) { if (i == 0 || j == 0) K[i][j] = 0; else if (weights[i-1] <= j) K[i][j] = max(values[i-1] + K[i-1][j - weights[i-1]], K[i-1][j]); else K[i][j] = K[i-1][j]; } } return K[n][totalWeight]; } int main() { int v[] = { 4, 1, 2, 5 }; int w[] = { 100, 100, 120, 80 }; vector values; vector weights; for (int i = 0; i < 4; ++i) values.push_back(v[i]); for (int i = 0; i < 4; ++i) weights.push_back(w[i]); int totalWeight = 200; int n = values.size(); cout << knapsack(totalWeight, weights, values, n) << endl; return 0; } ================================================ FILE: computer_science/algorithms/least_common_multiple/least_common_multiple.cpp ================================================ #include using namespace std; int lcm(int num1, int num2) { int remainder, n1 = num1, n2 = num2; do { remainder = n1 % n2; n1 = n2; n2 = remainder; } while (remainder != 0); return (num1 * num2) / n1; } int main() { cout << lcm(6, 3) << endl; return 0; } ================================================ FILE: computer_science/algorithms/linear-search/linear-search.js ================================================ export function linearSearch(list, value) { for (let item of list) { if (item === value) { return true; } } return false; } ================================================ FILE: computer_science/algorithms/linear-search/tests/linear-search.test.js ================================================ import { describe, expect, it } from 'vitest'; import { linearSearch } from '../linear-search'; describe('linearSearch', () => { it('linear search array', () => { const foo = [1, 3, 4, 69, 71, 81, 90, 99, 420, 1337, 69420]; expect(linearSearch(foo, 69)).toBeTruthy(); expect(linearSearch(foo, 1336)).toBeFalsy(); expect(linearSearch(foo, 69420)).toBeTruthy(); expect(linearSearch(foo, 69421)).toBeFalsy(); expect(linearSearch(foo, 1)).toBeTruthy(); expect(linearSearch(foo, 0)).toBeFalsy(); }); }); ================================================ FILE: computer_science/algorithms/maximum_subsequence_sum/maximum_subsequence_sum_1.cpp ================================================ #include using namespace std; int maximum_subsequence_sum(int ar[], int n) { int sum = 0, result = 0; for (int i = 0; i < n; i++) { if (sum + ar[i] > 0) sum += ar[i]; else sum = 0; if (sum > result) result = sum; } return result; } int main() { int n, result; int ar1[] = { 1, -3, 2, -5, 7, 6, -1, -4, 11, -23 }; n = 10; result = maximum_subsequence_sum(ar1, n); cout << result << endl; int ar2[] = { 1, -3, 2, -5, 7 }; n = 5; result = maximum_subsequence_sum(ar2, n); cout << result << endl; int ar3[] = { 1, -3, 6, -5, 7 }; n = 5; result = maximum_subsequence_sum(ar3, n); cout << result << endl; return 0; } ================================================ FILE: computer_science/algorithms/maximum_subsequence_sum/maximum_subsequence_sum_2.cpp ================================================ #include #include using namespace std; int maximum_subsequence_sum(vector &v) { int sum = 0, result = 0; for (int i = 0; i < v.size(); i++) { if (sum + v[i] > 0) sum += v[i]; else sum = 0; if (sum > result) result = sum; } return result; } int main() { int result; int ar1[] = { 1, -3, 2, -5, 7, 6, -1, -4, 11, -23 }; vector v1(ar1, ar1 + sizeof(ar1) / sizeof(ar1[0])); result = maximum_subsequence_sum(v1); cout << result << endl; int ar2[] = { 1, -3, 2, -5, 7 }; vector v2(ar2, ar2 + sizeof(ar2) / sizeof(ar2[0])); result = maximum_subsequence_sum(v2); cout << result << endl; int ar3[] = { 1, -3, 6, -5, 7 }; vector v3(ar3, ar3 + sizeof(ar3) / sizeof(ar3[0])); result = maximum_subsequence_sum(v3); cout << result << endl; return 0; } ================================================ FILE: computer_science/algorithms/min_and_max/minimax.cpp ================================================ #include using namespace std; void minimax(int v[], int n, int &a, int &b) { a = v[0]; b = v[0]; for (int i = 1; i < n; i++) { if (a > v[i]) a = v[i]; if (b < v[i]) b = v[i]; } } int main() { int v[] = { 1, 4, 6, 22 }; int a, b; minimax(v, 4, a, b); cout << "a: " << a << endl; cout << "b: " << b << endl; return 0; } ================================================ FILE: computer_science/algorithms/parse_strings/parse_strings.cpp ================================================ #include #include #include using namespace std; vector parse_string(string line) { vector v; string word = ""; for (int i = 0; i < line.size(); i++) { if (line[i] == ' ') { v.push_back(word); word.clear(); } else if (i == line.size() - 1) { word += line[i]; v.push_back(word); word.clear(); } else { word += line[i]; } } return v; } int main() { string s = "Top Coder comp Wedn at midnight"; vector strings = parse_string(s); for (int i = 0; i < strings.size(); i++) cout << strings[i] << endl; return 0; } ================================================ FILE: computer_science/algorithms/pointers/pointer.cpp ================================================ #include using namespace std; int main() { int n = 10; int *p; p = &n; cout << "N value: " << n << endl; cout << "Address pointed by P: " << p << endl; cout << "Value from the address pointed by P: " << *p << endl; *p = 20; cout << "Changed the value from the address pointed by P: " << *p << endl; cout << "New N value: " << n << endl; return 0; } ================================================ FILE: computer_science/algorithms/prime_number/prime_number.cpp ================================================ #include #include using namespace std; bool is_prime_number(int n) { if (n < 2) return false; if (n == 2) return true; if ((n % 2) == 0) return false; int s = sqrt(n); for (int i = 3; i <= s; i += 2) if (n % i == 0) return false; return true; } int main() { int n; cin >> n; while (n) { if (is_prime_number(n)) cout << "True" << endl; else cout << "False" << endl; cin >> n; } return 0; } ================================================ FILE: computer_science/algorithms/recursion/fibonacci/fibonacci.c ================================================ #include #include int fibonacciHelper(int n, int first, int second); int fibonacci(int n); int main() { fibonacci(10); return 0; } int fibonacciHelper(int n, int first, int second) { if (n == 1) return 0; if (n == 2) return 1; printf("%d\n", second); return fibonacciHelper(n - 1, second, first + second); } int fibonacci(int n) { return fibonacciHelper(n, 1, 0); } ================================================ FILE: computer_science/algorithms/recursion/fibonacci/fibonacci.py ================================================ # Fibonacci Sequence: 0 1 1 2 3 5 8 13 ... def fibonacci(num): if num == 1: return 0 if num == 2: return 1 return fibonacci(num-1) + fibonacci(num-2) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5)) ================================================ FILE: computer_science/algorithms/recursion/log_2.c ================================================ #include #include int log_2(int n); int main() { int i; for (i = 1; i <= 16; i++) printf("%d\n", log_2(i)); return 0; } int log_2(int n) { if (n <= 1) return 0; return 1 + log_2(n / 2); } ================================================ FILE: computer_science/algorithms/recursion/palindromo.c ================================================ #include #include int palindromo(char *n); int main() { char num1[6] = { '3', '6', '9', '9', '6', '3' }; char *n1 = num1; if (palindromo(n1)) printf("É palíndromo\n"); else printf("Não é palíndromo\n"); char num2[6] = { '3', '6', '0', '9', '6', '3' }; char *n2 = num2; if (palindromo(n2)) printf("É palíndromo\n"); else printf("Não é palíndromo\n"); return 0; } int palindromo(char *n) { if (strlen(n) <= 1) return 1; char first = n[0], last = n[strlen(n)-1]; memmove(n, n+1, strlen(n)); n[strlen(n)-1] = 0; return (first == last) * palindromo(n); } ================================================ FILE: computer_science/algorithms/recursion/regua.c ================================================ #include void regua (int n) { if (n == 1) printf("-\n"); else { regua(n-1); int i; for (i=0; i #include int reverse(char *str); int main() { char str[7] = { 'l', 'e', 'a', 'n', 'd', 'r', 'o' }; char *name = str; reverse(name); return 0; } int reverse(char *str) { if (strlen(str) == 0) return 0; printf("%c", str[strlen(str)-1]); str[strlen(str)-1] = 0; return reverse(str); } ================================================ FILE: computer_science/algorithms/recursion/sum.py ================================================ def list_sum(list): if len(list) == 1: return list[0] else: return list[0] + list_sum(list[1:]) list = [1, 2, 3, 4, 5] print(list_sum(list)) list = [0, 1, 0, 0, 0] print(list_sum(list)) list = [1, 2, 1, 1, 10] print(list_sum(list)) ================================================ FILE: computer_science/algorithms/reverse-string/reverse-string-in-place.js ================================================ function reverseString(s) { let pointer1 = 0; let pointer2 = s.length - 1; let auxiliaryChar; while (pointer1 < pointer2) { auxiliaryChar = s[pointer1]; s[pointer1] = s[pointer2]; s[pointer2] = auxiliaryChar; pointer1++; pointer2--; } } ================================================ FILE: computer_science/algorithms/reverse-string/reverse-string.js ================================================ export function reverseString(s) { const arraysOfChars = []; for (let index = s.length - 1; index >= 0; index--) { arraysOfChars.push(s[index]); } return arraysOfChars.join(''); } ================================================ FILE: computer_science/algorithms/reverse-string/tests/reverse-string.test.js ================================================ import { it, test, expect } from 'vitest'; test('reverseString', () => { it('returns the reversed string', () => { expect(reverseString('asdfghjkl')).toEqual('lkjhgfdsa'); }); it('returns the reversed string', () => { expect(reverseString('lkjhgfdsa')).toEqual('asdfghjkl'); }); it('returns the reversed string', () => { expect(reverseString('')).toEqual(''); }); }); ================================================ FILE: computer_science/algorithms/search/binary_search.cpp ================================================ #include #include using namespace std; int binary_search(vector &v, int element) { int NOT_FOUND = -1; int low = 0, high = v.size()-1, mid; while (low <= high) { mid = (low + high) / 2; if (v[mid] < element) low = mid + 1; else if (v[mid] > element) high = mid -1; else return mid; } return NOT_FOUND; } int main() { int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; vector v(ar, ar + sizeof(ar) / sizeof(ar[0])); int element = binary_search(v, 7); cout << element << endl; return 0; } ================================================ FILE: computer_science/algorithms/search/binary_search.py ================================================ def binary_search(list, item): first_index = 0 last_index = len(list)-1 while first_index <= last_index: middle_index = (first_index + last_index) // 2 if item == list[middle_index]: return True elif item > list[middle_index]: first_index = middle_index + 1 else: last_index = middle_index - 1 return False list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(binary_search(list, 8)) print(binary_search(list, 0)) print(binary_search(list, 10)) print(binary_search(list, 89)) other_list = [0, 1, 2, 8, 13, 17, 19, 32, 42,] print(binary_search(other_list, 3)) print(binary_search(other_list, 13)) ================================================ FILE: computer_science/algorithms/search/recursive_binary_search.py ================================================ def binary_search(list, item): if len(list) == 0: return False middle_index = (len(list) - 1) // 2 if item == list[middle_index]: return True elif item > list[middle_index]: return binary_search(list[middle_index+1:], item) else: return binary_search(list[:middle_index-1], item) list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(binary_search(list, 8)) print(binary_search(list, 0)) print(binary_search(list, 10)) print(binary_search(list, 89)) other_list = [0, 1, 2, 8, 13, 17, 19, 32, 42,] print(binary_search(other_list, 3)) print(binary_search(other_list, 13)) ================================================ FILE: computer_science/algorithms/search/sequential_search.py ================================================ def sequential_search(list, item): for element in list: if element == item: return True return False list = [1, 2, 32, 8, 17, 19, 42, 13, 0] print(sequential_search(list, 3)) print(sequential_search(list, 13)) ================================================ FILE: computer_science/algorithms/segment-tree/sum/lazy_update.cpp ================================================ #include using namespace std; #define MAX_SIZE (1 << 20) int segtree[MAX_SIZE]; int lazy[MAX_SIZE]; void lazy_update(int p, int start, int end, int left, int right, int inc) { if (lazy[p] != 0) { segtree[p] = (end - start + 1) * lazy[p]; if (start != end) { lazy[p * 2] = lazy[p]; lazy[p * 2] = lazy[p]; } lazy[p] = 0; } if (end < left || start > right) return; // Totally out of range if (start >= left && end <= right) { // Totally in the range segtree[p] = (end - start + 1) * inc; if (start != end) { // Not a leaf lazy[p * 2] += inc; lazy[p * 2 + 1] += inc; } return; } // Partially in the range int middle = (start + end) / 2; lazy_update(p * 2, start, middle, left, right, inc); lazy_update(p * 2 + 1, middle + 1, end, left, right, inc); segtree[p] = segtree[p * 2] + segtree[p * 2 + 1]; } int main() { return 0; } ================================================ FILE: computer_science/algorithms/sorting/bubble_sort/bubble_sort.cpp ================================================ #include using namespace std; #define swap(a, b) { int x=a; a=b; b=x; } void bubble_sort(int v[], int n) { for (int i = 1; i <= n - 1; i++) { for (int j = 0; j < n - i; j++) { if (v[j] > v[j+1]) swap(v[j], v[j+1]); } } } int main() { int ar[] = { 33,23,10,9,1 }; for (int i = 0; i < 5; i++) cout << ar[i] << " "; cout << endl; bubble_sort(ar, 5); for (int i = 0; i < 5; i++) cout << ar[i] << " "; cout << endl; return 0; } ================================================ FILE: computer_science/algorithms/sorting/bubble_sort/bubble_sort.py ================================================ def bubble_sort(ar): for i in range(len(ar)): for k in range(i, len(ar)-1): if ar[k] > ar[k+1]: ar[k], ar[k+1] = ar[k+1], ar[k] ================================================ FILE: computer_science/algorithms/sorting/bubble_sort/test_bubble_sort.py ================================================ from bubble_sort import bubble_sort ar = [4, 2, 3, 10, 22, 11, 9] bubble_sort(ar) print(ar) ================================================ FILE: computer_science/algorithms/sorting/insertion_sort.cpp ================================================ #include using namespace std; void insertion_sort(int n, int array[]) { int x, j; for (int i = 1; i < n; i++) { x = array[i]; for (j = i - 1; j >= 0 && array[j] > x; j--) array[j+1] = array[j]; array[j+1] = x; } } int main() { int array[] = { 17, 3, 2, 10 }; insertion_sort(4, array); for (int i = 0; i < 4; i++) cout << array[i] << " "; return 0; } ================================================ FILE: computer_science/algorithms/sorting/merge_sort.cpp ================================================ #include #include using namespace std; vector merge(vector& vec, const vector& left, const vector& right) { vector result; unsigned left_it = 0, right_it = 0; while (left_it < left.size() && right_it < right.size()) { if (left[left_it] < right[right_it]) { result.push_back(left[left_it]); left_it++; } else { result.push_back(right[right_it]); right_it++; } } while (left_it < left.size()) { result.push_back(left[left_it]); left_it++; } while (right_it < right.size()) { result.push_back(right[right_it]); right_it++; } vec = result; return vec; } vector merge_sort(vector& vec) { if (vec.size() == 1) return vec; vector::iterator middle = vec.begin() + (vec.size() / 2); vector left(vec.begin(), middle); vector right(middle, vec.end()); left = merge_sort(left); right = merge_sort(right); return merge(vec, left, right); } int main() { vector v; v.push_back(2); v.push_back(3); v.push_back(6); v.push_back(4); v.push_back(5); v.push_back(8); v.push_back(7); v.push_back(1); merge_sort(v); for (int i = 0; i < v.size(); i++) cout << v[i] << " "; return 0; } ================================================ FILE: computer_science/algorithms/sorting/reverse_insertion_sort.cpp ================================================ #include using namespace std; void reverse_insertion_sort(int n, int array[]) { int x, j; for (int i = 1; i < n; i++) { x = array[i]; for (j = i - 1; j >= 0 && array[j] < x; j--) array[j+1] = array[j]; array[j+1] = x; } } int main() { int array[] = { 17, 3, 2, 10 }; reverse_insertion_sort(4, array); for (int i = 0; i < 4; i++) cout << array[i] << " "; return 0; } ================================================ FILE: computer_science/algorithms/sorting/selection_sort.cpp ================================================ #include using namespace std; #define swap(a, b) { int x=a; a=b; b=x; } void selection_sort(int v[], int n) { for (int i = 0; i < n - 1; i++) { int smaller_position = i; for (int j = i + 1; j < n; j++) if (v[j] < v[smaller_position]) smaller_position = j; if (smaller_position != i) swap(v[i], v[smaller_position]); } } int main() { int ar[] = { 33,23,10,9,1 }; for (int i = 0; i < 5; i++) cout << ar[i] << " "; cout << endl; selection_sort(ar, 5); for (int i = 0; i < 5; i++) cout << ar[i] << " "; cout << endl; return 0; } ================================================ FILE: computer_science/algorithms/sorting/string_insertion_sort.cpp ================================================ #include using namespace std; void insertion_sort(int n, char array[]) { int i, j; char x; for (i = 1; i < n; i++) { x = array[i]; for (j = i - 1; j >= 0 && array[j] - '0' > x - '0'; j--) array[j+1] = array[j]; array[j+1] = x; } } int main() { char array[] = { 'l', 'e', 'a', 'n', 'd', 'r', 'o' }; insertion_sort(7, array); for (int i = 0; i < 7; i++) cout << array[i]; return 0; } ================================================ FILE: computer_science/algorithms/string_to_int/string_to_int.cpp ================================================ #include #include #include using namespace std; int to_digit_test(char digit) { string numbers = "0123456789"; return numbers.find(digit); } int to_digit(char digit) { return digit - '0'; } int string_to_number(string n) { if (n == "") { return -1; } else { int num = 0; for (int i = 0; i < n.size(); i++) { num = num * 10 + to_digit(n[i]); } return num; } } int string_to_int(string n) { int num = 0, digit, pot = n.size()-1; for (int i = 0; i < n.size(); i++) { digit = n[i] - 48; num += pow(10, pot) * digit; pot--; } return num; } int main() { string n1 = "2", n2 = "33", n3 = "457", n4 = "1023", n5 = "54739"; cout << string_to_int(n1) << endl; cout << string_to_int(n2) << endl; cout << string_to_int(n3) << endl; cout << string_to_int(n4) << endl; cout << string_to_int(n5) << endl; return 0; } ================================================ FILE: computer_science/algorithms/subset/subset.js ================================================ function getAllSubsets(subset, nums, output, index) { if (index == nums.length) { subset.push(output); return; } getAllSubsets(subset, nums, [...output], index + 1); output.push(nums[index]); getAllSubsets(subset, nums, [...output], index + 1); } ================================================ FILE: computer_science/big_o/README.md ================================================ # Big O A generalize way to categorize an algorithm time and space based on input. - Growth based on input - Drop constants - Consider the worst case ## Big O complexity - O(1) - O(logn) - O(n) - O(nlogn) - O(n^2) - O(n!) ## Examples ### O(n) ```javascript function sumCharCodes(n) { let sum = 0; for (let i = 0; i < n.length; ++i) { sum += n.charCodeAt(i); } for (let i = 0; i < n.length; ++i) { sum += n.charCodeAt(i); } return sum; } ``` ### O(n^2) ```javascript function sumCharCodes(n) { let sum = 0; for (let i = 0; i < n.length; ++i) { for (let j = 0; j < n.length; ++j) { sum += charCode; } } return sum; } ``` ### O(n^3) ```javascript function sumCharCodes(n) { let sum = 0; for (let i = 0; i < n.length; ++i) { for (let j = 0; j < n.length; ++j) { for (let k = 0; k < n.length; ++k) { sum += charCode; } } } return sum; } ``` ================================================ FILE: computer_science/big_o/example1.py ================================================ def foo(array): sum = 0 product = 1 for element in array: sum += element for element in array: product *= element print("%d, %d" %(sum, product)) foo([1, 2, 3, 4, 5]) # The complexity of the foo function is: O(N) # Initializing sum and product = 1 + 1 = 2 # We iterate through the array two times = 2 * length(array) = 2 * N # Printing sum and product = 1 # Conclusion: O(2N + 3) = O(N) ================================================ FILE: computer_science/big_o/example10.py ================================================ from math import sqrt def is_prime(num): if num < 2: return False if num == 2: return True if num % 2 == 0: return False for i in range(3, int(sqrt(num)) + 1, 2): if num % i == 0: return False return True print(is_prime(1)) # False print(is_prime(2)) # True print(is_prime(9)) # False print(is_prime(17)) # True print(is_prime(24)) # False # is prime function has complexity of O(sqrt(N)) ================================================ FILE: computer_science/big_o/example11.py ================================================ def factorial(n): if n < 0: return -1 if n == 0: return 1 return n * factorial(n - 1) # factorial function has a complexity of O(N) ================================================ FILE: computer_science/big_o/example12.py ================================================ def permutation(str): handle_permutation(str, "") def handle_permutation(str, prefix): if len(str) == 0: print(prefix) else: for i in range(len(str)): rem = str[0:i] + str[i+1:] handle_permutation(rem, prefix + str[i]) permutation('abc') ================================================ FILE: computer_science/big_o/example13.py ================================================ def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2) print(fib(1)) print(fib(4)) print(fib(5)) print(fib(10)) ================================================ FILE: computer_science/big_o/example14.py ================================================ def all_fib(n): for i in range(n): print(fib(i)) def fib(n): if n == 0: return 0 if n == 1: return 1 return fib(n - 1) + fib(n - 2) all_fib(10) # Complexity: O(2 ^ (n+1)) ================================================ FILE: computer_science/big_o/example15.py ================================================ def all_fib(n): memo = [] memo.append(0) memo.append(1) for i in range(n): print("%d: %d" %(i, fib(i, memo))) def fib(n, memo): if n <= len(memo) - 1: return memo[n] memo.append(fib(n - 1, memo) + fib(n - 2, memo)) return memo[n] all_fib(7) # Complexity: O(N) # All previous actions are already computed ================================================ FILE: computer_science/big_o/example16.py ================================================ def powers_of_2(n): if n <= 0: return 0 if n == 1: print(1) return 1 previous = powers_of_2(n / 2) current = previous * 2 print(current) return current powers_of_2(4) # Complexity: O(log N) ================================================ FILE: computer_science/big_o/example17.py ================================================ def product(a, b): sum = 0 for i in range(b): sum += a return sum print(product(2, 4)) # Complexity: O(b) | O(N) ================================================ FILE: computer_science/big_o/example18.py ================================================ def power(a, b): if b < 0: return 0 elif b == 0: return 1 else: return a * power(a, b - 1) print(power(2, 2)) print(power(2, 10)) print(power(3, 2)) # Complexity: O(B) ================================================ FILE: computer_science/big_o/example19.py ================================================ def mod(a, b): if b > a: return a return mod(a - b, b) print(mod(10, 2)) print(mod(10, 3)) print(mod(10, 4)) print(mod(10, 5)) print(mod(10, 6)) # Complexity: O(a / b) def mod(a, b): if b <= 0: return -1 div = a / b return a - div * b # Complexity: O(1) ================================================ FILE: computer_science/big_o/example2.py ================================================ def print_pairs(array): for i in array: for j in array: print("%d, %d" %(i, j)) print_pairs([1, 2, 3, 4, 5]) # The complexity of the print_pairs function is: O(N^2) # We do a nested loop = length(array) ^ 2 = N * 2 # There are O(N^2) pairs # Conclusion: O(N^2) ================================================ FILE: computer_science/big_o/example20.py ================================================ def div(a, b): count = 0 sum = b while sum <= a: sum += b count += 1 return count print(div(10, 5)) print(div(10, 2)) print(div(10, 3)) print(div(10, 11)) # Complexity: O(a / b) ================================================ FILE: computer_science/big_o/example21.py ================================================ def sqrt(n): return sqrt_helper(n, 1, n) def sqrt_helper(n, min, max): if min > max: return -1 guess = (min + max) / 2 if guess * guess > n: return sqrt_helper(n, min, guess - 1) elif guess * guess < n: return sqrt_helper(n, guess + 1, max) else: return guess print(sqrt(100)) print(sqrt(9)) print(sqrt(25)) print(sqrt(3)) # Complexity: O(log N) --> It is a binary search algorithm ================================================ FILE: computer_science/big_o/example22.py ================================================ from math import sqrt def square_root(n): for guess in range(int(sqrt(n))+1): if guess * guess == n: return guess return -1 print(square_root(100)) print(square_root(9)) print(square_root(25)) print(square_root(3)) # Complexity: O(log N) --> It is a binary search algorithm ================================================ FILE: computer_science/big_o/example3.py ================================================ def print_unordered_pairs(array): for i in range(len(array)): for j in range(i+1, len(array)): print("%d, %d" %(array[i], array[j])) print_unordered_pairs([1, 2, 3, 4, 5]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array) * (length(array) - 1) / 2 = (length(array) * 2 - length(array)) / 2 = (N^2 - N) / 2 # There are O((N^2 - N) / 2) pairs # Conclusion: O(N^2) ================================================ FILE: computer_science/big_o/example4.py ================================================ def print_unordered_pairs(array_a, array_b): for a in array_a: for b in array_b: if a < b: print('%d, %d' %(a, b)) print_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array_a) * length(array_b) = N^2 # There are O(N^2) pairs # Conclusion: O(N^2) ================================================ FILE: computer_science/big_o/example5.py ================================================ def print_unordered_pairs(array_a, array_b): for a in array_a: for b in array_b: for i in range(1000000): print('%d, %d' %(a, b)) print_unordered_pairs([1, 2, 3, 4, 5], [3, 1, 2, 5, 4]) # The complexity of the print_unordered_pairs function is: O(N^2) # We do a nested loop = length(array_a) * length(array_b) * 1000000 = N^2 * 1000000 # There are O(N^2 * 1000000) pairs # Conclusion: O(N^2) ================================================ FILE: computer_science/big_o/example6.py ================================================ def reverse(array): for i in range(len(array) / 2): index = len(array) - i - 1 temporary_num = array[index] array[index] = array[i] array[i] = temporary_num return array new_array = reverse(list(range(1, 6)) for i in new_array: print(i) # The complexity of the reverse function is: O(N) # Even though we iterate only through half of the array (O(N/2)), we still consider this a O(N) complexity # Conclusion: O(N) ================================================ FILE: computer_science/big_o/example7.py ================================================ # O(N + P), if P < N / 2 --> O(N) # O(2N) --> O(N) # O(N + logN) --> O(N) # O(N + M), if N > M then O(N), otherwise O(M) ================================================ FILE: computer_science/big_o/example9.py ================================================ def sum(node): if node is None: return 0 return sum(node.left) + node.value + sum(node.right) # If we have N nodes in our tree, this will be O(N) complexity ================================================ FILE: computer_science/data_structures/array/array.cpp ================================================ #include using namespace std; int main() { int A[4]; // 4 bytes x 4 integers = 16 bytes A[0] = 0, A[1] = 1, A[2] = 2, A[3] = 3; cout << A << endl; // address of A array first element cout << *A << endl; // value of first element from A array | Same as A[0] return 0; } ================================================ FILE: computer_science/data_structures/array/big_o.py ================================================ # Array Big O complexity # Append (insert/push): O(1) - Constant Time # Pop (remove): O(1) - Constant Time # Sort: O(N log N) # Reverse: O(N) - Linear Time ================================================ FILE: computer_science/data_structures/array/list.py ================================================ a = [1, 2, 3, 4, 5] print(a) a.append(6) # O(1) print(a) a.append('hello') print(a) a.append([1, 2]) print(a) a.pop() # O(1) print(a) a.pop() print(a) print(a[0]) print(a[3]) a[2] = 33 # immutable sorting sorted_a = sorted(a) print(sorted_a) # in place sorting: O(N log N) a.sort() print(a) # in place reverse: O(N) a.reverse() print(a) # length of an array length = len(a) print(length) # min and max min = min(a) max = max(a) print(min) print(max) ================================================ FILE: computer_science/data_structures/array/vectors.cpp ================================================ #include #include #include #include using namespace std; // passing vector as reference void desc_sort(vector &v) { sort(v.begin(), v.end(), greater()); } // passing vector as pointer void desc_sort(vector *v) { sort(v->begin(), v->end(), greater()); } int main() { vector v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); v.push_back(10); for (int i = 0; i < v.size(); i++) cout << v[i] << endl; string arr[] = { "bla", "ble", "bli" }; vector v3(arr, arr + sizeof(arr) / sizeof(arr[0])); for (int i = 0; i < v3.size(); i++) cout << v3[i] << endl; int ar[] = { 1, 2, 3, 4, 5 }; vector v2(ar, ar + sizeof(ar) / sizeof(ar[0])); for (int i = 0; i < v2.size(); i++) cout << v2[i] << endl; cout << v.size() << endl; // remove last element v.pop_back(); // remove first element v.erase(v.begin()); // remove first element v.erase(v.begin()+0); // remove the last element using erase v.erase(v.begin() + v.size() - 1); for (int i = 0; i < v.size(); i++) cout << v[i] << endl; cout << v.size() << endl; // making a pair of integers in the vector vector< pair > pairs; pairs.push_back(make_pair(4, 1)); pairs.push_back(make_pair(3, 1)); pairs.push_back(make_pair(2, 1)); pairs.push_back(make_pair(5, 1)); pairs.push_back(make_pair(7, 1)); pairs.push_back(make_pair(2, 1)); pairs[0].first = 0; pairs.back().second++; // sort vector of pairs based on the first element sort(pairs.begin(), pairs.end()); for (int i = 0; i < pairs.size(); i++) cout << pairs[i].first << " " << pairs[i].second << endl; // sort from end to begin of the vector vector vetor; vetor.push_back(1); vetor.push_back(2); vetor.push_back(3); vetor.push_back(4); vetor.push_back(10); desc_sort(vetor); for (int i = 0; i < vetor.size(); i++) cout << vetor[i] << endl; vector vetorzin; vetorzin.push_back(1); vetorzin.push_back(2); vetorzin.push_back(3); vetorzin.push_back(4); vetorzin.push_back(10); desc_sort(&vetorzin); int removing = 0; vetorzin.erase(vetorzin.begin() + 1); removing++; vetorzin.erase(vetorzin.begin() + 2 - removing); for (int i = 0; i < vetorzin.size(); i++) cout << vetorzin[i] << endl; // implement reverse reverse(vetorzin.begin(), vetorzin.end()); // matrix vector< vector > matrix; vector v; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { v.push_back(i); } matrix.push_back(v); v.clear() } // iterators vector vec; vec.push_back(100); vec.push_back(99); vec.begin(); vec.end(); // capacity vec.size(); vec.empty(); // element access cout << vec[0] << endl; cout << vec[1] << endl; cout << vec.at(0) << endl; cout << vec.front() << endl; cout << vec.back() << endl; return 0; } ================================================ FILE: computer_science/data_structures/binary-heap/README.md ================================================ # Binary Heap - A complete binary tree (all levels have both the left and right children) - It's a min or max heap - Min heap: quickly get the minimum value of the tree - Root node holds the minimum value - Every child node needs to be greater than or equal to the parent node - Max heap: quickly get the maximum value of the tree - Root node holds the maximum value - Every child node needs to be smaller than or equal to the parent node ================================================ FILE: computer_science/data_structures/binary-heap/min-heap.js ================================================ export class MinHeap { constructor() { this.heap = []; } insert(value) { if (value != null) { this.heap.push(value); this.siftUp(this.heap.length - 1); return true; } return false; } extract() { if (this.isEmpty()) { return undefined; } if (this.size() === 1) { return this.heap.shift(); } const removedValue = this.heap.shift(); this.siftDown(0); return removedValue; } size() { return this.heap.length; } isEmpty() { return this.size() === 0; } findMinimum() { return this.isEmpty() ? undefined : this.heap[0]; } siftUp(index) { let parentIndex = this.getParentIndex(index); while (index > 0 && this.heap[index] < this.heap[parentIndex]) { this.swap(parentIndex, index); index = parentIndex; parentIndex = this.getParentIndex(index); } } siftDown(index) { let elementIndex = index; let leftIndex = this.getLeftIndex(index); let rightIndex = this.getRightIndex(index); let size = this.size(); if (leftIndex < size && this.heap[leftIndex] < this.heap[elementIndex]) { elementIndex = leftIndex; } if (rightIndex < size && this.heap[rightIndex] < this.heap[elementIndex]) { elementIndex = rightIndex; } if (index !== elementIndex) { this.swap(index, elementIndex); this.siftDown(elementIndex); } } swap(a, b) { const temp = this.heap[a]; this.heap[a] = this.heap[b]; this.heap[b] = temp; } getLeftIndex(index) { return 2 * index + 1; } getRightIndex(index) { return 2 * index + 2; } getParentIndex(index) { return index === 0 ? undefined : Math.floor((index - 1) / 2); } } ================================================ FILE: computer_science/data_structures/binary-heap/min-heap.test.js ================================================ import { describe, expect, it } from 'vitest'; import { MinHeap } from './min-heap'; describe('MinHeap', () => { it('findMinimum', () => { const heap = new MinHeap(); heap.insert(2); heap.insert(3); heap.insert(4); heap.insert(5); heap.insert(1); expect(heap.findMinimum()).toEqual(1); }); it('size', () => { const heap = new MinHeap(); for (let i = 1; i < 10; i++) { heap.insert(i); } expect(heap.size()).toEqual(9); }); it('integrate all methods', () => { const heap = new MinHeap(); expect(heap.isEmpty()).toEqual(true); heap.insert(2); heap.insert(3); heap.insert(4); heap.insert(5); heap.insert(1); expect(heap.isEmpty()).toEqual(false); expect(heap.size()).toEqual(5); expect(heap.findMinimum()).toEqual(1); expect(heap.extract()).toEqual(1); expect(heap.size()).toEqual(4); heap.insert(1); expect(heap.size()).toEqual(5); expect(heap.findMinimum()).toEqual(1); expect(heap.extract()).toEqual(1); expect(heap.extract()).toEqual(2); expect(heap.extract()).toEqual(3); expect(heap.extract()).toEqual(4); expect(heap.extract()).toEqual(5); expect(heap.size()).toEqual(0); expect(heap.isEmpty()).toEqual(true); }); }); ================================================ FILE: computer_science/data_structures/binary_search_tree/BinarySearchTree/index.js ================================================ import { Queue } from '../../queue/queue'; export class BinarySearchTree { constructor(value) { this.value = value; this.left = null; this.right = null; } insertLeft(value) { if (this.left) { const node = new BinarySearchTree(value); node.left = this.left; this.left = node; } else { this.left = new BinarySearchTree(value); } } insertRight(value) { if (this.right) { const node = new BinarySearchTree(value); node.right = this.right; this.right = node; } else { this.right = new BinarySearchTree(value); } } preOrder() { console.log(this.value); if (this.left) this.left.preOrder(); if (this.right) this.right.preOrder(); } inOrder() { if (this.left) this.left.inOrder(); console.log(this.value); if (this.right) this.right.inOrder(); } postOrder() { if (this.left) this.left.postOrder(); if (this.right) this.right.postOrder(); console.log(this.value); } bfs() { const queue = new Queue(); queue.enqueue(this); while (!queue.isEmpty()) { const node = queue.dequeue(); console.log(node.value); if (node.left) queue.enqueue(node.left); if (node.right) queue.enqueue(node.right); } } insertNode(value) { if (value <= this.value && this.left) { this.left.insertNode(value); } else if (value <= this.value) { this.left = new BinarySearchTree(value); } else if (value > this.value && this.right) { this.right.insertNode(value); } else { this.right = new BinarySearchTree(value); } } findNode(value) { if (value < this.value && this.left) { return this.left.findNode(value); } if (value > this.value && this.right) { return this.right.findNode(value); } return this.value === value; } removeNode(value, parent) { if (value < this.value && this.left) { return this.left.removeNode(value, this); } if (value < this.value) { return false; } if (value > this.value && this.right) { return this.right.removeNode(value, this); } if (value > this.value) { return false; } if (this.left === null && this.right === null && this == parent.left) { parent.left = null; this.clearNode(); return true; } if (this.left === null && this.right === null && this == parent.right) { parent.right = null; this.clearNode(); return true; } if (this.left && this.right === null && this == parent.left) { parent.left = this.left; this.clearNode(); return true; } if (this.left && this.right === null && this == parent.right) { parent.right = this.left; this.clearNode(); return true; } if (this.right && this.left === null && this == parent.left) { parent.left = this.right; this.clearNode(); return true; } if (this.right && this.left === null && this == parent.right) { parent.right = this.right; this.clearNode(); return true; } this.value = this.right.findMinimumValue(); this.right.removeNode(this.value, this); return true; } clearNode() { this.value = null; this.left = null; this.right = null; } findMinimumValue() { if (this.left) return this.left.findMinimumValue(); return this.value; } } ================================================ FILE: computer_science/data_structures/binary_search_tree/BinarySearchTree/index.test.js ================================================ import { describe, expect, it } from 'vitest'; import { BinarySearchTree } from '.'; function buildBST() { const tree = new BinarySearchTree(50); tree.insertNode(21); tree.insertNode(4); tree.insertNode(32); tree.insertNode(76); tree.insertNode(64); tree.insertNode(52); tree.insertNode(100); return tree; } describe('BinarySearchTree', () => { it('instantiates a BinarySearchTree', () => { const tree = new BinarySearchTree('a'); expect(tree.value).toEqual('a'); expect(tree.right).toEqual(null); expect(tree.left).toEqual(null); }); describe('inserts a left node', () => { it('with a left child', () => { const tree = new BinarySearchTree('a'); tree.left = new BinarySearchTree('b'); tree.insertLeft('c'); expect(tree.left.value).toEqual('c'); expect(tree.left.left.value).toEqual('b'); }); it('without a left child', () => { const tree = new BinarySearchTree('a'); tree.insertLeft('b'); expect(tree.left.value).toEqual('b'); }); }); describe('inserts a right node', () => { it('with a right child', () => { const tree = new BinarySearchTree('a'); tree.right = new BinarySearchTree('b'); tree.insertRight('c'); expect(tree.right.value).toEqual('c'); expect(tree.right.right.value).toEqual('b'); }); it('without a right child', () => { const tree = new BinarySearchTree('a'); tree.insertRight('b'); expect(tree.right.value).toEqual('b'); }); }); describe('traversal', () => { const root = new BinarySearchTree(1); const two = new BinarySearchTree(2); const three = new BinarySearchTree(3); const four = new BinarySearchTree(4); const five = new BinarySearchTree(5); const six = new BinarySearchTree(6); const seven = new BinarySearchTree(7); two.left = three; two.right = four; five.left = six; five.right = seven; root.left = two; root.right = five; it('traverses in pre order', () => { console.log('====== pre order ======'); root.preOrder(); console.log('====== // ======'); }); it('traverses in order', () => { console.log('====== in order ======'); root.inOrder(); console.log('====== // ======'); }); it('traverses in post order', () => { console.log('====== post order ======'); root.postOrder(); console.log('====== // ======'); }); it('traverses via breadth first search', () => { console.log('====== bfs ======'); root.bfs(); console.log('====== // ======'); }); }); it('inserts nodes to the BST', () => { const tree = buildBST(); expect(tree.value).toEqual(50); expect(tree.left.value).toEqual(21); expect(tree.left.left.value).toEqual(4); expect(tree.left.right.value).toEqual(32); expect(tree.right.value).toEqual(76); expect(tree.right.left.value).toEqual(64); expect(tree.right.left.left.value).toEqual(52); expect(tree.right.right.value).toEqual(100); }); describe('findNode', () => { it('finds the node in the tree', () => { const tree = buildBST(); expect(tree.findNode(50)).toEqual(true); expect(tree.findNode(21)).toEqual(true); expect(tree.findNode(4)).toEqual(true); expect(tree.findNode(32)).toEqual(true); expect(tree.findNode(76)).toEqual(true); expect(tree.findNode(64)).toEqual(true); expect(tree.findNode(52)).toEqual(true); expect(tree.findNode(100)).toEqual(true); expect(tree.findNode(0)).toEqual(false); expect(tree.findNode(999)).toEqual(false); }); }); describe('removeNode', () => { it('removes a node in the tree', () => { const tree = buildBST(); expect(tree.findNode(4)).toEqual(true); expect(tree.removeNode(4)).toEqual(true); expect(tree.findNode(4)).toEqual(false); }); it('removes a node in the middle of the left subtree', () => { const tree = buildBST(); expect(tree.findNode(21)).toEqual(true); expect(tree.removeNode(21)).toEqual(true); expect(tree.findNode(21)).toEqual(false); expect(tree.value).toEqual(50); expect(tree.left.value).toEqual(32); expect(tree.left.left.value).toEqual(4); expect(tree.right.value).toEqual(76); expect(tree.right.left.value).toEqual(64); expect(tree.right.left.left.value).toEqual(52); expect(tree.right.right.value).toEqual(100); }); it('removes a node in the middle of the right subtree', () => { const tree = buildBST(); expect(tree.findNode(76)).toEqual(true); expect(tree.removeNode(76)).toEqual(true); expect(tree.findNode(76)).toEqual(false); expect(tree.value).toEqual(50); expect(tree.left.value).toEqual(21); expect(tree.left.left.value).toEqual(4); expect(tree.left.right.value).toEqual(32); expect(tree.right.value).toEqual(100); expect(tree.right.left.value).toEqual(64); expect(tree.right.left.left.value).toEqual(52); }); it('removes the root node', () => { const tree = buildBST(); expect(tree.findNode(50)).toEqual(true); expect(tree.removeNode(50)).toEqual(true); expect(tree.findNode(50)).toEqual(false); expect(tree.value).toEqual(52); expect(tree.left.value).toEqual(21); expect(tree.left.left.value).toEqual(4); expect(tree.left.right.value).toEqual(32); expect(tree.right.value).toEqual(76); expect(tree.right.right.value).toEqual(100); expect(tree.right.left.value).toEqual(64); }); }); }); ================================================ FILE: computer_science/data_structures/binary_search_tree/big_o.py ================================================ # insert: O(log(N)) - Logarithmic Time # find / search: O(log(N)) - Logarithmic Time # traversal: O(N) - Linear Time ================================================ FILE: computer_science/data_structures/binary_search_tree/binary_search_tree.py ================================================ from queue import Queue class Node: def __init__(self, value): self.value = value self.left_child = None self.right_child = None class BinarySearchTree: def __init__(self): self.root = None def insert(self, value): if self.root: self.insert_node(self.root, value) else: self.root = Node(value) def insert_node(self, current_node, value): if value <= current_node.value and current_node.left_child: self.insert_node(current_node.left_child, value) elif value <= current_node.value: current_node.left_child = Node(value) elif current_node.right_child: self.insert_node(current_node.right_child, value) else: current_node.right_child = Node(value) def find(self, value): return self.find_node(self.root, value) def find_node(self, current_node, value): if value < current_node.value and current_node.left_child: return self.find_node(current_node.left_child, value) if value > current_node.value and current_node.right_child: return self.find_node(current_node.right_child, value) return value == current_node.value def pre_order(self): if self.root: self.pre_order_traversal(self.root) else: print('Tree empty') def pre_order_traversal(self, current_node): print(current_node.value) if current_node.left_child: self.pre_order_traversal(current_node.left_child) if current_node.right_child: self.pre_order_traversal(current_node.right_child) def in_order(self): if self.root: self.in_order_traversal(self.root) else: print('Tree empty') def in_order_traversal(self, current_node): if current_node.left_child: self.in_order_traversal(current_node.left_child) print(current_node.value) if current_node.right_child: self.in_order_traversal(current_node.right_child) def post_order(self): if self.root: self.post_order_traversal(self.root) else: print('Tree empty') def post_order_traversal(self, current_node): if current_node.left_child: self.post_order_traversal(current_node.left_child) if current_node.right_child: self.post_order_traversal(current_node.right_child) print(current_node.value) def bfs(self): queue = Queue() queue.put(self.root) while not queue.empty(): current_node = queue.get() print(current_node.value) if current_node.left_child: queue.put(current_node.left_child) if current_node.right_child: queue.put(current_node.right_child) ================================================ FILE: computer_science/data_structures/binary_search_tree/test_binary_search_tree.py ================================================ from binary_search_tree import * bst = BinarySearchTree() bst.insert(15) bst.insert(10) bst.insert(8) bst.insert(12) bst.insert(20) bst.insert(17) bst.insert(25) bst.insert(19) print('Find 15') print(bst.find(15)) print('Find 10') print(bst.find(10)) print('Find 8') print(bst.find(8)) print('Find 12') print(bst.find(12)) print('Find 20') print(bst.find(20)) print('Find 17') print(bst.find(17)) print('Find 25') print(bst.find(25)) print('Find 19') print(bst.find(19)) print('Find 0') print(bst.find(0)) print() print('Pre Order') bst.pre_order() print() print('In Order') bst.in_order() print() print('Post Order') bst.post_order() print() print('BFS') bst.bfs() ================================================ FILE: computer_science/data_structures/binary_search_tree/test_node.py ================================================ from binary_search_tree import Node node = Node(1) print(node.get()) node.set(2) print(node.get()) ================================================ FILE: computer_science/data_structures/binary_search_tree_without_node/binary_search_tree.py ================================================ class BinarySearchTree: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def insert_node(self, value): if value <= self.value and self.left_child: self.left_child.insert_node(value) elif value <= self.value: self.left_child = BinarySearchTree(value) elif value > self.value and self.right_child: self.right_child.insert_node(value) else: self.right_child = BinarySearchTree(value) def find_node(self, value): if value < self.value and self.left_child: return self.left_child.find_node(value) if value > self.value and self.right_child: return self.right_child.find_node(value) return value == self.value def remove_node(self, value, parent): if value < self.value and self.left_child: return self.left_child.remove_node(value, self) elif value < self.value: return False elif value > self.value and self.right_child: return self.right_child.remove_node(value, self) elif value > self.value: return False else: if self.left_child is None and self.right_child is None and self == parent.left_child: parent.left_child = None self.clear_node() elif self.left_child is None and self.right_child is None and self == parent.right_child: parent.right_child = None self.clear_node() elif self.left_child and self.right_child is None and self == parent.left_child: parent.left_child = self.left_child self.clear_node() elif self.left_child and self.right_child is None and self == parent.right_child: parent.right_child = self.left_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.left_child: parent.left_child = self.right_child self.clear_node() elif self.right_child and self.left_child is None and self == parent.right_child: parent.right_child = self.right_child self.clear_node() else: self.value = self.right_child.find_minimum_value() self.right_child.remove_node(self.value, self) return True def clear_node(self): self.value = None self.left_child = None self.right_child = None def find_minimum_value(self): if self.left_child: return self.left_child.find_minimum_value() else: return self.value def pre_order_traversal(self): print(self.value) if self.left_child: self.left_child.pre_order_traversal() if self.right_child: self.right_child.pre_order_traversal() def in_order_traversal(self): if self.left_child: self.left_child.in_order_traversal() print(self.value) if self.right_child: self.right_child.in_order_traversal() def post_order_traversal(self): if self.left_child: self.left_child.post_order_traversal() if self.right_child: self.right_child.post_order_traversal() print(self.value) ================================================ FILE: computer_science/data_structures/binary_search_tree_without_node/test_binary_search_tree.py ================================================ from binary_search_tree import * bst = BinarySearchTree(15) bst.insert_node(10) bst.insert_node(8) bst.insert_node(12) bst.insert_node(20) bst.insert_node(17) bst.insert_node(25) bst.insert_node(19) print(bst.find_node(15)) # True print(bst.find_node(10)) # True print(bst.find_node(8)) # True print(bst.find_node(12)) # True print(bst.find_node(20)) # True print(bst.find_node(17)) # True print(bst.find_node(25)) # True print(bst.find_node(19)) # True print(bst.find_node(0)) # False print print(bst.find_minimum_value()) print bst.pre_order_traversal() print bst.in_order_traversal() print bst.post_order_traversal() print print(bst.remove_node(8, None)) print bst.pre_order_traversal() print print(bst.remove_node(17, None)) print bst.pre_order_traversal() print print(bst.remove_node(15, None)) print bst.pre_order_traversal() print print(bst.remove_node(20, None)) print bst.pre_order_traversal() ================================================ FILE: computer_science/data_structures/binary_tree/BinaryTree/index.js ================================================ import { Queue } from '../../queue/queue'; export class BinaryTree { constructor(value) { this.value = value; this.left = null; this.right = null; } insertLeft(value) { if (this.left) { const node = new BinaryTree(value); node.left = this.left; this.left = node; } else { this.left = new BinaryTree(value); } } insertRight(value) { if (this.right) { const node = new BinaryTree(value); node.right = this.right; this.right = node; } else { this.right = new BinaryTree(value); } } preOrder() { console.log(this.value); if (this.left) this.left.preOrder(); if (this.right) this.right.preOrder(); } inOrder() { if (this.left) this.left.inOrder(); console.log(this.value); if (this.right) this.right.inOrder(); } postOrder() { if (this.left) this.left.postOrder(); if (this.right) this.right.postOrder(); console.log(this.value); } bfs() { const queue = new Queue(); queue.enqueue(this); while (!queue.isEmpty()) { const node = queue.dequeue(); console.log(node.value); if (node.left) queue.enqueue(node.left); if (node.right) queue.enqueue(node.right); } } } ================================================ FILE: computer_science/data_structures/binary_tree/BinaryTree/index.test.js ================================================ import { describe, expect, it } from 'vitest'; import { BinaryTree } from '.'; describe('BinaryTree', () => { it('instantiates a BinaryTree', () => { const tree = new BinaryTree('a'); expect(tree.value).toEqual('a'); expect(tree.right).toEqual(null); expect(tree.left).toEqual(null); }); describe('inserts a left node', () => { it('with a left child', () => { const tree = new BinaryTree('a'); tree.left = new BinaryTree('b'); tree.insertLeft('c'); expect(tree.left.value).toEqual('c'); expect(tree.left.left.value).toEqual('b'); }); it('without a left child', () => { const tree = new BinaryTree('a'); tree.insertLeft('b'); expect(tree.left.value).toEqual('b'); }); }); describe('inserts a right node', () => { it('with a right child', () => { const tree = new BinaryTree('a'); tree.right = new BinaryTree('b'); tree.insertRight('c'); expect(tree.right.value).toEqual('c'); expect(tree.right.right.value).toEqual('b'); }); it('without a right child', () => { const tree = new BinaryTree('a'); tree.insertRight('b'); expect(tree.right.value).toEqual('b'); }); }); describe('traversal', () => { const root = new BinaryTree(1); const two = new BinaryTree(2); const three = new BinaryTree(3); const four = new BinaryTree(4); const five = new BinaryTree(5); const six = new BinaryTree(6); const seven = new BinaryTree(7); two.left = three; two.right = four; five.left = six; five.right = seven; root.left = two; root.right = five; it('traverses in pre order', () => { console.log('====== pre order ======'); root.preOrder(); console.log('====== // ======'); }); it('traverses in order', () => { console.log('====== in order ======'); root.inOrder(); console.log('====== // ======'); }); it('traverses in post order', () => { console.log('====== post order ======'); root.postOrder(); console.log('====== // ======'); }); it('traverses via breadth first search', () => { console.log('====== bfs ======'); root.bfs(); console.log('====== // ======'); }); }); }); ================================================ FILE: computer_science/data_structures/binary_tree/big_o.py ================================================ # Binary Tree: Big O Complexity # Search: O(log N) - Logarithmic Time # Insert: O(log N) - Logarithmic Time # Delete: O(log N) - Logarithmic Time # Traversal: O(N) - Linear Time ================================================ FILE: computer_science/data_structures/binary_tree/binary_tree.py ================================================ from queue import Queue class BinaryTree: def __init__(self, value): self.value = value self.left_child = None self.right_child = None def insert_left(self, value): if self.left_child: self.left_child.insert_left(value) else: self.left_child = BinaryTree(value) def insert_right(self, value): if self.right_child: self.right_child.insert_right(value) else: self.right_child = BinaryTree(value) def pre_order(self): print(self.value) if self.left_child: self.left_child.pre_order() if self.right_child: self.right_child.pre_order() def post_order(self): if self.left_child: self.left_child.post_order() if self.right_child: self.right_child.post_order() print(self.value) def in_order(self): if self.left_child: self.left_child.in_order() print(self.value) if self.right_child: self.right_child.in_order() def bfs(self): queue = Queue() queue.put(self) while not queue.empty(): current_node = queue.get() print(current_node.value) if current_node.left_child: queue.put(current_node.left_child) if current_node.right_child: queue.put(current_node.right_child) ================================================ FILE: computer_science/data_structures/binary_tree/test_binary_tree.py ================================================ from binary_tree import BinaryTree a_node = BinaryTree('a') a_node.insert_left('b') a_node.insert_right('c') b_node = a_node.left_child b_node.insert_right('d') c_node = a_node.right_child c_node.insert_left('e') c_node.insert_right('f') d_node = b_node.right_child e_node = c_node.left_child f_node = c_node.right_child a = a_node.value b = b_node.value c = c_node.value d = d_node.value e = e_node.value f = f_node.value print print('---------------------------------------') print print(" |%s|" % (a)) print(" / \\") print(" |%s| |%s|" % (b, c)) print(" \\ / \\") print(" |%s| |%s| |%s|" % (d, e, f)) # ------- Building this Tree ------- # # |a| # / \ # |b| |c| # \ / \ # |d| |e| |f| print print('---------------------------------------') print tree = a_node print('Depth First: Pre Order') print tree.pre_order() print print print('---------------------------------------') print print('Depth First: Post Order') print tree.post_order() print print print('---------------------------------------') print print('Depth First: In Order') print tree.in_order() print print print('---------------------------------------') print print('Breadth First Search') print tree.bfs() print ================================================ FILE: computer_science/data_structures/graph/AdjacentListGraph/AdjacentListGraph.js ================================================ export function addNode(AdjacentListGraph, key) { AdjacentListGraph.set(key, []); } export function addEdge(AdjacentListGraph, origin, destination) { AdjacentListGraph.get(origin).push(destination); AdjacentListGraph.get(destination).push(origin); } export function bfs(AdjacentListGraph, vertex) { const visitedVertices = new Set(); const queue = [vertex]; while (queue.length) { const origin = queue.shift(); const destinations = AdjacentListGraph.get(origin); for (let destination of destinations) { if (!visitedVertices.has(destination)) { visitedVertices.add(destination); queue.push(destination); } } } } export function dfs(AdjacentListGraph, vertex, visitedVertices = new Set()) { const destinations = AdjacentListGraph.get(vertex); visitedVertices.add(vertex); for (let destination of destinations) { if (!visitedVertices.has(destination)) { dfs(AdjacentListGraph, destination, visitedVertices); } } } ================================================ FILE: computer_science/data_structures/graph/AdjacentListGraph/example.js ================================================ import { addNode, addEdge, bfs, dfs } from './AdjacentListGraph.js'; const airports = [ 'PHX', 'BKK', 'JFK', 'LIM', 'MEX', 'OKC', 'LAX', 'EZE', 'HEL', 'LOS', 'LA', ]; const routes = [ ['PHX', 'LA'], ['PHX', 'JFK'], ['JFK', 'OKC'], ['JFK', 'LOS'], ['JFK', 'HEL'], ['MEX', 'LA'], ['MEX', 'BKK'], ['MEX', 'LIM'], ['MEX', 'EZE'], ['LIM', 'BKK'], ]; const AdjacentListGraph = new Map(); for (let airport of airports) { addNode(AdjacentListGraph, airport); } for (let [origin, destination] of routes) { addEdge(AdjacentListGraph, origin, destination); } bfs(AdjacentListGraph, 'PHX'); dfs(AdjacentListGraph, 'PHX'); ================================================ FILE: computer_science/data_structures/graph/README.md ================================================ # Graph ## Breadth First Search (BFS) - Use the queue data structure to hold each vertex that needs to be visited in the future. - It should keep a visited data structure to store all the visited vertices. - Runtime: O(V+E) / V = vertices | E = edges. ## Depth First Search (DFS) - Use the stack data structure or do recursive. - It should keep a visited data structure to store all the visited vertices. - Runtime: O(V+E) / V = vertices | E = edges. ================================================ FILE: computer_science/data_structures/graph/adjacency_list.cpp ================================================ #include using namespace std; typedef pair pii; typedef vector vii; typedef vector vi; #define pb push_back int main() { vector AdjList; vii vectorOfPairs; vectorOfPairs.pb(make_pair(1, 50)); // Vertice 0 connected with vertice 1 and weight 50 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(0, 50)); // Vertice 0 connected with vertice 1 and weight 50 vectorOfPairs.pb(make_pair(2, 20)); // Vertice 1 connected with vertice 2 and weight 20 vectorOfPairs.pb(make_pair(3, 30)); // Vertice 1 connected with vertice 3 and weight 30 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(1, 20)); // Vertice 2 connected with vertice 1 and weight 20 vectorOfPairs.pb(make_pair(3, 40)); // Vertice 2 connected with vertice 3 and weight 40 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(1, 30)); // Vertice 3 connected with vertice 1 and weight 30 vectorOfPairs.pb(make_pair(2, 40)); // Vertice 2 connected with vertice 3 and weight 40 vectorOfPairs.pb(make_pair(4, 60)); // Vertice 3 connected with vertice 4 and weight 60 AdjList.pb(vectorOfPairs); vectorOfPairs.clear(); vectorOfPairs.pb(make_pair(3, 60)); // Vertice 4 connected with vertice 3 and weight 60 AdjList.pb(vectorOfPairs); for (int i = 0; i < AdjList.size(); i++) { for (int j = 0; j < AdjList[i].size(); j++) { cout << "Vertice: " << i; cout << " connected with vertice " << AdjList[i][j].first; cout << " with weight " << AdjList[i][j].second << endl; } cout << endl; } return 0; } ================================================ FILE: computer_science/data_structures/graph/graph.js ================================================ class Vertex { constructor(key) { this.key = key; this.adjacent = []; } contains(key) { for (let vertex of this.adjacent) { if (vertex.key === key) { return true; } } return false; } } class Graph { constructor() { this.vertices = []; } addVertex(key) { if (this.contains(key)) { console.log(`Vertex ${key} not added because it's an existent key`); return; } this.vertices.push(new Vertex(key)); } contains(key) { for (let vertex of this.vertices) { if (vertex.key === key) { return true; } } return false; } addEdge(from, to) { let fromVertex = this.getVertex(from); let toVertex = this.getVertex(to); if (!fromVertex) { console.log(`Vertex ${from} doesn't exist in the graph`); return; } if (!toVertex) { console.log(`Vertex ${to} doesn't exist in the graph`); return; } if (fromVertex.contains(to)) { console.log(`Existing edge: ${from} --> ${to}`); return; } fromVertex.adjacent.push(toVertex); } getVertex(key) { for (let vertex of this.vertices) { if (vertex.key === key) { return vertex; } } } print() { for (let vertex of this.vertices) { let adjacent = vertex.adjacent.reduce( (verticesString, vertex) => `${verticesString} ${vertex.key}`, '' ); console.log(`Vertice ${vertex.key}: ${adjacent}`); } } } const graph = new Graph(); graph.addVertex(0); for (let i = 1; i <= 4; i++) { graph.addVertex(i); } graph.addVertex(0); graph.addVertex(0); graph.addEdge(1, 2); graph.addEdge(1, 3); graph.addEdge(2, 3); graph.addEdge(2, 4); graph.addEdge(1, 2); graph.addEdge(6, 2); graph.addEdge(3, 2); graph.addEdge(1, 1); console.log(); graph.print(); ================================================ FILE: computer_science/data_structures/graph/graph.py ================================================ class Graph: def __init__(self): self.vertices = [] def add_vertex(self, key): if self.contains(self.vertices, key): print("Vertex", key, "not added because it is an existing key") else: self.vertices.append(Vertex(key)) def print(self): for vertex in self.vertices: print("Vertex", vertex.key) for neighbor in vertex.adjacent: print(neighbor.key) def add_edge(self, from_key, to_key): from_vertex = self.get_vertex(from_key) to_vertex = self.get_vertex(to_key) if from_vertex is None or to_vertex is None: print("Invalid edge (", from_key, "-->", to_key, ")") return if self.contains(from_vertex.adjacent, to_key): print("Edge", to_key, "not added because it is already an existing neighbor") return from_vertex.adjacent.append(to_vertex) def get_vertex(self, key): for vertex in self.vertices: if vertex.key == key: return vertex def contains(self, vertices, key): for vertex in vertices: if vertex.key == key: return True return False class Vertex: def __init__(self, key): self.key = key self.adjacent = [] ================================================ FILE: computer_science/data_structures/graph/test_graph.py ================================================ from graph import * g = Graph() for i in range(5): g.add_vertex(i) g.add_edge(1, 2) g.add_edge(1, 3) g.add_edge(2, 3) g.add_edge(2, 4) g.add_edge(1, 2) g.add_edge(6, 2) g.add_edge(3, 2) g.add_edge(1, 1) g.print() ================================================ FILE: computer_science/data_structures/hash_table/big_o.py ================================================ # Hash Table / Dictionaty Big O complexity # Insert: O(1) - Constant Time # Search: O(1) - Constant Time # Delete: O(1) - Constant Time ================================================ FILE: computer_science/data_structures/hash_table/dictionary.py ================================================ d1 = {} d2 = dict() d3 = { 'something': 10, 'other_thing': 11 } print(d3['something']) d1[1] = 1 d1[2] = 2 d1[3] = 3 d1[4] = 4 for key, value in d1.items(): print('key: %d | value: %d' %(key, value)) d1[2] = -2 print(d1[2]) ================================================ FILE: computer_science/data_structures/hash_table/maps.cpp ================================================ #include #include #include using namespace std; int main() { map m; m["one"] = 1; m["two"] = 2; m["three"] = 3; int one_plus_two = m["one"] + m["two"]; cout << one_plus_two << endl; int total = 0; for (map::iterator it = m.begin(); it != m.end(); ++it) total += it->second; cout << total << endl; if (m.find("two") != m.end()) m.erase(m.find("two")); total = 0; for (map::iterator it = m.begin(); it != m.end(); ++it) total += it->second; cout << total << endl; if (m.find("one") != m.end()) { cout << m.find("one")->first << endl; m.find("one")->second++; cout << m.find("one")->second << endl; } return 0; } ================================================ FILE: computer_science/data_structures/linked_list/big-o.js ================================================ /*** === Linked List Big O complexity === Push Front: O(1) - Constant Time Push Back: O(N) - Linear Time If it has the tail: O(1) - Constant Time Push in the middle: O(N) - Linear Time Remove: O(N) - Linear Time Remove of head or tail: O(1) - Constant Time Is Empty: O(1) - Constant Time Size: O(N) - Linear Time Search: O(N) - Linear Time Get head or tail: O(1) - Constant Time ***/ ================================================ FILE: computer_science/data_structures/linked_list/big_o.py ================================================ # Linked List Big O complexity # Push Front: O(1) - Constant Time # Push Back: O(N) - Linear Time # Remove: O(N) - Linear Time # Is Empty: O(1) - Constant Time # Size: O(N) - Linear Time # Search: O(N) - Linear Time ================================================ FILE: computer_science/data_structures/linked_list/linked-list.js ================================================ export class Node { constructor(value, next = null) { this.value = value; this.next = next; } } export class LinkedList { constructor() { this.head = null; } pushFront(value) { this.head = new Node(value, this.head); } pushBack(value) { if (this.isEmpty()) { this.head = new Node(value); return; } let currentNode = this.head; while (currentNode && currentNode.next) { currentNode = currentNode.next; } currentNode.next = new Node(value); } size() { let count = 0; let currentNode = this.head; while (currentNode) { count += 1; currentNode = currentNode.next; } return count; } search(value) { let currentNode = this.head; while (currentNode && currentNode.value !== value) { currentNode = currentNode.next; } return Boolean(currentNode); } remove(value) { if (this.isEmpty()) { return; } if (this.head.value === value) { this.head = this.head.next; return; } let currentNode = this.head; while (currentNode.next) { if (currentNode.next.value === value) { currentNode.next = currentNode.next.next; return; } currentNode = currentNode.next; } } isEmpty() { return this.head === null; } } ================================================ FILE: computer_science/data_structures/linked_list/linked_list.py ================================================ class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def is_empty(self): return self.head == None def push_front(self, data): new_node = Node(data) new_node.next = self.head self.head = new_node def push_back(self, data): new_node = Node(data) current_node = self.head while current_node.next: current_node = current_node.next current_node.next = new_node def size(self): current_node = self.head count = 0 while current_node: count += 1 current_node = current_node.next return count def search(self, item): current_node = self.head while current_node and not current_node.data == item: current_node = current_node.next return current_node != None and current_node.data == item def remove(self, item): if self.head == None: print('List is empty') return current_node = self.head previous_node = None while current_node and current_node.data != item: previous_node = current_node current_node = current_node.next if previous_node == None: self.head = current_node.next else: previous_node.next = current_node.next ================================================ FILE: computer_science/data_structures/linked_list/test_linked_list.py ================================================ from linked_list import * print('--- Instantiate Linked List ---') linked_list = LinkedList() print(linked_list) print('--- Push Front & Size ---') linked_list.push_front(10) linked_list.push_front(9) linked_list.push_front(8) print("Current size: %i" %(linked_list.size())) print('--- Push Back ---') linked_list.push_back(11) print("Current size: %i" %(linked_list.size())) print('--- Printing all nodes data ---') current_node = linked_list.head while current_node: print(current_node.data) current_node = current_node.next print('--- Searching ---') print(linked_list.search(10)) print(linked_list.search(0)) print('--- Removing ---') print("Size: %i" %(linked_list.size())) print("Searching for 10 - Found: %r" %(linked_list.search(10))) print('Removing 10') linked_list.remove(10) print("Size: %i" %(linked_list.size())) print("Searching for 10 - Found: %r" %(linked_list.search(10))) print('Removing 9, 8, and 11') linked_list.remove(11) linked_list.remove(8) linked_list.remove(9) print("Size: %i" %(linked_list.size())) print('Trying to remove item from empty list') linked_list.remove(0) ================================================ FILE: computer_science/data_structures/linked_list/test_node.py ================================================ from linked_list import Node node = Node(9) print(node) print(node.get_data()) node.set_data(10) print(node.get_data()) print("------------") print(node.get_next()) other_node = Node(0) node.set_next(other_node) print(node.get_next()) print(node.get_next().get_data()) ================================================ FILE: computer_science/data_structures/linked_list/tests/linked-list.test.js ================================================ import { describe, expect, it } from 'vitest'; import { LinkedList, Node } from '../linked-list'; describe('LinkedList', () => { it('verifies linked list behavior', () => { const linkedList = new LinkedList(); expect(linkedList.isEmpty()).toBeTruthy(); expect(linkedList.size()).toEqual(0); linkedList.pushFront(1); expect(linkedList.isEmpty()).toBeFalsy(); expect(linkedList.size()).toEqual(1); expect(linkedList.head).toEqual(new Node(1)); linkedList.pushBack(2); linkedList.pushBack(3); linkedList.pushBack(4); expect(linkedList.size()).toEqual(4); linkedList.pushFront(0); expect(linkedList.size()).toEqual(5); expect(linkedList.search(0)).toBeTruthy(); expect(linkedList.search(1)).toBeTruthy(); expect(linkedList.search(2)).toBeTruthy(); expect(linkedList.search(3)).toBeTruthy(); expect(linkedList.search(4)).toBeTruthy(); expect(linkedList.search(5)).toBeFalsy(); linkedList.remove(5); expect(linkedList.size()).toEqual(5); linkedList.remove(0); expect(linkedList.size()).toEqual(4); linkedList.remove(4); expect(linkedList.size()).toEqual(3); linkedList.remove(2); expect(linkedList.size()).toEqual(2); linkedList.remove(1); expect(linkedList.size()).toEqual(1); linkedList.remove(3); expect(linkedList.size()).toEqual(0); expect(linkedList.isEmpty()).toBeTruthy(); }); }); ================================================ FILE: computer_science/data_structures/queue/big_o.py ================================================ # Queue Big O complexity # Enqueue (push): O(1) - Constant Time # Dequeue (remove): O(1) - Constant Time # Front: O(1) - Constant Time # Back: O(1) - Constant Time # Is Empty: O(1) - Constant Time # Size: O(1) - Constant Time ================================================ FILE: computer_science/data_structures/queue/queue.js ================================================ export class Queue { constructor() { this.items = []; } enqueue(item) { this.items.push(item); } dequeue() { return this.items.shift(); } isEmpty() { return this.size() === 0; } front() { return this.items[0]; } back() { return this.items.at(-1); } size() { return this.items.length; } } ================================================ FILE: computer_science/data_structures/queue/queue.py ================================================ # Queue Big O complexity # Enqueue (push): O(1) - Constant Time # Dequeue (remove): O(1) - Constant Time # Front: O(1) - Constant Time # Back: O(1) - Constant Time # Is Empty: O(1) - Constant Time # Size: O(1) - Constant Time class Emptiness(Exception): pass class Queue: def __init__(self): self.items = [] def enqueue(self, item): self.items.append(item) def dequeue(self): if self.is_empty(): raise Emptiness('The Queue is empty') return self.items.pop(0) def is_empty(self): return self.size() == 0 def front(self): if self.is_empty(): raise Emptiness('The Queue is empty') return self.items[0] def back(self): if self.is_empty(): raise Emptiness('The Queue is empty') return self.items[-1] def size(self): return len(self.items) def test_enqueue(queue, item): queue.enqueue(item) print(queue.items) def test_dequeue(queue): queue.dequeue() print(queue.items) def test_emptiness(queue): is_empty = queue.is_empty() print(is_empty) def test_size(queue): size = queue.size() print(size) def test_front(queue): front = queue.front() print(front) def test_back(queue): back = queue.back() print(back) queue = Queue() test_emptiness(queue) # True test_size(queue) # 0 test_enqueue(queue, 1) # [1] test_enqueue(queue, 2) # [1, 2] test_enqueue(queue, 3) # [1, 2, 3] test_enqueue(queue, 4) # [1, 2, 3, 4] test_enqueue(queue, 5) # [1, 2, 3, 4, 5] test_emptiness(queue) # False test_size(queue) # 5 test_front(queue) # 1 test_back(queue) # 5 test_dequeue(queue) # [2, 3, 4, 5] test_dequeue(queue) # [3, 4, 5] test_dequeue(queue) # [4, 5] test_dequeue(queue) # [5] test_emptiness(queue) # False test_size(queue) # 1 test_front(queue) # 5 test_back(queue) # 5 test_dequeue(queue) # [] test_emptiness(queue) # True test_size(queue) # 0 # Other test queue = Queue() queue.enqueue(1) queue.enqueue(2) queue.enqueue(3) queue.enqueue(4) queue.enqueue(5) for item in queue.items: print(item) test_front(queue) test_back(queue) queue.dequeue() test_front(queue) queue.dequeue() test_size(queue) while not queue.is_empty(): test_front(queue) queue.dequeue() test_size(queue) ================================================ FILE: computer_science/data_structures/queue/tests/queue.test.js ================================================ import { describe, expect, it } from 'vitest'; import { Queue } from '../queue'; describe('Queue', () => { it('', () => { const queue = new Queue(); expect(queue.isEmpty()).toBeTruthy(); expect(queue.size()).toEqual(0); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); queue.enqueue(5); expect(queue.isEmpty()).toBeFalsy(); expect(queue.size()).toEqual(5); expect(queue.front()).toEqual(1); expect(queue.back()).toEqual(5); expect(queue.items).toEqual([1, 2, 3, 4, 5]); queue.dequeue(); expect(queue.items).toEqual([2, 3, 4, 5]); queue.dequeue(); expect(queue.items).toEqual([3, 4, 5]); queue.dequeue(); expect(queue.items).toEqual([4, 5]); queue.dequeue(); expect(queue.items).toEqual([5]); queue.dequeue(); expect(queue.isEmpty()).toBeTruthy(); }); it('', () => { const queue = new Queue(); queue.enqueue(1); queue.enqueue(2); queue.enqueue(3); queue.enqueue(4); queue.enqueue(5); expect(queue.items).toEqual([1, 2, 3, 4, 5]); expect(queue.front()).toEqual(1); expect(queue.back()).toEqual(5); while (!queue.isEmpty()) { queue.dequeue(); } expect(queue.isEmpty()).toBeTruthy(); }); }); ================================================ FILE: computer_science/data_structures/segment_tree/frequency.cpp ================================================ #include using namespace std; #define MAX_SIZE (1 << 20) int A[4]; int segtree[MAX_SIZE]; map frequencyMap; void initialize_frequency_map() { for (int i = 0; i <= 4; i++) { if (frequencyMap.find(A[i]) == frequencyMap.end()) frequencyMap[A[i]] = 1; else frequencyMap[A[i]]++; } } void build_segtree(int node, int start, int end) { if (start == end) { segtree[node] = A[start]; } else { int middle = (start + end) / 2; build_segtree(node * 2, start, middle); build_segtree(node * 2 + 1, middle + 1, end); if (frequencyMap[segtree[node * 2]] > frequencyMap[segtree[node * 2 + 1]]) segtree[node] = segtree[node * 2]; else if (frequencyMap[segtree[node * 2]] < frequencyMap[segtree[node * 2 + 1]]) segtree[node] = segtree[node * 2 + 1]; else segtree[node] = max(segtree[node * 2], segtree[node * 2 + 1]); } } int main() { A[0] = 1; A[1] = 3; A[2] = 3; A[3] = 1; A[4] = 1; initialize_frequency_map(); build_segtree(1, 0, 4); for (int i = 1; i < 10; i++) cout << segtree[i] << " "; return 0; } ================================================ FILE: computer_science/data_structures/segment_tree/max.cpp ================================================ #include using namespace std; #define MAX_SIZE (1 << 20) int A[4]; int segtree[MAX_SIZE]; void build_segtree(int node, int start, int end) { if (start == end) { segtree[node] = A[start]; } else { int middle = (start + end) / 2; build_segtree(node * 2, start, middle); build_segtree(node * 2 + 1, middle + 1, end); segtree[node] = max(segtree[node * 2], segtree[node * 2 + 1]); } } int main() { A[0] = 1; A[1] = 3; A[2] = 3; A[3] = 1; A[4] = 1; build_segtree(1, 0, 4); for (int i = 1; i < 10; i++) cout << segtree[i] << " "; return 0; } ================================================ FILE: computer_science/data_structures/segment_tree/min.cpp ================================================ #include using namespace std; #define MAX_SIZE (1 << 20) int A[4]; int segtree[MAX_SIZE]; void build_segtree(int node, int start, int end) { if (start == end) { segtree[node] = A[start]; } else { int middle = (start + end) / 2; build_segtree(node * 2, start, middle); build_segtree(node * 2 + 1, middle + 1, end); segtree[node] = min(segtree[node * 2], segtree[node * 2 + 1]); } } int main() { A[0] = 1; A[1] = 3; A[2] = 3; A[3] = 1; A[4] = 1; build_segtree(1, 0, 4); for (int i = 1; i < 10; i++) cout << segtree[i] << " "; return 0; } ================================================ FILE: computer_science/data_structures/segment_tree/sum.cpp ================================================ #include using namespace std; #define MAX_SIZE (1 << 20) int A[4]; int segtree[MAX_SIZE]; void build_segtree(int node, int start, int end) { if (start == end) { segtree[node] = A[start]; } else { int middle = (start + end) / 2; build_segtree(node * 2, start, middle); build_segtree(node * 2 + 1, middle + 1, end); segtree[node] = segtree[node * 2] + segtree[node * 2 + 1]; } } int main() { A[0] = 1; A[1] = 3; A[2] = 3; A[3] = 1; A[4] = 1; build_segtree(1, 0, 4); for (int i = 1; i < 10; i++) cout << segtree[i] << " "; return 0; } ================================================ FILE: computer_science/data_structures/set/set.js ================================================ export class Set { constructor() { this.items = {}; } add(item) { if (!this.has(item)) { this.items[item] = item; } return this; } delete(item) { if (this.has(item)) { delete this.items[item]; return true; } return false; } has(item) { return this.items.hasOwnProperty(item); } clear() { this.items = {}; } size() { return Object.keys(this.items).length; } values() { return Object.values(this.items); } union(otherSet) { const unionSet = new Set(); this.values().forEach((value) => unionSet.add(value)); otherSet.values().forEach((value) => unionSet.add(value)); return unionSet; } intersection(otherSet) { const intersectionSet = new Set(); for (let value of this.values()) { if (otherSet.has(value)) { intersectionSet.add(value); } } return intersectionSet; } difference(otherSet) { const differenceSet = new Set(); for (let value of this.values()) { if (!otherSet.has(value)) { differenceSet.add(value); } } return differenceSet; } isSubsetOf(otherSet) { for (let value of this.values()) { if (!otherSet.has(value)) { return false; } } return true; } } ================================================ FILE: computer_science/data_structures/set/sets.cpp ================================================ // add an element, but do not allow duples [duplicates?] // remove elements // get count of elements (distinct elements) // check whether elements are present in set #include #include #include using namespace std; int main() { set s; // adding elements to set for (int i = 0; i <= 100; i++) s.insert(i); // set doesn't accept duplicate elements s.insert(50); // need to be 101 (100 elements + 0 number) cout << s.size() << endl; // remove even numbers for (int i = 0; i <= 100; i+=2) s.erase(i); // need to be 50 cout << s.size() << endl; // calculate the sum of set elements int total = 0; for (set::const_iterator iterator = s.begin(); iterator != s.end(); iterator++) total += *iterator; cout << total << endl; // removing the duplicates from a vector vector v; for (int i = 10; i > 0; i--) v.push_back(i); v.push_back(5); set s2; for (int i = 1; i <= 10; i++) s2.insert(v[i]); vector v2; for (set::const_iterator iterator = s2.begin(); iterator != s2.end(); iterator++) v2.push_back(*iterator); for (int i = 0; i < 10; i++) cout << v2[i] << endl; return 0; } ================================================ FILE: computer_science/data_structures/set/tests/set.test.js ================================================ import { describe, it, expect } from 'vitest'; import { Set } from '../set'; describe('Set', () => { it('performs all behaviors correctly', () => { const set = new Set(); set.add(1); expect(set.values()).toEqual([1]); expect(set.has(1)).toEqual(true); expect(set.size()).toEqual(1); set.add(2); expect(set.values()).toEqual([1, 2]); expect(set.has(2)).toEqual(true); expect(set.size()).toEqual(2); set.delete(1); expect(set.values()).toEqual([2]); set.delete(2); expect(set.values()).toEqual([]); }); it('union sets', () => { const setA = new Set(); setA.add(1); setA.add(2); setA.add(3); const setB = new Set(); setB.add(3); setB.add(4); setB.add(5); setB.add(6); const unionAB = setA.union(setB); expect(unionAB.values()).toEqual([1, 2, 3, 4, 5, 6]); }); it('intersection sets', () => { const setA = new Set(); setA.add(1); setA.add(2); setA.add(3); const setB = new Set(); setB.add(2); setB.add(3); setB.add(4); const intersectionAB = setA.intersection(setB); expect(intersectionAB.values()).toEqual([2, 3]); }); it('difference sets', () => { const setA = new Set(); setA.add(1); setA.add(2); setA.add(3); const setB = new Set(); setB.add(2); setB.add(3); setB.add(4); const differenceAB = setA.difference(setB); expect(differenceAB.values()).toEqual([1]); }); it('is subset of', () => { const setA = new Set(); setA.add(1); setA.add(2); const setB = new Set(); setB.add(1); setB.add(2); setB.add(3); const setC = new Set(); setC.add(2); setC.add(3); setC.add(4); expect(setA.isSubsetOf(setB)).toEqual(true); expect(setA.isSubsetOf(setC)).toEqual(false); }); }); ================================================ FILE: computer_science/data_structures/stack/deque_api.py ================================================ from collections import deque q = deque() q.append(1) q.append(2) q.append(3) print(q) print(q.pop()) print(q.pop()) print(q.pop()) ================================================ FILE: computer_science/data_structures/stack/stack.cpp ================================================ #include using namespace std; #define MAX_STACK_SIZE 10 class Stack { private: int container[MAX_STACK_SIZE]; int numberOfElements; public: Stack() { numberOfElements = 0; } void push(int element) { if (numberOfElements > MAX_STACK_SIZE) { cout << "Error: Stack Overflow"; } else { container[numberOfElements] = element; numberOfElements++; } } int pop() { if (isEmpty()) { cout << "Error: No element to pop"; } else { numberOfElements--; return container[numberOfElements]; } } int top() { return container[numberOfElements-1]; } bool isEmpty() { return numberOfElements == 0; } }; int main() { Stack stack; if (stack.isEmpty()) cout << "Stack is empty" << endl; stack.push(1); stack.push(2); stack.push(3); cout << stack.pop() << endl; stack.push(10); cout << stack.top() << endl; if (!stack.isEmpty()) cout << "Stack is not empty" << endl; return 0; } ================================================ FILE: computer_science/data_structures/stack/stack.js ================================================ const push = (stack, item) => [item, ...stack]; const pop = (stack) => stack.slice(1); const top = (stack) => stack[0]; const isEmpty = (stack) => size(stack) === 0; const size = (stack) => stack.length; // testing let stack = []; console.log(isEmpty(stack)); stack = push(stack, 1); console.log(stack); stack = push(stack, 2); console.log(stack); stack = push(stack, 3); console.log(stack); stack = push(stack, 4); console.log(stack); stack = push(stack, 5); console.log(stack); console.log(top(stack)); console.log(size(stack)); console.log(isEmpty(stack)); stack = pop(stack); stack = pop(stack); stack = pop(stack); stack = pop(stack); console.log(isEmpty(stack)); console.log(top(stack)); stack = pop(stack); console.log(isEmpty(stack)); console.log(size(stack)); ================================================ FILE: computer_science/data_structures/stack/stack.py ================================================ # Stack Big O complexity # Push: O(1) - Constant Time # Pop (remove): O(1) - Constant Time # Top (top): O(1) - Constant Time # Is Empty: O(1) - Constant Time # Size: O(1) - Constant Time class Emptiness(Exception): pass class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items.pop() def is_empty(self): return self.size() == 0 def top(self): if self.is_empty(): raise Emptiness('The Stack is empty') return self.items[-1] def size(self): return len(self.items) stack = Stack() print(stack.is_empty()) stack.push(1) print(stack.items) stack.push(2) print(stack.items) stack.push(3) print(stack.items) stack.push(4) print(stack.items) stack.push(5) print(stack.items) print(stack.is_empty()) print(stack.top()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.pop()) print(stack.is_empty()) print(stack.pop()) print(stack.is_empty()) # reversing a list def reverse(bookshelf): stack = Stack() for book in bookshelf: stack.push(book) reversed_bookshelf = [] while not stack.is_empty(): reversed_bookshelf.append(stack.pop()) return reversed_bookshelf bookshelf = [ 'Harry Potter', 'Atomic Habits', 'Leonardo da Vinci', 'Sapiens', 'Peak' ] reversed_bookshelf = reverse(bookshelf) print(reversed_bookshelf) ================================================ FILE: computer_science/data_structures/stack/stack_class.js ================================================ class Stack { constructor() { this.items = []; } push(item) { this.items.push(item); } pop() { return this.items.pop(); } top() { return this.items[this.items.length - 1]; } isEmpty() { return this.size() === 0; } size() { return this.items.length; } } // testing const stack = new Stack(); console.log(stack.isEmpty()); stack.push(1); console.log(stack.items); stack.push(2); console.log(stack.items); stack.push(3); console.log(stack.items); stack.push(4); console.log(stack.items); stack.push(5); console.log(stack.items); console.log(stack.isEmpty()); console.log(stack.top()); stack.pop(); console.log(stack.items); stack.pop(); console.log(stack.items); stack.pop(); console.log(stack.items); stack.pop(); console.log(stack.items); console.log(stack.isEmpty()); stack.pop(); console.log(stack.items); console.log(stack.isEmpty()); console.log(stack.top()); // Reversing a list with the stack data structure function reverse(list) { const stack = new Stack(); for (item of list) { stack.push(item); } const reversedList = []; while (!stack.isEmpty()) { reversedList.push(stack.pop()); } return reversedList; } const reversedBooks = reverse([ 'Harry Potter', 'Atomic Habits', 'Leonardo da Vinci', 'Sapiens', 'Peak', ]); console.log(reversedBooks); ================================================ FILE: computer_science/data_structures/stack/stack_closure.js ================================================ const createStack = () => { let items = []; const push = (item) => items = [item, ...items]; const pop = () => items = items.slice(1); const top = () => items[0]; const isEmpty = () => size() === 0; const size = () => items.length; const getItems = () => items; return { push, pop, top, isEmpty, size, getItems }; }; // testing const stack = createStack(); console.log(stack.isEmpty()); stack.push(1); console.log(stack.getItems()); stack.push(2); console.log(stack.getItems()); stack.push(3); console.log(stack.getItems()); stack.push(4); console.log(stack.getItems()); stack.push(5); console.log(stack.getItems()); console.log(stack.top()); console.log(stack.size()); console.log(stack.isEmpty()); stack.pop(); console.log(stack.getItems()); stack.pop(); console.log(stack.getItems()); stack.pop(); console.log(stack.getItems()); stack.pop(); console.log(stack.getItems()); console.log(stack.isEmpty()); console.log(stack.top()); stack.pop(); console.log(stack.getItems()); console.log(stack.isEmpty()); console.log(stack.size()); ================================================ FILE: computer_science/data_structures/string/strings.cpp ================================================ #include #include using namespace std; int main() { // defining strings string string1 = "hello world"; string string2; // printing strings cout << string1 << endl; // finding letter(s) in a string // return npos --> -1 if don't find the element cout << string1.find("e") << endl; // using input for string cin >> string2; cout << string2 << endl; // size cout << string1.size() << endl; cout << string2.size() << endl; // substrings cout << string1.substr(0, 5) << endl; cout << string1.substr(6, string1.size() - 1) << endl; string palavra = "lalala.lololo"; cout << palavra.substr(6, 1) << endl; cout << palavra.substr(0, 6 - 0) << endl; cout << palavra.substr(6+1, palavra.size()-6) << endl; // string to integer string um = "1"; cout << stoi(um) << " - deu certo!" << endl; string vinte = "20"; cout << stoi(vinte) << " - deu certo.. de novo!" << endl; // last element of string string word = "Leandro"; cout << palavra.back() << endl; // we can iterate a string: each char for (int i = 0; i < word; i++) cout << word[i] << " "; cout << endl; // compare string letter with char for (int i = 0; i < word.size(); i++) if (word[i] == 'a') cout << word[i] << " "; cout << endl; // use cin to get string // use getline(cin, string) to get a line of strings return 0; } ================================================ FILE: package.json ================================================ { "name": "algorithms", "scripts": { "test": "vitest" }, "devDependencies": { "vitest": "0.34.5" }, "type": "module" } ================================================ FILE: problem-solving.md ================================================ # Algorithm Problem Solving 0. Start with the naive solution. It shows you understand the problem. 1. Think out loud, even if it's quiet. It lets the interviewer help out if you get stuck. 2. Write your own test cases. Write at least 3 test cases to show you understand the problem. 3. Outline your algorithm on the IDE. It makes it easier for everyone to follow along. 4. Refer back to each step of your algorithm as you're coding. This shows you can walk the walk. 5. Dry run your code line by line against your test cases. Dont wait for the interviewer to ask you to do it. 6. Offer to optimize the algorithm. Point out the bottleneck first then explain what you need to do differently. 7. Solve for the running time. Solve it throughout your code then explain your nested for loop makes it O(n^2) 8. Use good variable names. Thing1 and thing2 aren't good things to write. 9. Abstract functions away. Don't spend the entire interview on a parsing function that isn't important to the algorithm 10. Do it for the interviewer. Keep checking in with the interviewer if they understand what's going on or if you need to walk them through your ideas. ================================================ FILE: system-design.md ================================================ # System Design - [Preparing to System Design](https://qr.ae/TSJEwu) - [InterviewBit System Design course](https://www.interviewbit.com/courses/system-design/) - [System Design Primer](https://github.com/donnemartin/system-design-primer) - [The System Design Process](https://www.hiredintech.com/classrooms/system-design/lesson/55) - [High Scalability](http://highscalability.com/) - [System Design Template](https://leetcode.com/discuss/career/229177/My-System-Design-Template)