Showing preview only (294K chars total). Download the full file or copy to clipboard to get everything.
Repository: keep-practicing/leetcode-go
Branch: master
Commit: 8fb3d0066cf6
Files: 252
Total size: 229.4 KB
Directory structure:
gitextract_t27zlmsi/
├── .codacy.yml
├── .codecov.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── _config.yml
├── bak.README.md
├── docs/
│ ├── _config.yml
│ └── index.md
├── go.mod
├── solutions/
│ ├── 0001_two_sum/
│ │ ├── twosum.go
│ │ └── twosum_test.go
│ ├── 0002_add_two_numbers/
│ │ ├── add_two_numbers.go
│ │ └── add_two_numbers_test.go
│ ├── 0003_longest_substring_without_repeating_characters/
│ │ ├── longest_substring_without_repeating_characters.go
│ │ └── longest_substring_without_repeating_characters_test.go
│ ├── 0004_median_of_two_sorted_arrays/
│ │ ├── motsa.go
│ │ └── motsa_test.go
│ ├── 0007_reverse_integer/
│ │ ├── reverse_integer.go
│ │ └── reverse_integer_test.go
│ ├── 0009_palindrome_number/
│ │ ├── palindrome_number.go
│ │ └── palindrome_number_test.go
│ ├── 0011_container_with_most_water/
│ │ ├── container_with_most_water.go
│ │ └── container_with_most_water_test.go
│ ├── 0013_roman_to_integer/
│ │ ├── roman_to_integer.go
│ │ └── roman_to_integer_test.go
│ ├── 0014_longest_common_prefix/
│ │ ├── lcp.go
│ │ └── lcp_test.go
│ ├── 0015_3Sum/
│ │ ├── 3sum.go
│ │ └── 3sum_test.go
│ ├── 0017_letter_combination_of_a_phone_number/
│ │ ├── letter_combination_of_phone_number.go
│ │ └── letter_combination_of_phone_number_test.go
│ ├── 0019_remove_nth_node_from_end_of_list/
│ │ ├── remove_nth_node_from_end_of_list.go
│ │ └── remove_nth_node_from_end_of_list_test.go
│ ├── 0020_valid_parentheses/
│ │ ├── valid_parentheses.go
│ │ └── valid_parentheses_test.go
│ ├── 0021_merge_two_sorted_lists/
│ │ ├── mergeTwoLists.go
│ │ └── mergeTwoLists_test.go
│ ├── 0023_merge_k_sorted_lists/
│ │ ├── mksl.go
│ │ └── mksl_test.go
│ ├── 0024_swap_nodes_in_pairs/
│ │ ├── swap_nodes_in_pairs.go
│ │ └── swap_nodes_in_pairs_test.go
│ ├── 0025_reverse_nodes_in_k_group/
│ │ ├── reverse_node_k_group.go
│ │ └── reverse_node_k_group_test.go
│ ├── 0026_remove_duplicates_from_sorted_array/
│ │ ├── rdfsa.go
│ │ └── rdfsa_test.go
│ ├── 0027_remove_element/
│ │ ├── remove_element.go
│ │ └── remove_element_test.go
│ ├── 0028_implement_strstr/
│ │ ├── implement_strstr.go
│ │ └── implement_strstr_test.go
│ ├── 0033_search_in_rotated_sorted_array/
│ │ ├── search_in_rotated_sorted_array.go
│ │ └── search_in_rotated_sorted_array_test.go
│ ├── 0034_find_first_and_last_position_of_element_in_sorted_array/
│ │ ├── find_first_and_last_position_of_element_in_sorted_array.go
│ │ └── find_first_and_last_position_of_element_in_sorted_array_test.go
│ ├── 0035_search_insert_position/
│ │ ├── search_insert_position.go
│ │ └── search_insert_position_test.go
│ ├── 0048_rotate_image/
│ │ ├── rotate_image.go
│ │ └── rotate_image_test.go
│ ├── 0053_maximum_subarray/
│ │ ├── maximum_subarray.go
│ │ └── maximum_subarray_test.go
│ ├── 0058_length_of_last_word/
│ │ ├── len_of_last_word.go
│ │ └── len_of_last_word_test.go
│ ├── 0061_rotate_list/
│ │ ├── rotate_list.go
│ │ └── rotate_list_test.go
│ ├── 0062_unique_paths/
│ │ ├── unique_paths.go
│ │ └── unique_paths_test.go
│ ├── 0063_unique_paths_2/
│ │ ├── unique_paths2.go
│ │ └── unique_paths2_test.go
│ ├── 0064_minimum_path_sum/
│ │ ├── minimum_path_sum.go
│ │ └── minimum_path_sum_test.go
│ ├── 0066_plus_one/
│ │ ├── plus_one.go
│ │ └── plus_one_test.go
│ ├── 0067_add_binary/
│ │ ├── add_binary.go
│ │ └── add_binary_test.go
│ ├── 0069_sqrtx/
│ │ ├── sqrtx.go
│ │ └── sqrtx_test.go
│ ├── 0070_climbing_stairs/
│ │ ├── climbing_stairs.go
│ │ └── climbing_stairs_test.go
│ ├── 0075_sort_colors/
│ │ ├── sort_colors.go
│ │ └── sort_colors_test.go
│ ├── 0076_minimum_window_substring/
│ │ ├── minimum_window_substring.go
│ │ └── minimum_window_substring_test.go
│ ├── 0077_combinations/
│ │ ├── combinations.go
│ │ └── combinations_test.go
│ ├── 0079_word_search/
│ │ ├── word_search.go
│ │ └── word_search_test.go
│ ├── 0080_remove_duplicates_from_sorted_array2/
│ │ ├── rdfsa2.go
│ │ └── rdfsa2_test.go
│ ├── 0082_remove_duplicates_from_sorted_list_2/
│ │ ├── rdfsl.go
│ │ └── rdfsl_test.go
│ ├── 0083_remove_duplicates_from_sorted_list/
│ │ ├── rdfsl.go
│ │ └── rdfsl_test.go
│ ├── 0086_partition_list/
│ │ ├── partition_list.go
│ │ └── partition_list_test.go
│ ├── 0088_merge_sorted_array/
│ │ ├── msa.go
│ │ └── msa_test.go
│ ├── 0092_reverse_linked_list_2/
│ │ ├── reverse_linked_list2.go
│ │ └── reverse_linked_list2_test.go
│ ├── 0094_binary_tree_inorder_traversal/
│ │ ├── binary_tree_inorder_traversal.go
│ │ └── binary_tree_inorder_traversal_test.go
│ ├── 0100_same_tree/
│ │ ├── same_tree.go
│ │ └── same_tree_test.go
│ ├── 0101_symmetric_tree/
│ │ ├── symmetric_tree.go
│ │ └── symmetric_tree_test.go
│ ├── 0102_binary_tree_level_order_traversal/
│ │ ├── binary_tree_level_order_traversal.go
│ │ └── binary_tree_level_order_traversal_test.go
│ ├── 0104_maximun_depth_of_binary_tree/
│ │ ├── maxdobt.go
│ │ └── maxdobt_test.go
│ ├── 0107_binary_tree_level_order_traversal_2/
│ │ ├── binary_tree_level_order_traversal2.go
│ │ └── binary_tree_level_order_traversal2_test.go
│ ├── 0111_minimum_depth_of_binary_tree/
│ │ ├── minimum_depth_of_binary_tree.go
│ │ └── minimum_depth_of_binary_tree_test.go
│ ├── 0112_path_sum/
│ │ ├── path_sum.go
│ │ └── path_sum_test.go
│ ├── 0120_triangle/
│ │ ├── triangle.go
│ │ └── triangle_test.go
│ ├── 0121_best_time_to_buy_and_sell_stock/
│ │ ├── maxprofit.go
│ │ └── maxprofit_test.go
│ ├── 0122_best_time_to_buy_and_sell_stock_2/
│ │ ├── maxprofit.go
│ │ └── maxprofit_test.go
│ ├── 0125_valid_palindrome/
│ │ ├── valid_palindrome.go
│ │ └── valid_palindrome_test.go
│ ├── 0136_single_number/
│ │ ├── single_number.go
│ │ └── single_number_test.go
│ ├── 0144_binary_tree_preorder_traversal/
│ │ ├── binary_tree_preorder_traversal.go
│ │ └── binary_tree_preorder_traversal_test.go
│ ├── 0150_evaluate_reverse_polish_notation/
│ │ ├── evaluate_reverse_polish_notation.go
│ │ └── evaluate_reverse_polish_notation_test.go
│ ├── 0153_find_minimum_in_rotated_sorted_array/
│ │ ├── fmirsa.go
│ │ └── fmirsa_test.go
│ ├── 0155_min_stack/
│ │ ├── min_stack.go
│ │ └── min_stack_test.go
│ ├── 0165_compare_version_numbers/
│ │ ├── compare_version_numbers.go
│ │ └── compare_version_numbers_test.go
│ ├── 0167_two_sum2/
│ │ ├── two_sum2.go
│ │ └── two_sum2_test.go
│ ├── 0179_largest_number/
│ │ ├── ln.go
│ │ └── ln_test.go
│ ├── 0198_house_robber/
│ │ ├── house_robber.go
│ │ └── house_robber_test.go
│ ├── 0200_number_of_island/
│ │ ├── number_of_island.go
│ │ └── number_of_island_test.go
│ ├── 0203_remove_linked_list_elements/
│ │ ├── remove_linked_list_elements.go
│ │ └── remove_linked_list_elements_test.go
│ ├── 0206_reverse_linked_list/
│ │ ├── reverse_linked_list.go
│ │ └── reverse_linked_list_test.go
│ ├── 0208_implement_trie_prefix_tree/
│ │ ├── impltrie.go
│ │ └── impltrie_test.go
│ ├── 0209_minimum_size_subarray_sum/
│ │ ├── minimum_size_subarray_sum.go
│ │ └── minimum_size_subarray_sum_test.go
│ ├── 0211_add_and_search_word/
│ │ ├── add_and_search_word.go
│ │ └── add_and_search_word_test.go
│ ├── 0215_kth_largest_element_in_an_array/
│ │ ├── kthleiaa.go
│ │ └── kthleiaa_test.go
│ ├── 0217_contains_duplicate/
│ │ ├── contains_duplicate.go
│ │ └── contains_duplicate_test.go
│ ├── 0219_contains_duplicate_2/
│ │ ├── contains_duplicate_2.go
│ │ └── contains_duplicate_2_test.go
│ ├── 0226_invert_binary_tree/
│ │ ├── invert_binary_tree.go
│ │ └── invert_binary_tree_test.go
│ ├── 0235_lowest_common_ancestor_of_a_binary_search_tree/
│ │ ├── lcaoabst.go
│ │ └── lcaoabst_test.go
│ ├── 0236_Lowest_Common_Ancestor_of_a_Binary_Tree/
│ │ ├── lca.go
│ │ └── lca_test.go
│ ├── 0237_delete_node_in_a_linked_list/
│ │ ├── dniall.go
│ │ └── dniall_test.go
│ ├── 0257_binary_tree_paths/
│ │ ├── binary_tree_paths.go
│ │ └── binary_tree_paths_test.go
│ ├── 0258_add_digits/
│ │ ├── add_digits.go
│ │ └── add_digits_test.go
│ ├── 0283_move_zeroes/
│ │ ├── move_zeroes.go
│ │ ├── move_zeroes2.go
│ │ ├── move_zeroes2_test.go
│ │ └── move_zeroes_test.go
│ ├── 0300_longest_increasing_subsequence/
│ │ ├── lis.go
│ │ └── lis_test.go
│ ├── 0303_range_sum_query/
│ │ ├── rsqim.go
│ │ └── rsqim_test.go
│ ├── 0307_Range_Sum_Query_Mutable/
│ │ ├── range_sum_query_mut.go
│ │ └── range_sum_query_mut_test.go
│ ├── 0328_odd_even_linked_list/
│ │ ├── odd_even_linked_list.go
│ │ └── odd_even_linked_list_test.go
│ ├── 0343_integer_break/
│ │ ├── integer_break.go
│ │ └── integer_break_test.go
│ ├── 0344_reverse_string/
│ │ ├── reverse_string.go
│ │ └── reverse_string_test.go
│ ├── 0345_reverse_vowels_of_a_string/
│ │ ├── reverse_vowels.go
│ │ └── reverse_vowels_test.go
│ ├── 0347_top_k_frequent_elements/
│ │ ├── topkfe.go
│ │ └── topkfe_test.go
│ ├── 0349_intersection_of_2_arrays/
│ │ ├── intersection_of_two_arrays.go
│ │ └── intersection_of_two_arrays_test.go
│ ├── 0350_intersection_of_two_arrays2/
│ │ ├── intersection_of_two_arrays2.go
│ │ └── intersection_of_two_arrays2_test.go
│ ├── 0376_wiggle_subsequence/
│ │ ├── wiggle_subsequence.go
│ │ └── wiggle_subsequence_test.go
│ ├── 0392_is_subsequence/
│ │ ├── is_subsequence.go
│ │ └── is_subsequence_test.go
│ ├── 0404_sum_of_left_leaves/
│ │ ├── sum_of_left_leaves.go
│ │ └── sum_of_left_leaves_test.go
│ ├── 0416_partition_equal_subset_sum/
│ │ ├── partition_equal_subset_sum.go
│ │ └── partition_equal_subset_sum_test.go
│ ├── 0435_non_overlapping_intervals/
│ │ ├── dp_solution.go
│ │ ├── greedy_solution.go
│ │ ├── interval.go
│ │ └── solution_test.go
│ ├── 0437_path_sum_3/
│ │ ├── path_sum_3.go
│ │ └── path_sum_3_test.go
│ ├── 0438_all_anagrams_in_a_string/
│ │ ├── all_anagrams_in_a_string.go
│ │ └── all_anagrams_in_a_string_test.go
│ ├── 0447_number_of_boomerangs/
│ │ ├── number_of_boomerangs.go
│ │ └── number_of_boomerangs_test.go
│ ├── 0454_4sum2/
│ │ ├── 4sum2.go
│ │ └── 4sum2_test.go
│ ├── 0455_assign_cookies/
│ │ ├── assign_cookies.go
│ │ └── assign_cookies_test.go
│ ├── 0557_reverse_words_in_a_string_3/
│ │ ├── reverse_words_in_a_string_3.go
│ │ └── reverse_words_in_a_string_3_test.go
│ ├── 0674_longest_continuous_increasing_subsequence/
│ │ ├── lcis.go
│ │ └── lcis_test.go
│ ├── 0677_map_sum_pairs/
│ │ ├── map_sum_pairs.go
│ │ └── map_sum_pairs_test.go
│ ├── 0704_binary_search/
│ │ ├── binary_search.go
│ │ └── binary_search_test.go
│ ├── 0713_subarray_product_less_than_k/
│ │ ├── spltk.go
│ │ └── spltk_test.go
│ ├── 0717_1_bit_and_2_bit_characters/
│ │ ├── 1bitand2bitc.go
│ │ └── 1bitand2bitc_test.go
│ ├── 0728_self_dividing_numbers/
│ │ ├── self_dividing_numbers.go
│ │ └── self_dividing_numbers_test.go
│ ├── 0735_asteroid_collision/
│ │ ├── ac.go
│ │ └── ac_test.go
│ ├── 0747_largest_number_at_least_twice_of_others/
│ │ ├── largest_number_at_least_twice_of_others.go
│ │ └── largest_number_at_least_twice_of_others_test.go
│ ├── 0872_leaf_similar_trees/
│ │ ├── leaf_similar_trees.go
│ │ └── leaf_similar_trees_test.go
│ ├── 1021_Remove_Outermost_Parentheses/
│ │ ├── remove_outmost_parentheses.go
│ │ └── remove_outmost_parentheses_test.go
│ ├── 148_Sort_List/
│ │ ├── sortlist.go
│ │ └── sortlist_test.go
│ ├── 304_Range_Sum_Query_2D/
│ │ ├── rsq.go
│ │ └── rsq_test.go
│ └── README.md
├── ut.bash
└── utils/
├── infinite.go
├── maxint.go
├── maxint_test.go
├── minint.go
├── minint_test.go
├── set.go
└── set_test.go
================================================
FILE CONTENTS
================================================
================================================
FILE: .codacy.yml
================================================
---
exclude_paths:
- '**/*.md'
- 'README.md'
================================================
FILE: .codecov.yml
================================================
codecov:
notify:
require_ci_to_pass: yes
coverage:
round: up
range: 0..10
precision: 2
status:
project: yes
patch: yes
changes: yes
comment:
layout: "reach, diff, flags, files"
behavior: default
require_changes: false # if true: only post the comment if coverage changes
require_base: yes # [yes :: must have a base report to post]
require_head: yes # [yes :: must have a head report to post]
branches: null
================================================
FILE: .gitignore
================================================
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, build with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# JetBrains
.idea/
# vs code
.vscode/
# mac
.DS_Store
================================================
FILE: .travis.yml
================================================
language: go
go:
- "1.12.x"
go_import_path: leetcode
install:
- go get -t -v ./...
script:
- go test ./... -race -coverprofile=coverage.txt -covermode=atomic
after_success:
- bash <(curl -s https://codecov.io/bash)
branches:
only:
- master
================================================
FILE: LICENSE
================================================
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
For more information, please refer to <http://unlicense.org>
================================================
FILE: Makefile
================================================
# Basic go commands
GOCMD=go
GOBUILD=$(GOCMD) build
GOCLEAN=$(GOCMD) clean
GOTEST=$(GOCMD) test
GOGET=$(GOCMD) get
GOFMT=$(GOCMD) fmt
test:
@echo "unit test"
$(GOTEST) ./...
clean:
@echo "clean test cache"
$(GOCLEAN) -testcache
fmt:
@echo "fmt code"
$(GOFMT) ./...
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-architect
================================================
FILE: bak.README.md
================================================
# Go Solution for Leetcode algorithm problems
[](https://travis-ci.org/zwfang/leetcode)
[](https://codecov.io/gh/zwfang/leetcode)
[](https://www.codacy.com/app/zwfang/leetcode?utm_source=github.com&utm_medium=referral&utm_content=zwfang/leetcode&utm_campaign=Badge_Grade)
[](https://goreportcard.com/report/github.com/zwfang/leetcode)
continually updating 😃.
### [view by sorted](./solutions/README.md)
### Array
* [1. Two Sum](solutions/0001_two_sum/twosum.go) *`lookup table;`* *`hash table`*
* [4. Median of Two Sorted Arrays](solutions/0004_median_of_two_sorted_arrays/motsa.go) *`binary search;`* *`divide and conquer`*
* [11. Container With Most Water](solutions/0011_container_with_most_water/container_with_most_water.go) *`double index;`* *`array`*
* [15. 3Sum](solutions/0015_3Sum/3sum.go) *`double index;`* *`array`*
* [26. Remove Duplicates from Sorted Array](solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go) *`double index;`* *`array`*
* [27. Remove Element](solutions/0027_remove_element/remove_element.go) *`double index;`* *`array`*
* [48. Rotate Image](solutions/0048_rotate_image/rotate_image.go)
* [53. Maximum Subarray](solutions/0053_maximum_subarray/maximum_subarray.go) *`dynamic programming`*
* [75. Sort Colors](solutions/0075_sort_colors/sort_colors.go) *`sort;`* *`array`*
* [80. Remove Duplicates from Sorted Array II](solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go) *`double index;`* *`array`*
* [88. Merge Sorted Array](solutions/0088_merge_sorted_array/msa.go) *`sort;`* *`array`*
* [121. Best Time to Buy and Sell Stock](solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go) *`dynamic programming;`* *`array`*
* [122. Best Time to Buy and Sell Stock II](solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go) *`greedy;`* *`array`*
* [136. Single Number](solutions/0136_single_number/single_number.go) *`hash table;`* *`bit manipulation`*
* [167. Two Sum II - Input array is sorted](solutions/0167_two_sum2/two_sum2.go) *`double index;`* *`binary search`*
* [179. Largest Number](solutions/0179_largest_number/ln.go) *`sort`*
* [200. Number of Islands](solutions/0200_number_of_island/number_of_island.go) *`dfs;`* *`bfs`*
* [209. Minimum Size Subarray Sum](solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go) *`sliding window`*
* [215. Kth Largest Element in an Array](solutions/0215_kth_largest_element_in_an_array/kthleiaa.go) *`sort`*
* [217. Contains Duplicate](solutions/0217_contains_duplicate/contains_duplicate.go) *`map`*
* [219. Contains Duplicate II](solutions/0219_contains_duplicate_2/contains_duplicate_2.go) *`map`*
* [283. Move Zeroes(solution1)](solutions/0283_move_zeroes/move_zeroes.go) *`sliding window`*
* [283. Move Zeroes(solution2)](solutions/0283_move_zeroes/move_zeroes2.go) *`sliding window`*
* [303. Range Sum Query - Immutable](solutions/0303_range_sum_query/rsqim.go)
* [347. Top K Frequent Elements](solutions/0347_top_k_frequent_elements/topkfe.go) *`hash table;`* *`heap`*
* [349. Intersection of Two Arrays](solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays.go) *`set`*
* [350. Intersection of Two Arrays II](solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go) *`hash table`*
* [447. Number of Boomerangs](solutions/0447_number_of_boomerangs/number_of_boomerangs.go) *`hash table`*
* [454. 4Sum II](solutions/0454_4sum2/4sum2.go) *`hash table`*
* [674. Longest Continuous Increasing Subsequence](solutions/0674_longest_continuous_increasing_subsequence/lcis.go)
* [713. Subarray Product Less Than K](solutions/0713_subarray_product_less_than_k/spltk.go) *`sliding window`* *`array`*
* [717. 1-bit and 2-bit Characters](solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc.go)
* [747. Largest Number At Least Twice of Others](solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others.go)
### Stack
* [155. Min Stack](solutions/0155_min_stack/min_stack.go)
* [735. Asteroid Collision](solutions/0735_asteroid_collision/ac.go)
### String
* [3. Longest Substring Without Repeating Characters](solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go) *`sliding window;`* *`hash table`*
* [14. Longest Common Prefix](solutions/0014_longest_common_prefix/lcp.go)
* [17. Letter Combinations of a Phone Number](solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go) *`tree`*
* [20. Valid Parentheses](solutions/0020_valid_parentheses/valid_parentheses.go) *`stack`*
* [28. Implement strStr()](solutions/0028_implement_strstr/implement_strstr.go) *`double index`*
* [58. Length of Last Word](solutions/0058_length_of_last_word/len_of_last_word.go)
* [67. Add Binary](solutions/0067_add_binary/add_binary.go) *`brute force`*
* [76. Minimum Window Substring](solutions/0076_minimum_window_substring/minimum_window_substring.go) *`sliding window`*
* [125. Valid Palindrome](solutions/0125_valid_palindrome/valid_palindrome.go) *`string;`* *`double index`*
* [165. Compare Version Numbers](solutions/0165_compare_version_numbers/compare_version_numbers.go)
* [344. Reverse String](solutions/0344_reverse_string/reverse_string.go) *`string;`* *`double index`*
* [345. Reverse Vowels of a String](solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go) *`string;`* *`double index`*
* [438. Find All Anagrams in a String](solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string.go) *`sliding window`*
* [557. Reverse Words in a String III](solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3.go)
* [1021. Remove Outermost Parentheses](solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses.go) *`stack`*
### Linked List
* [2. Add Two Numbers](solutions/0002_add_two_numbers/add_two_numbers.go) *`recursion;`* *`math`*
* [19. Remove Nth Node From End of List](solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go) *`two pointers`*
* [21. Merge Two Sorted Lists](solutions/0021_merge_two_sorted_lists/mergeTwoLists.go)
* [23. Merge k Sorted Lists](solutions/0023_merge_k_sorted_lists/mksl.go) *`heap`*
* [24. Swap Nodes in Pairs](solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go)
* [25. Reverse Nodes in k-Group](solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go)
* [61. Rotate List](solutions/0061_rotate_list/rotate_list.go)
* [82. Remove Duplicates from Sorted List II](solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go)
* [83. Remove Duplicates from Sorted List](solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go)
* [86. Partition List](solutions/0086_partition_list/partition_list.go) *`two pointers`*
* [92. Reverse Linked List II](solutions/0092_reverse_linked_list_2/reverse_linked_list2.go)
* [148. Sort List](solutions/148_Sort_List/sortlist.go) *`sort`*
* [203. Remove Linked List Elements](solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go)
* [206. Reverse Linked List](solutions/0206_reverse_linked_list/reverse_linked_list.go)
* [237. Delete Node in a Linked List](solutions/0237_delete_node_in_a_linked_list/dniall.go)
* [328. Odd Even Linked List](solutions/0328_odd_even_linked_list/odd_even_linked_list.go)
### Dynamic Programming
* [62. Unique Paths](solutions/0062_unique_paths/unique_paths.go) *`array`*
* [63. Unique Paths 2](solutions/0063_unique_paths_2/unique_paths2.go) *`array`*
* [64. Minimum Path Sum](solutions/0064_minimum_path_sum/minimum_path_sum.go) *`array`*
* [70. Climbing Stairs](solutions/0070_climbing_stairs/climbing_stairs.go)
* [120. Triangle](solutions/0120_triangle/triangle.go) *`array`*
* [198. House Robber](solutions/0198_house_robber/house_robber.go)
* [300. Longest Increasing Subsequence](solutions/0300_longest_increasing_subsequence/lis.go)
* [304. Range Sum Query 2D - Immutable](solutions/304_Range_Sum_Query_2D/rsq.go)
* [343. Integer Break](solutions/0343_integer_break/integer_break.go) *`math`*
* [376. Wiggle Subsequence](solutions/0376_wiggle_subsequence/wiggle_subsequence.go) *`greedy;`* *`dynamic programming`*
* [416. Partition Equal Subset Sum](solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum.go) *`0-1 knapsack problem`*
* [435. Non-overlapping Intervals](solutions/0435_non_overlapping_intervals/dp_solution.go) *`greedy;`* *`dynamic programming`* *`0-1 knapsack problem`*
### Greedy
* [392. Is Subsequence](solutions/0392_is_subsequence/is_subsequence.go)
* [435. Non-overlapping Intervals](solutions/0435_non_overlapping_intervals/greedy_solution.go) *`greedy;`* *`dynamic programming`*
* [455. Assign Cookies](solutions/0455_assign_cookies/assign_cookies.go)
### Backtracking
* [77. Combinations](solutions/0077_combinations/combinations.go) *`combine`*
* [79. Word Search](solutions/0079_word_search/word_search.go) *`array`*
### Tree
* [94. Binary Tree Inorder Traversal](solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go) *`binary tree;`* *`stack`*
* [100. Same Tree](solutions/0100_same_tree/same_tree.go) *`binary tree;`* *`dfs`*
* [101. Symmetric Tree](solutions/0101_symmetric_tree/symmetric_tree.go) *`binary tree;`* *`dfs;`* *`bfs;`*
* [102. Binary Tree Level Order Traversal](solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go) *`binary tree;`* *`dfs`*
* [104. Maximum Depth of Binary Tree](solutions/0104_maximun_depth_of_binary_tree/maxdobt.go) *`binary tree depth`*
* [107. Binary Tree Level Order Traversal II](solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go) *`binary tree;`* *`bfs`*
* [111. Minimum Depth of Binary Tree](solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go) *`binary tree;`* *`dfs`*
* [112. Path Sum](solutions/0112_path_sum/path_sum.go) *`binary tree;`* *`dfs`*
* [144. Binary Tree Preorder Traversal](solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go) *`binary tree;`* *`pre-order traversal`*
* [208. Implement Trie (Prefix Tree)](solutions/0208_implement_trie_prefix_tree/impltrie.go) *`trie`*
* [226. Invert Binary Tree](solutions/0226_invert_binary_tree/invert_binary_tree.go) *`binary tree`*
* [211. Add and Search Word - Data structure design](solutions/0211_add_and_search_word/add_and_search_word.go) *`trie`*
* [235. Lowest Common Ancestor of a Binary Search Tree](solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go) *`binary tree`*
* [236. Lowest Common Ancestor of a Binary Tree](solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go) *`binary tree`*
* [257. Binary Tree Paths](solutions/0257_binary_tree_paths/binary_tree_paths.go) *`binary tree`*
* [307. Range Sum Query - Mutable](solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut.go) *`segment tree`*
* [404. Sum of Left Leaves](solutions/0404_sum_of_left_leaves/sum_of_left_leaves.go) *`binary tree`*
* [437. Path Sum III](solutions/0437_path_sum_3/path_sum_3.go) *`binary tree`*
* [677. Map Sum Pairs](solutions/0677_map_sum_pairs/map_sum_pairs.go) *`trie`*
* [872. Leaf-Similar Trees](solutions/0872_leaf_similar_trees/leaf_similar_trees.go) *`binary tree`*
### Binary Search
* [33. Search in Rotated Sorted Array](solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go) *`array;`* *`binary search`*
* [34. Find First and Last Position of Element in Sorted Array](solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go) *`array;`* *`binary search`*
* [35. Search Insert Position](solutions/0035_search_insert_position/search_insert_position.go) *`array;`* *`binary search`*
* [69. Sqrt(x)](solutions/0069_sqrtx/sqrtx.go) *`math;`* *`binary search`*
* [153. Find Minimum in Rotated Sorted Array](solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go)
* [704. Binary Search](solutions/0704_binary_search/binary_search.go)
### Math
* [7. Reverse Integer](solutions/0007_reverse_integer/reverse_integer.go)
* [9. Palindrome Number](solutions/0009_palindrome_number/palindrome_number.go)
* [13. Roman to Integer](solutions/0013_roman_to_integer/roman_to_integer.go) *`string`*
* [66. Plus One](solutions/0066_plus_one/plus_one.go) *`array`*
* [150. Evaluate Reverse Polish Notation](solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go) *`stack`*
* [258. Add Digits](solutions/0258_add_digits/add_digits.go)
================================================
FILE: docs/_config.yml
================================================
theme: jekyll-theme-hacker
================================================
FILE: docs/index.md
================================================
## Welcome to GitHub Pages
You can use the [editor on GitHub](https://github.com/keep-in-practice/leetcode-go/edit/master/docs/index.md) to maintain and preview the content for your website in Markdown files.
Whenever you commit to this repository, GitHub Pages will run [Jekyll](https://jekyllrb.com/) to rebuild the pages in your site, from the content in your Markdown files.
### Markdown
Markdown is a lightweight and easy-to-use syntax for styling your writing. It includes conventions for
```markdown
Syntax highlighted code block
# Header 1
## Header 2
### Header 3
- Bulleted
- List
1. Numbered
2. List
**Bold** and _Italic_ and `Code` text
[Link](url) and 
```
For more details see [GitHub Flavored Markdown](https://guides.github.com/features/mastering-markdown/).
### Jekyll Themes
Your Pages site will use the layout and styles from the Jekyll theme you have selected in your [repository settings](https://github.com/keep-in-practice/leetcode-go/settings). The name of this theme is saved in the Jekyll `_config.yml` configuration file.
### Support or Contact
Having trouble with Pages? Check out our [documentation](https://docs.github.com/categories/github-pages-basics/) or [contact support](https://github.com/contact) and we’ll help you sort it out.
================================================
FILE: go.mod
================================================
module leetcode
go 1.13
================================================
FILE: solutions/0001_two_sum/twosum.go
================================================
/*
1. Two Sum
Source: https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
*/
package twosum
// Time complexity: O(n)
// Space complexity: O(n)
func twoSum(nums []int, target int) []int {
record := make(map[int]int)
for i, j := range nums {
complement := target - j
if res, ok := record[complement]; ok {
return []int{res, i}
}
record[j] = i
}
return []int{}
}
// brute force
// Time complexity: O(n^2)
// Space complexity: O(1)
func twoSum1(nums []int, target int) []int {
for i, j := range nums {
for k := i + 1; k < len(nums); k++ {
if nums[k]+j == target {
return []int{i, k}
}
}
}
return []int{}
}
================================================
FILE: solutions/0001_two_sum/twosum_test.go
================================================
package twosum
import (
"reflect"
"testing"
)
func TestTwoSum(t *testing.T) {
nums := []int{2, 7, 11, 15}
funcs := []func([]int, int) []int{twoSum, twoSum1}
for _, testFunc := range funcs {
if res := testFunc(nums, 9); !reflect.DeepEqual(res, []int{0, 1}) {
t.Error("Failed, two sum")
}
if res := testFunc(nums, 6); !reflect.DeepEqual(res, []int{}) {
t.Error("Failed, two sum")
}
}
}
================================================
FILE: solutions/0002_add_two_numbers/add_two_numbers.go
================================================
/*
2. Add Two Numbers
Source: https://leetcode.com/problems/add-two-numbers/
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
*/
package addtwonumbers
// ListNode is node of linked list
type ListNode struct {
Val int
Next *ListNode
}
// 解法一,暴力解法
func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
head := ListNode{Val: -1}
cur := &head
carry := 0
for l1 != nil && l2 != nil {
sum := l1.Val + l2.Val + carry
val := sum % 10
carry = sum / 10
node := ListNode{Val: val}
cur.Next = &node
cur = cur.Next
l1 = l1.Next
l2 = l2.Next
}
if carry == 0 {
if l1 != nil {
cur.Next = l1
}
if l2 != nil {
cur.Next = l2
}
return head.Next
}
for l1 != nil {
sum := l1.Val + carry
val := sum % 10
carry = sum / 10
node := ListNode{Val: val}
cur.Next = &node
cur = cur.Next
l1 = l1.Next
}
for l2 != nil {
sum := l2.Val + carry
val := sum % 10
carry = sum / 10
node := ListNode{Val: val}
cur.Next = &node
cur = cur.Next
l2 = l2.Next
}
for carry != 0 {
val := carry % 10
carry = carry / 10
node := ListNode{Val: val}
cur.Next = &node
cur = cur.Next
}
return head.Next
}
// 解法二,递归
func addTwoNumbers2(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil && l2 == nil {
return nil
} else if l1 == nil && l2 != nil {
return l2
} else if l1 != nil && l2 == nil {
return l1
}
sum := l1.Val + l2.Val
next := addTwoNumbers2(l1.Next, l2.Next)
if sum >= 10 {
carry := sum / 10
sum %= 10
next = addTwoNumbers2(next, &ListNode{Val: carry})
}
return &ListNode{Val: sum, Next: next}
}
================================================
FILE: solutions/0002_add_two_numbers/add_two_numbers_test.go
================================================
package addtwonumbers
import (
"os"
"reflect"
"testing"
)
func createSingleLinkedList(arr []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range arr {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
func TestAddTwoNumbers1(t *testing.T) {
testDatas := []struct {
name string
arg1 *ListNode
arg2 *ListNode
expected *ListNode
}{
{
name: "one",
arg1: createSingleLinkedList([]int{2, 4, 3}),
arg2: createSingleLinkedList([]int{5, 6, 4}),
expected: createSingleLinkedList([]int{7, 0, 8}),
},
{
name: "two",
arg1: createSingleLinkedList([]int{5}),
arg2: createSingleLinkedList([]int{5}),
expected: createSingleLinkedList([]int{0, 1}),
},
{
name: "three",
arg1: createSingleLinkedList([]int{1}),
arg2: createSingleLinkedList([]int{9, 9, 9}),
expected: createSingleLinkedList([]int{0, 0, 0, 1}),
},
{
name: "four",
arg1: createSingleLinkedList([]int{9, 9, 9}),
arg2: createSingleLinkedList([]int{1}),
expected: createSingleLinkedList([]int{0, 0, 0, 1}),
},
{
name: "five",
arg1: createSingleLinkedList([]int{4, 3, 1}),
arg2: createSingleLinkedList([]int{1}),
expected: createSingleLinkedList([]int{5, 3, 1}),
},
{
name: "six",
arg1: createSingleLinkedList([]int{1}),
arg2: createSingleLinkedList([]int{4, 3, 1}),
expected: createSingleLinkedList([]int{5, 3, 1}),
},
}
for _, testData := range testDatas {
t.Run(testData.name, func(t *testing.T) {
if result := addTwoNumbers1(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) {
t.Errorf("expected %v, got %v", testData.expected, result)
}
})
}
}
func TestAddTwoNumbers2(t *testing.T) {
testDatas := []struct {
name string
arg1 *ListNode
arg2 *ListNode
expected *ListNode
}{
{
name: "one",
arg1: createSingleLinkedList([]int{2, 4, 3}),
arg2: createSingleLinkedList([]int{5, 6, 4}),
expected: createSingleLinkedList([]int{7, 0, 8}),
},
{
name: "two",
arg1: createSingleLinkedList([]int{5}),
arg2: createSingleLinkedList([]int{5}),
expected: createSingleLinkedList([]int{0, 1}),
},
{
name: "three",
arg1: createSingleLinkedList([]int{1}),
arg2: createSingleLinkedList([]int{9, 9, 9}),
expected: createSingleLinkedList([]int{0, 0, 0, 1}),
},
{
name: "four",
arg1: createSingleLinkedList([]int{9, 9, 9}),
arg2: createSingleLinkedList([]int{1}),
expected: createSingleLinkedList([]int{0, 0, 0, 1}),
},
{
name: "five",
arg1: createSingleLinkedList([]int{4, 3, 1}),
arg2: createSingleLinkedList([]int{1}),
expected: createSingleLinkedList([]int{5, 3, 1}),
},
{
name: "six",
arg1: createSingleLinkedList([]int{1}),
arg2: createSingleLinkedList([]int{4, 3, 1}),
expected: createSingleLinkedList([]int{5, 3, 1}),
},
}
for _, testData := range testDatas {
t.Run(testData.name, func(t *testing.T) {
if result := addTwoNumbers2(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) {
t.Errorf("expected %v, got %v", testData.expected, result)
}
})
}
}
func TestMain(m *testing.M) {
os.Exit(m.Run())
}
================================================
FILE: solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go
================================================
/*
3. Longest Substring Without Repeating Characters
Source: https://leetcode.com/problems/longest-substring-without-repeating-characters/
Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
*/
package longestsubstringwithoutrepeatingcharacters
// Time complexity: O(n)
// Space complexity: O(n)
func lengthOfLongestSubstring(s string) int {
var (
start = 0
res = 0
lastOccurredRecord = make(map[rune]int)
)
for i, ch := range []rune(s) {
if lastIndex, ok := lastOccurredRecord[ch]; ok && lastIndex >= start {
start = lastIndex + 1
}
if i-start+1 > res {
res = i - start + 1
}
lastOccurredRecord[ch] = i
}
return res
}
================================================
FILE: solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters_test.go
================================================
package longestsubstringwithoutrepeatingcharacters
import "testing"
func TestLengthOfLongestSubstring(t *testing.T) {
testData := []string{
"abcabcbb",
"bbbbb",
"pwwkew",
}
expectedData := []int{3, 1, 3}
for index, data := range testData {
if res := lengthOfLongestSubstring(data); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0004_median_of_two_sorted_arrays/motsa.go
================================================
/*
4. Median of Two Sorted Arrays
https://leetcode.com/problems/median-of-two-sorted-arrays/
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
*/
// time: 2018-12-29
package motsa
import "leetcode/utils"
// binary search
// time complexity: O(log(m+n)), where m is nums1's length, n is nums2's length.
// space complexity: O(log(m+n))
func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
var (
m = len(nums1)
n = len(nums2)
)
if 0 == m && 0 == n {
panic("nums1 and nums2 cannot be both empty.")
}
if 0 == m {
return float64(nums2[n>>1]+nums2[n>>1-(n+1)%2]) / 2
}
if 0 == n {
return float64(nums1[m>>1]+nums1[m>>1-(m+1)%2]) / 2
}
var (
left = (m + n + 1) >> 1
right = (m + n + 2) >> 1
)
return float64(findKth(nums1, 0, nums2, 0, left)+findKth(nums1, 0, nums2, 0, right)) / 2
}
/*
使用二分法, 在两个有序数组中找到第k个元素。
使用两个变量i和j分别来标记数组nums1和nums2的起始位置。
1. 当某一个数组的起始位置大于等于其数组长度时,说明其所有数字均已经被淘汰了,
相当于一个空数组了,那么实际上就变成了在另一个数组中找数字,直接就可以找出来了
2. 如果K=1的话,那么我们只要比较nums1和nums2的起始位置i和j上的数字就可以了。
3. 对K二分,分别在nums1和nums2中查找第K/2个元素,注意这里由于两个数组的长度不定,所以有可能某个数组没有第K/2个数字,
需要先检查一下,数组中到底存不存在第k/2个数字,如果存在就取出来,反之赋值为整型最大值,
比较两个数组的第k/2个数字,如果第一个数组的第k/2个数字小的话,说明我们要找的数字肯定不再第一个数组的前k/2个数字中,
所以舍弃掉,将第一个数组的起始位置移动k/2,并且此时k也减去k/2(舍弃了k/2个之后,只需要在剩下的里面寻找k-k/2就可以了)
*/
func findKth(nums1 []int, i int, nums2 []int, j int, k int) int {
if i >= len(nums1) {
return nums2[j+k-1]
}
if j >= len(nums2) {
return nums1[i+k-1]
}
if 1 == k {
if nums1[i] < nums2[j] {
return nums1[i]
}
return nums2[j]
}
var (
midVal1, midVal2 int
)
if i+k/2-1 < len(nums1) {
midVal1 = nums1[i+k/2-1]
} else {
midVal1 = utils.MaxInt
}
if j+k/2-1 < len(nums2) {
midVal2 = nums2[j+k/2-1]
} else {
midVal2 = utils.MaxInt
}
if midVal1 < midVal2 {
return findKth(nums1, i+k/2, nums2, j, k-k/2)
}
return findKth(nums1, i, nums2, j+k/2, k-k/2)
}
================================================
FILE: solutions/0004_median_of_two_sorted_arrays/motsa_test.go
================================================
package motsa
import (
"testing"
)
func TestFindMedianSortedArrays(t *testing.T) {
type arg struct {
nums1 []int
nums2 []int
}
testCases := []arg{
{nums1: []int{1, 3}, nums2: []int{2}},
{nums1: []int{1, 2}, nums2: []int{3, 4}},
{nums1: []int{}, nums2: []int{3, 4, 5}},
{nums1: []int{4, 5, 6}, nums2: []int{}},
{nums1: []int{2, 3, 4, 5}, nums2: []int{1}},
{nums1: []int{1}, nums2: []int{2, 3, 4, 5, 6, 7}},
{nums1: []int{1, 2, 3, 4, 5, 6, 8, 9, 23, 34}, nums2: []int{7}},
}
expected := []float64{2, 2.5, 4, 5, 3, 4, 6}
for index, data := range testCases {
if res := findMedianSortedArrays(data.nums1, data.nums2); res != expected[index] {
t.Errorf("expected %f, got %f", expected[index], res)
}
}
defer func() {
if err := recover(); err == nil || err != "nums1 and nums2 cannot be both empty." {
t.Errorf("expected err: nums1 and nums2 cannot be both empty.")
}
}()
findMedianSortedArrays([]int{}, []int{})
}
================================================
FILE: solutions/0007_reverse_integer/reverse_integer.go
================================================
/*
7. Reverse Integer
https://leetcode.com/problems/reverse-integer/
Given a 32-bit signed integer, reverse digits of an integer.
*/
// time: 2018-12-29
package reverseinteger
// time complexity: O(log 10 x ) = O(log x)
// space complexity: O(1)
func reverse(x int) int {
if 0 == x {
return x
}
isPositive := true
if x < 0 {
isPositive = false
x *= -1
}
res := 0
for x > 0 {
res = res*10 + x%10
x /= 10
}
if !isPositive {
res *= -1
}
if res < -1<<31 || res > (1<<31)-1 {
return 0
}
return res
}
================================================
FILE: solutions/0007_reverse_integer/reverse_integer_test.go
================================================
package reverseinteger
import "testing"
func TestReverse(t *testing.T) {
testCases := []int{
123, -123, 10, 0, 12239999999999,
}
expected := []int{321, -321, 1, 0, 0}
for index, data := range testCases {
if res := reverse(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0009_palindrome_number/palindrome_number.go
================================================
/*
9. Palindrome Number
https://leetcode.com/problems/palindrome-number/
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
*/
// time: 2018-12-30
package palindromenumber
// Time complexity: O(log 10 (n))
// Space complexity : O(1)
func isPalindrome(x int) bool {
var (
y int
z = x
)
for x > 0 {
y = y*10 + x%10
x /= 10
}
return y == z
}
================================================
FILE: solutions/0009_palindrome_number/palindrome_number_test.go
================================================
package palindromenumber
import "testing"
func TestIsPalindrome(t *testing.T) {
testCases := []int{121, -121, 10, 0}
expected := []bool{true, false, false, true}
for index, data := range testCases {
if res := isPalindrome(data); res != expected[index] {
t.Errorf("expected %t, got %t", expected[index], res)
}
}
}
================================================
FILE: solutions/0011_container_with_most_water/container_with_most_water.go
================================================
/*
11. Container With Most Water
https://leetcode.com/problems/container-with-most-water/
Given n non-negative integers a1, a2, ..., an ,
where each represents a point at coordinate (i, ai).
n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0).
Find two lines, which together with x-axis forms a container,
such that the container contains the most water.
Note: You may not slant the container and n is at least 2.
*/
// time: 2018-12-26
package containerwithmostwater
import "leetcode/utils"
// time complexity: O(n)
// space complexity: O(1)
func maxArea(height []int) int {
var (
water int
l int
r = len(height) - 1
)
for l < r {
h := utils.CalcMinInt(height[l], height[r])
water = utils.CalcMaxInt(water, (r-l)*h)
for height[l] <= h && l < r {
l++
}
for height[r] <= h && l < r {
r--
}
}
return water
}
// time complexity: O(n^2)
// space complexity: O(n)
func maxArea1(height []int) int {
n := len(height)
if n >= 0 && n < 2 {
return 0
}
memo := make([]int, n)
memo[1] = 1 * utils.CalcMinInt(height[0], height[1])
for i := 2; i < n; i++ {
for j := i - 1; j >= 0; j-- {
memo[i] = utils.CalcMaxInt(memo[i], (i-j)*utils.CalcMinInt(height[i], height[j]))
}
}
return utils.CalcMaxInt(memo...)
}
// time complexity: O(n^2)
// space complexity: O(1)
func maxArea2(height []int) int {
res := 0
for i := 0; i < len(height); i++ {
for j := i + 1; j < len(height); j++ {
tmp := (j - i) * utils.CalcMinInt(height[i], height[j])
if tmp > res {
res = tmp
}
}
}
return res
}
================================================
FILE: solutions/0011_container_with_most_water/container_with_most_water_test.go
================================================
package containerwithmostwater
import "testing"
func TestMaxArea(t *testing.T) {
testCases := [][]int{
{1, 8, 6, 2, 5, 4, 8, 3, 7},
{},
{1},
{1, 2},
{2, 3, 5, 7, 8, 9, 5, 3, 2},
}
expected := []int{49, 0, 0, 1, 20}
for index, data := range testCases {
if res := maxArea(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
func TestMaxArea1(t *testing.T) {
testCases := [][]int{
{1, 8, 6, 2, 5, 4, 8, 3, 7},
{},
{1},
{1, 2},
{2, 3, 5, 7, 8, 9, 5, 3, 2},
}
expected := []int{49, 0, 0, 1, 20}
for index, data := range testCases {
if res := maxArea1(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
func TestMaxArea2(t *testing.T) {
testCases := [][]int{
{1, 8, 6, 2, 5, 4, 8, 3, 7},
{},
{1},
{1, 2},
{2, 3, 5, 7, 8, 9, 5, 3, 2},
}
expected := []int{49, 0, 0, 1, 20}
for index, data := range testCases {
if res := maxArea2(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0013_roman_to_integer/roman_to_integer.go
================================================
/*
13. Roman to Integer
https://leetcode.com/problems/roman-to-integer/
*/
// time: 2018-12-31
package rti
// time complexity: O(n)
// space complexity: O(1)
func romanToInt(s string) int {
if 0 == len(s) {
return 0
}
digits := map[byte]int{'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
sum := digits[s[len(s)-1]]
for i := len(s) - 1; i > 0; i-- {
cur := digits[s[i]]
pre := digits[s[i-1]]
if cur > pre {
sum -= pre
} else {
sum += pre
}
}
return sum
}
================================================
FILE: solutions/0013_roman_to_integer/roman_to_integer_test.go
================================================
package rti
import "testing"
func TestRomanToInt(t *testing.T) {
testCases := []string{
"III",
"IV",
"IX",
"LVIII",
"MCMXCIV",
"",
}
expected := []int{3, 4, 9, 58, 1994, 0}
for index, s := range testCases {
if res := romanToInt(s); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0014_longest_common_prefix/lcp.go
================================================
/*
14. Longest Common Prefix
https://leetcode.com/problems/longest-common-prefix/
Write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
*/
// time: 2018-12-31
package lcp
// time complexity: O(len(strs) * max len of string)
// space complexity: O(1)
func longestCommonPrefix(strs []string) string {
if 0 == len(strs) {
return ""
}
res := ""
for i := 0; i < len(strs[0]); i++ {
c := strs[0][i]
for j := 1; j < len(strs); j++ {
if i >= len(strs[j]) || strs[j][i] != c {
return res
}
}
res += string(c)
}
return res
}
================================================
FILE: solutions/0014_longest_common_prefix/lcp_test.go
================================================
package lcp
import "testing"
func TestLongestCommonPrefix(t *testing.T) {
testCases := [][]string{
{"flower", "flow", "flight"},
{"dog", "racecar", "car"},
{},
{""},
}
expected := []string{
"fl",
"",
"",
"",
}
for index, strs := range testCases {
if res := longestCommonPrefix(strs); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
================================================
FILE: solutions/0015_3Sum/3sum.go
================================================
/*
15. 3Sum
https://leetcode.com/problems/3sum/
*/
// time: 2019-03-01
package threesum
import "sort"
// time complexity: O(n^2)
func threeSum(nums []int) [][]int {
sort.Ints(nums)
var res [][]int
for i := 0; i < len(nums)-2; i++ {
if nums[i] > 0 {
break
}
if i > 0 && nums[i] == nums[i-1] {
continue
}
for l, r := i+1, len(nums)-1; l < r; {
if l > i+1 && nums[l] == nums[l-1] {
l++
continue
}
if r < len(nums)-1 && nums[r] == nums[r+1] {
r--
continue
}
switch sum := nums[i] + nums[l] + nums[r]; {
case sum < 0:
l++
case sum > 0:
r--
default:
res = append(res, []int{nums[i], nums[l], nums[r]})
l++
r--
}
}
}
return res
}
================================================
FILE: solutions/0015_3Sum/3sum_test.go
================================================
package threesum
import (
"reflect"
"testing"
)
func TestThreeSum(t *testing.T) {
testData := [][]int{
{-1, 0, 1, 2, -6, -4},
{-7, 3, -7, 3, 4, 5, 6, 6, 4},
}
expected := [][][]int{
{{-1, 0, 1}},
{{-7, 3, 4}},
}
for index, nums := range testData {
if res := threeSum(nums); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
================================================
FILE: solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go
================================================
/*
17. Letter Combinations of a Phone Number
Source: https://leetcode.com/problems/letter-combinations-of-a-phone-number/
Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.
A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
Example:
Input: "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.
*/
package lettercombinationsofaphonenumber
var (
letterMap = []string{
" ",
"",
"abc",
"def",
"ghi",
"jkl",
"mno",
"pqrs",
"tuv",
"wxyz",
}
res []string
)
// Time complexity: O(2^n)
// Space complexity: O(n)
func letterCombinations(digits string) []string {
res = []string{}
if digits == "" {
return res
}
findCombinations(digits, 0, "")
return res
}
func findCombinations(digits string, index int, s string) {
if index == len(digits) {
res = append(res, s)
return
}
ch := digits[index]
letters := letterMap[ch-'0']
for _, i := range letters {
findCombinations(digits, index+1, s+string(i))
}
return
}
================================================
FILE: solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number_test.go
================================================
package lettercombinationsofaphonenumber
import (
"reflect"
"testing"
)
func TestLetterCombinations(t *testing.T) {
testData := []string{
"23",
"",
}
expectedData := [][]string{
{"ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"},
{},
}
for index, digits := range testData {
if res := letterCombinations(digits); !reflect.DeepEqual(res, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go
================================================
/*
19. Remove Nth Node From End of List
https://leetcode.com/problems/remove-nth-node-from-end-of-list/
Given a linked list, remove the n-th node from the end of list and return its head.
*/
// time: 2018-12-31
package rnthnfeol
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n)
// space complexity: O(1)
func removeNthFromEnd(head *ListNode, n int) *ListNode {
if n <= 0 {
return head
}
dummy := &ListNode{}
dummy.Next = head
var (
p = dummy
q = dummy
)
for i := 0; i < n; i++ {
q = q.Next
}
for q.Next != nil {
p = p.Next
q = q.Next
}
p.Next = p.Next.Next
return dummy.Next
}
================================================
FILE: solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list_test.go
================================================
package rnthnfeol
import (
"reflect"
"testing"
)
func TestRemoveNthFromEnd(t *testing.T) {
type arg struct {
head *ListNode
n int
}
testCase := []arg{
{head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), n: 2},
{head: createSingleLinkedList([]int{1, 2, 3, 4, 5}), n: 0},
}
expected := []*ListNode{
createSingleLinkedList([]int{1, 2, 3, 5}),
createSingleLinkedList([]int{1, 2, 3, 4, 5}),
}
for index, data := range testCase {
if res := removeNthFromEnd(data.head, data.n); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected")
}
}
}
func createSingleLinkedList(arr []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range arr {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
================================================
FILE: solutions/0020_valid_parentheses/valid_parentheses.go
================================================
/*
20. Valid Parentheses
Source: https://leetcode.com/problems/valid-parentheses/
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
1. Open brackets must be closed by the same type of brackets.
2. Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()"
Output: true
Example 2:
Input: "()[]{}"
Output: true
Example 3:
Input: "(]"
Output: false
Example 4:
Input: "([)]"
Output: false
Example 5:
Input: "{[]}"
Output: true
*/
package validparentheses
// Time complexity: O(n)
// Space complexity: O(n)
func isValid(s string) bool {
var (
stacks []rune
mapping = map[rune]rune{')': '(', ']': '[', '}': '{'}
)
for _, char := range s {
if char == ')' || char == '}' || char == ']' {
var topElement rune
if len(stacks) > 0 {
topElement = stacks[len(stacks)-1]
stacks = stacks[:len(stacks)-1]
} else {
topElement = '#'
}
if mapping[char] != topElement {
return false
}
} else {
stacks = append(stacks, char)
}
}
return len(stacks) == 0
}
================================================
FILE: solutions/0020_valid_parentheses/valid_parentheses_test.go
================================================
package validparentheses
import "testing"
func TestIsValid(t *testing.T) {
testData := []string{"()", "(((((())))))", "()()()()", "(((((((()", "((()(())))", "", ")(", "}{", "][", "(][)"}
expectedData := []bool{true, true, true, false, true, true, false, false, false, false}
for i, s := range testData {
result := isValid(s)
if result != expectedData[i] {
t.Error("测试不通过")
}
}
}
================================================
FILE: solutions/0021_merge_two_sorted_lists/mergeTwoLists.go
================================================
/*
21. Merge Two Sorted Lists
Source: https://leetcode.com/problems/merge-two-sorted-lists/
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
*/
package mergetwolists
// ListNode is node of linked list
type ListNode struct {
Val int
Next *ListNode
}
// Recursion
// Time complexity: O(len(l1)+len(l2))
// Space complexity: O(len(l1)+len(l2))
func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
if l1 == nil && l2 == nil {
return nil
}
if l1 == nil {
return l2
}
if l2 == nil {
return l1
}
if l1.Val < l2.Val {
l1.Next = mergeTwoLists(l1.Next, l2)
return l1
}
l2.Next = mergeTwoLists(l1, l2.Next)
return l2
}
================================================
FILE: solutions/0021_merge_two_sorted_lists/mergeTwoLists_test.go
================================================
package mergetwolists
import (
"reflect"
"testing"
)
func createSingleLinkedList(arr []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range arr {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
func TestMergeTwoLists(t *testing.T) {
testDatas := []struct {
name string
arg1 *ListNode
arg2 *ListNode
expected *ListNode
}{
{
name: "one",
arg1: createSingleLinkedList([]int{1, 3, 5}),
arg2: createSingleLinkedList([]int{2, 4, 6}),
expected: createSingleLinkedList([]int{1, 2, 3, 4, 5, 6}),
},
{
name: "two",
arg1: createSingleLinkedList([]int{1}),
arg2: createSingleLinkedList([]int{2, 4, 6}),
expected: createSingleLinkedList([]int{1, 2, 4, 6}),
},
{
name: "three",
arg1: nil,
arg2: nil,
expected: nil,
},
{
name: "four",
arg1: createSingleLinkedList([]int{2, 4, 6}),
arg2: createSingleLinkedList([]int{1}),
expected: createSingleLinkedList([]int{1, 2, 4, 6}),
},
}
for _, testData := range testDatas {
t.Run(testData.name, func(t *testing.T) {
if result := mergeTwoLists(testData.arg1, testData.arg2); !reflect.DeepEqual(result, testData.expected) {
t.Errorf("mergeTwoLists() = %v, expected %v", result, testData.expected)
}
})
}
}
================================================
FILE: solutions/0023_merge_k_sorted_lists/mksl.go
================================================
/*
23. Merge k Sorted Lists
https://leetcode.com/problems/merge-k-sorted-lists/
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
// time: 2019-01-02
package mksl
import (
"sort"
)
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// heap
// time complexity: O(n log n), where n is len of all lists, the main complexity is sort.
// space complexity: O(n), where n is len of all lists.
func mergeKLists(lists []*ListNode) *ListNode {
for i := 0; i < len(lists); {
if lists[i] == nil {
lists = append(lists[0:i], lists[i+1:]...)
} else {
i++
}
}
if 0 == len(lists) {
return nil
}
head := &ListNode{}
cur := head
for len(lists) > 0 {
for i := (len(lists) - 1) / 2; i >= 0; i-- {
siftUp(lists, len(lists), i)
}
cur.Next = &ListNode{Val: lists[0].Val}
cur = cur.Next
lists[0] = lists[0].Next
if lists[0] == nil {
lists = lists[1:]
}
}
return head.Next
}
// build heap
func siftUp(lists []*ListNode, n int, k int) {
for 2*k+1 < n {
j := 2*k + 1
if j+1 < n && lists[j+1].Val < lists[j].Val {
j = j + 1
}
if lists[k].Val < lists[j].Val {
break
}
lists[j], lists[k] = lists[k], lists[j]
k = j
}
}
// brute force
// time complexity: O(n log n), where n is len of all lists, the main complexity is sort.
// space complexity: O(2n), where n is len of all lists.
func mergeKLists1(lists []*ListNode) *ListNode {
nodes := make([]int, 0)
head := &ListNode{}
pointer := head
for _, j := range lists {
for {
if j != nil {
nodes = append(nodes, j.Val)
j = j.Next
} else {
break
}
}
}
sort.Ints(nodes)
for _, j := range nodes {
pointer.Next = &ListNode{Val: j}
pointer = pointer.Next
}
return head.Next
}
================================================
FILE: solutions/0023_merge_k_sorted_lists/mksl_test.go
================================================
package mksl
import (
"reflect"
"testing"
)
func TestMergeKLists(t *testing.T) {
testCases := [][]*ListNode{
{
createSingleList([]int{1, 4, 5}),
createSingleList([]int{2, 3, 4}),
createSingleList([]int{4, 6}),
},
{
createSingleList([]int{}),
createSingleList([]int{4, 5}),
createSingleList([]int{}),
},
{
createSingleList([]int{}),
createSingleList([]int{}),
createSingleList([]int{}),
},
{
createSingleList([]int{1, 4, 5}),
createSingleList([]int{1, 3, 4}),
createSingleList([]int{2, 6}),
},
}
expected := []*ListNode{
createSingleList([]int{1, 2, 3, 4, 4, 4, 5, 6}),
createSingleList([]int{4, 5}),
nil,
createSingleList([]int{1, 1, 2, 3, 4, 4, 5, 6}),
}
for index, lists := range testCases {
if res := mergeKLists(lists); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
func TestMergeKLists1(t *testing.T) {
testCases := [][]*ListNode{
{
createSingleList([]int{1, 4, 5}),
createSingleList([]int{1, 3, 4}),
createSingleList([]int{2, 6}),
},
{
createSingleList([]int{}),
createSingleList([]int{4, 5}),
createSingleList([]int{}),
},
{
createSingleList([]int{}),
createSingleList([]int{}),
createSingleList([]int{}),
},
}
expected := []*ListNode{
createSingleList([]int{1, 1, 2, 3, 4, 4, 5, 6}),
createSingleList([]int{4, 5}),
nil,
}
for index, lists := range testCases {
if res := mergeKLists1(lists); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
func createSingleList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range nums {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
================================================
FILE: solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go
================================================
/*
24. Swap Nodes in Pairs
https://leetcode.com/problems/swap-nodes-in-pairs/
Given a linked list, swap every two adjacent nodes and return its head.
*/
// time: 2019-01-02
package swapnodesinpairs
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n/2), where n is len of linked list.
// space complexity: O(1)
func swapPairs(head *ListNode) *ListNode {
dummy := &ListNode{}
dummy.Next = head
cur := dummy
for cur.Next != nil && cur.Next.Next != nil {
node1 := cur.Next
node2 := node1.Next
node3 := node2.Next
node2.Next = node1
node1.Next = node3
cur.Next = node2
cur = node1
}
return dummy.Next
}
================================================
FILE: solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs_test.go
================================================
package swapnodesinpairs
import (
"reflect"
"testing"
)
func TestSwapPairs(t *testing.T) {
head := createSingleList([]int{1, 2, 3, 4})
expected := createSingleList([]int{2, 1, 4, 3})
if res := swapPairs(head); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
func createSingleList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range nums {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
================================================
FILE: solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go
================================================
/*
25. Reverse Nodes in k-Group
Source: https://leetcode.com/problems/reverse-nodes-in-k-group/
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
Note:
Only constant extra memory is allowed.
You may not alter the values in the list's nodes, only nodes itself may be changed.
*/
package reversenodesinkgroup
// ListNode is node of linked list
type ListNode struct {
Val int
Next *ListNode
}
func reverseKGroup(head *ListNode, k int) *ListNode {
if head == nil || head.Next == nil || k < 2 {
return head
}
p := new(ListNode)
s := new(ListNode)
l := k
p.Next = head
head = p
s = p
for s != nil && k != 0 {
s = s.Next
k--
}
for s != nil {
reverse(&p, &s)
k = l
for s != nil && k != 0 {
s = s.Next
k--
}
}
return head.Next
}
func reverse(p **ListNode, s **ListNode) {
var tmp *ListNode
prev := (*p).Next
tail := (*p).Next
flag := (*s).Next
(*p).Next = nil
for prev != flag {
tmp = (*p).Next
(*p).Next = prev
prev = prev.Next
(*p).Next.Next = tmp
}
tail.Next = prev
*p = tail
*s = tail
}
================================================
FILE: solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group_test.go
================================================
package reversenodesinkgroup
import (
"reflect"
"testing"
)
func createSingleLinkedList(arr []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range arr {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
func TestReverseKGroup(t *testing.T) {
type args struct {
head *ListNode
k int
}
tests := []struct {
name string
args args
expected *ListNode
}{
{
name: "one",
args: args{
head: createSingleLinkedList([]int{1, 2, 3, 4, 5}),
k: 2,
},
expected: createSingleLinkedList([]int{2, 1, 4, 3, 5}),
},
{
name: "two",
args: args{
head: createSingleLinkedList([]int{1, 2, 3, 4, 5}),
k: 3,
},
expected: createSingleLinkedList([]int{3, 2, 1, 4, 5}),
},
{
name: "three",
args: args{
head: createSingleLinkedList([]int{1}),
k: 2,
},
expected: createSingleLinkedList([]int{1}),
},
}
for _, data := range tests {
t.Run(data.name, func(t *testing.T) {
if result := reverseKGroup(data.args.head, data.args.k); !reflect.DeepEqual(result, data.expected) {
t.Errorf("reverseKGroup() = %v, expected %v", result, data.expected)
}
})
}
}
================================================
FILE: solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go
================================================
/*
26. Remove Duplicates from Sorted Array
https://leetcode.com/problems/remove-duplicates-from-sorted-array/
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
*/
// time: 2018-12-20
package rdfsa
// double index
// time complexity: O(n)
// space complexity: O(1)
func removeDuplicates(nums []int) int {
n := len(nums)
if 0 == n {
return n
}
var (
res = 1
i = 1
index = nextDifferentCharacterIndex(nums, 1) // 下一个不重复的地址
)
for index < n {
res++
nums[i] = nums[index]
i++
index = nextDifferentCharacterIndex(nums, index+1)
}
return res
}
func nextDifferentCharacterIndex(nums []int, p int) int {
for ; p < len(nums); p++ {
if nums[p] != nums[p-1] {
break
}
}
return p
}
================================================
FILE: solutions/0026_remove_duplicates_from_sorted_array/rdfsa_test.go
================================================
package rdfsa
import "testing"
func TestRemoveDuplicates(t *testing.T) {
// removeDuplicates([]int{0, 0, 1, 1, 1, 2, 2, 3, 3, 4})
testCases := [][]int{
{1, 1, 2},
{0, 0, 1, 1, 1, 2, 2, 3, 3, 4},
{},
}
expected := []int{2, 5, 0}
for index, data := range testCases {
if res := removeDuplicates(data); expected[index] != res {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0027_remove_element/remove_element.go
================================================
/*
27. Remove Element
https://leetcode.com/problems/remove-element/
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
*/
// time: 2018-12-20
package removeelement
// two pointers
// time complexity: O(n)
// space complexity: O(1)
func removeElement(nums []int, val int) int {
x := 0
for j := 0; j < len(nums); j++ {
if nums[j] != val {
if x != j {
nums[x] = nums[j]
}
x++
}
}
return x
}
/*
func removeElement1(nums []int, val int) int {
var (
l int
r = len(nums)
)
for l < r {
if nums[l] == val {
r--
nums[l] = nums[r]
} else {
l++
}
}
return r
}
*/
================================================
FILE: solutions/0027_remove_element/remove_element_test.go
================================================
package removeelement
import "testing"
func TestRemoveElement(t *testing.T) {
nums := []int{0, 1, 2, 2, 3, 0, 4, 2}
val := 2
expected := 5
if res := removeElement(nums, val); res != expected {
t.Errorf("expected %d, got %d", expected, res)
}
}
================================================
FILE: solutions/0028_implement_strstr/implement_strstr.go
================================================
/*
28. Implement strStr()
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.
clarification:
For the purpose of this problem, we will return 0 when needle is an empty string.
*/
// time: 2019-01-02
package implstr
// time complexity: O( (m-n+1)*n ), where m is len(haystack), n is len(needle)
// space complexity: O(1)
func strStr(haystack string, needle string) int {
if 0 == len(needle) {
return 0
}
for i, j := 0, 0; i <= len(haystack)-len(needle); i++ {
for j = 0; j < len(needle); j++ {
if haystack[i+j] != needle[j] {
break
}
}
if len(needle) == j {
return i
}
}
return -1
}
================================================
FILE: solutions/0028_implement_strstr/implement_strstr_test.go
================================================
package implstr
import "testing"
func TestStrStr(t *testing.T) {
type arg struct {
haystack string
needle string
}
testCases := []arg{
{haystack: "hello", needle: "ll"},
{haystack: "aaaaa", needle: "bba"},
{haystack: "hello"},
}
expected := []int{2, -1, 0}
for index, data := range testCases {
if res := strStr(data.haystack, data.needle); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go
================================================
/*
33. Search in Rotated Sorted Array
https://leetcode.com/problems/search-in-rotated-sorted-array/
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
Your algorithm's runtime complexity must be in the order of O(log n).
*/
// time: 2018-12-20
package searchinrotatedsortedarray
// binary search
/*
问题分析:
二分情况分为三种:
1.mid在pivot左边,即mid左边部分是有序的。
nums[mid] >= nums[l] && nums[mid] > nums[r]
此时,只需要比较target是否在左边有序部分。
2.mid在pivot右边,并且包含pivot,即mid右边是有序的。
nums[mid] < nums[l] && nums[mid] <= nums[r],
此时,只需要比较target是否在右边有序部分。
3. 整个array是有序的,
nums[mid] >= nums[l] &&nums[mid] <= nums[r]
放在第一和第二中情况中处理都可以。
*/
// time complexity: O(logn)
// space complexity: O(1)
func search(nums []int, target int) int {
var (
l int
r = len(nums) - 1
)
for l <= r {
mid := l + (r-l)/2
if target == nums[mid] {
return mid
}
if nums[mid] >= nums[l] && nums[mid] > nums[r] {
if target >= nums[l] && target < nums[mid] {
r = mid - 1
} else {
l = mid + 1
}
} else {
if target > nums[mid] && target <= nums[r] {
l = mid + 1
} else {
r = mid - 1
}
}
}
return -1
}
================================================
FILE: solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array_test.go
================================================
package searchinrotatedsortedarray
import "testing"
func TestSearch(t *testing.T) {
type arg struct {
nums []int
target int
}
testCases := []arg{
{nums: []int{4, 5, 6, 7, 0, 1, 2}, target: 0},
{nums: []int{4, 5, 6, 7, 0, 1, 2}, target: 3},
{nums: []int{}, target: 2},
{nums: []int{4}, target: 4},
{nums: []int{4, 5, 6, 7, 0}, target: 0},
{nums: []int{9, 7}, target: 7},
{nums: []int{1, 3}, target: 3},
{nums: []int{4, 5, 6, 7, 8, 1, 2}, target: 5},
}
expected := []int{4, -1, -1, 0, 4, 1, 1, 1}
for index, data := range testCases {
if res := search(data.nums, data.target); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go
================================================
/*
34. Find First and Last Position of Element in Sorted Array
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
*/
// time: 2018-12-20
package findfirstandlastpositionofelementinsortedarray
// binary search
// time complexity: O(logn)
// space complexity: O(1)
func searchRange(nums []int, target int) []int {
lowerIndex := firstOccurance(nums, target)
first := -1
if lowerIndex != len(nums) && target == nums[lowerIndex] {
first = lowerIndex
}
upperIndex := lastOccurance(nums, target)
last := -1
if upperIndex == len(nums) && len(nums) > 0 && target == nums[len(nums)-1] {
last = len(nums) - 1
} else if upperIndex != len(nums) && upperIndex > 0 && target == nums[upperIndex-1] {
last = upperIndex - 1
}
return []int{first, last}
}
func firstOccurance(nums []int, target int) int {
var (
l int
r = len(nums)
)
for l != r { // 夹逼思想
mid := l + (r-l)/2
if nums[mid] < target {
l = mid + 1
} else {
r = mid
}
}
return l
}
func lastOccurance(nums []int, target int) int {
var (
l int
r = len(nums)
)
for l != r {
mid := l + (r-l)/2
if nums[mid] <= target {
l = mid + 1
} else {
r = mid
}
}
return l
}
// double index scan
// Time complexity: O(n)
// Space complexity: O(1)
func searchRange1(nums []int, target int) []int {
var (
l int
r = len(nums) - 1
)
for l <= r {
flag := false
if nums[l] != target {
l++
flag = true
}
if nums[r] != target {
r--
flag = true
}
if !flag {
break
}
}
if r < l {
return []int{-1, -1}
}
return []int{l, r}
}
// binary search + linear scan
// Time complexity: O(logn) ~ O(n)
// Space complexity: O(1)
func searchRange2(nums []int, target int) []int {
var (
l int
r = len(nums) - 1
tmp = -1
)
for l <= r {
mid := l + (r-l)/2
if nums[mid] == target {
tmp = mid
break
}
if nums[mid] < target {
l = mid + 1
} else {
r = mid - 1
}
}
if -1 == tmp {
return []int{-1, -1}
}
l = tmp
r = tmp
for true {
if l > 0 && nums[l-1] == target {
l--
} else {
break
}
}
for true {
if r < len(nums)-1 && target == nums[r+1] {
r++
} else {
break
}
}
return []int{l, r}
}
================================================
FILE: solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array_test.go
================================================
package findfirstandlastpositionofelementinsortedarray
import (
"reflect"
"runtime"
"testing"
)
func TestSearchRange(t *testing.T) {
type arg struct {
nums []int
target int
}
testCases := []arg{
{
nums: []int{5, 7, 7, 8, 8, 10},
target: 8,
},
{
nums: []int{5, 7, 7, 8, 8, 10},
target: 6,
},
{
nums: []int{1},
target: 1,
},
{
nums: []int{},
target: 0,
},
{
nums: []int{2, 2},
target: 2,
},
{
nums: []int{1},
target: 0,
},
}
expected := [][]int{
{3, 4},
{-1, -1},
{0, 0},
{-1, -1},
{0, 1},
{-1, -1},
}
testFuncs := []func([]int, int) []int{
searchRange,
searchRange1,
searchRange2,
}
for _, testFunc := range testFuncs {
for index, testData := range testCases {
if res := testFunc(testData.nums, testData.target); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("function %s, expected %v, got %v", runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name(), expected[index], res)
}
}
}
}
================================================
FILE: solutions/0035_search_insert_position/search_insert_position.go
================================================
/*
35. Search Insert Position
https://leetcode.com/problems/search-insert-position/
Given a sorted array and a target value,
return the index if the target is found.
If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
*/
// time: 2019-01-02
package sip
// binary search
// time complexity: O( log n )
// space complexity: O(1)
func searchInsert(nums []int, target int) int {
var (
l int
r = len(nums) - 1
)
for l <= r {
mid := l + (r-l)/2
if target == nums[mid] {
return mid
}
if target < nums[mid] {
r = mid - 1
} else {
l = mid + 1
}
}
return l
}
================================================
FILE: solutions/0035_search_insert_position/search_insert_position_test.go
================================================
package sip
import "testing"
func TestSearchInsert(t *testing.T) {
testCases := [][]int{
{1, 3, 5, 6},
{1, 3, 5, 6},
{1, 3, 5, 6},
{1, 3, 5, 6},
}
targets := []int{5, 2, 7, 0}
expected := []int{2, 1, 4, 0}
for index, nums := range testCases {
if res := searchInsert(nums, targets[index]); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0048_rotate_image/rotate_image.go
================================================
/*
48. Rotate Image
https://leetcode.com/problems/rotate-image/
You are given an n x n 2D matrix representing an image.
Rotate the image by 90 degrees (clockwise).
Note:
You have to rotate the image in-place,
which means you have to modify the input 2D matrix directly.
DO NOT allocate another 2D matrix and do the rotation.
*/
// time: 2019-01-02
package ri
// time complexity: O(n^2)
// space complexity: O(1)
func rotate(matrix [][]int) {
/*
[
[1,2,3],
[4,5,6],
[7,8,9]
]
*/
n := len(matrix)
for i := 0; i < n; i++ {
for j := i + 1; j < n; j++ {
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
}
}
/*
[
[1,4,7],
[2,5,8],
[3,6,9]
]
*/
for i := 0; i < n; i++ {
for j := 0; j < n/2; j++ {
matrix[i][j], matrix[i][n-1-j] = matrix[i][n-1-j], matrix[i][j]
}
}
/*
[
[7,4,1],
[8,5,2],
[9,6,3]
]
*/
}
================================================
FILE: solutions/0048_rotate_image/rotate_image_test.go
================================================
package ri
import (
"reflect"
"testing"
)
func TestRotate(t *testing.T) {
matrix := [][]int{
{5, 1, 9, 11},
{2, 4, 8, 10},
{13, 3, 6, 7},
{15, 14, 12, 16},
}
expected := [][]int{
{15, 13, 2, 5},
{14, 3, 4, 1},
{12, 6, 8, 9},
{16, 7, 10, 11},
}
if rotate(matrix); !reflect.DeepEqual(matrix, expected) {
t.Errorf("expected %v, got %v", expected, matrix)
}
}
================================================
FILE: solutions/0053_maximum_subarray/maximum_subarray.go
================================================
/*
53. Maximum Subarray
https://leetcode.com/problems/maximum-subarray/
Given an integer array nums,
find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
*/
// time: 2019-01-02
package maximumsubarray
import (
"fmt"
"math"
)
// time complexity: O(n)
// space complexity: O(1)
func maxSubArray(nums []int) int {
var (
max = math.MinInt32
sum int
start, end, f int
)
for i, j := range nums {
sum += j
if sum > max {
if f != 0 {
start = f + 1
f = 0
}
max = sum
end = i
}
if sum < 0 {
f = i
sum = 0
}
}
fmt.Printf("start index is %d, end index is %d\n", start, end)
return max
}
================================================
FILE: solutions/0053_maximum_subarray/maximum_subarray_test.go
================================================
package maximumsubarray
import "testing"
func TestMaxSubarray(t *testing.T) {
nums := []int{-2, 1, -3, 4, -1, 2, 1, -5, 4}
expected := 6
if res := maxSubArray(nums); res != expected {
t.Errorf("expected %d, got %d", expected, res)
}
}
================================================
FILE: solutions/0058_length_of_last_word/len_of_last_word.go
================================================
/*
58. Length of Last Word
https://leetcode.com/problems/length-of-last-word/
Given a string s consists of upper/lower-case alphabets and empty space characters ' ',
return the length of last word in the string.
If the last word does not exist, return 0.
Note: A word is defined as a character sequence consists of non-space characters only.
*/
// time: 2019-01-02
package lenoflastword
// time complexity: O(n)
// space complexity: O(1)
func lengthOfLastWord(s string) int {
var (
n = len(s)
cur = n - 1
)
for cur >= 0 {
if n-1 == cur && s[cur] == 32 {
cur--
n--
continue
}
if s[cur] != 32 {
cur--
} else {
break
}
}
return n - cur - 1
}
================================================
FILE: solutions/0058_length_of_last_word/len_of_last_word_test.go
================================================
package lenoflastword
import "testing"
func TestLengthOfLastWord(t *testing.T) {
s := "hello world "
expected := 5
if res := lengthOfLastWord(s); res != expected {
t.Errorf("expected %d, got %d", expected, res)
}
}
================================================
FILE: solutions/0061_rotate_list/rotate_list.go
================================================
/*
61. Rotate List
Source: https://leetcode.com/problems/rotate-list/
Given a linked list, rotate the list to the right by k places, where k is non-negative.
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
rotate 1 steps to the right: 2->0->1->NULL
Explanation:
rotate 2 steps to the right: 1->2->0->NULL
otate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
*/
package rotatelist
// ListNode is node of linked list
type ListNode struct {
Val int
Next *ListNode
}
func rotateRight(head *ListNode, k int) *ListNode {
if k == 0 || head == nil || head.Next == nil {
return head
}
var (
listSize int
count int
p = head
rotateNode = head
)
for p != nil && count < k {
p = p.Next
listSize++
count++
}
if p == nil {
k = k % listSize
if k == 0 {
return head
}
p = head
for count = 0; count < k; count++ {
p = p.Next
}
}
for p.Next != nil {
rotateNode = rotateNode.Next
p = p.Next
}
p.Next = head
head = rotateNode.Next
rotateNode.Next = nil
return head
}
================================================
FILE: solutions/0061_rotate_list/rotate_list_test.go
================================================
package rotatelist
import (
"reflect"
"testing"
)
func createSingleLinkedList(arr []int) *ListNode {
head := &ListNode{}
cur := head
for _, j := range arr {
cur.Next = &ListNode{Val: j}
cur = cur.Next
}
return head.Next
}
func TestRotateList(t *testing.T) {
testDatas := []struct {
name string
arg *ListNode
k int
expected *ListNode
}{
{
name: "one",
arg: createSingleLinkedList([]int{1, 2, 3, 4}),
k: 2,
expected: createSingleLinkedList([]int{3, 4, 1, 2}),
},
{
name: "two",
arg: createSingleLinkedList([]int{1, 2, 3}),
k: 3,
expected: createSingleLinkedList([]int{1, 2, 3}),
},
{
name: "three",
arg: createSingleLinkedList([]int{1, 2, 3}),
k: 5,
expected: createSingleLinkedList([]int{2, 3, 1}),
},
{
name: "four",
arg: createSingleLinkedList([]int{1, 2, 3}),
k: 0,
expected: createSingleLinkedList([]int{1, 2, 3}),
},
{
name: "five",
arg: nil,
k: 0,
expected: nil,
},
{
name: "four",
arg: createSingleLinkedList([]int{1}),
k: 5,
expected: createSingleLinkedList([]int{1}),
},
}
for _, testData := range testDatas {
t.Run(testData.name, func(t *testing.T) {
if result := rotateRight(testData.arg, testData.k); !reflect.DeepEqual(result, testData.expected) {
t.Errorf("expected %v, got %v", testData.expected, result)
}
})
}
}
================================================
FILE: solutions/0062_unique_paths/unique_paths.go
================================================
/*
62. Unique Paths
Source: https://leetcode.com/problems/unique-paths/
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28
*/
package uniquepaths
// recursion
/*
func uniquePaths(m int, n int) int {
if m == 1 || n == 1 {
return 1
}
return uniquePaths(m, n-1) + uniquePaths(m-1, n)
}
*/
// memory search
/*
func uniquePaths(m int, n int) int {
memo := make([][]int, m) // memo[i][j]存储(i+1)*(j+1)grid的路径数量
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
memo[i] = append(memo[i], -1)
}
}
return calcPaths(m, n, memo)
}
func calcPaths(m int, n int, memo [][]int) int {
if memo[m-1][n-1] != -1 {
return memo[m-1][n-1]
}
if m == 1 || n == 1 {
memo[m-1][n-1] = 1
return 1
}
res := calcPaths(m, n-1, memo) + calcPaths(m-1, n, memo)
memo[m-1][n-1] = res
return res
}
*/
func uniquePaths(m int, n int) int {
memo := make([][]int, m) // memo[i][j]存储(i+1)*(j+1)grid的路径数量
for i := 0; i < m; i++ {
memo[i] = append(memo[i], 1)
}
for i := 1; i < n; i++ {
memo[0] = append(memo[0], 1)
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
memo[i] = append(memo[i], memo[i-1][j]+memo[i][j-1])
}
}
return memo[m-1][n-1]
}
================================================
FILE: solutions/0062_unique_paths/unique_paths_test.go
================================================
package uniquepaths
import "testing"
func TestUniquePaths(t *testing.T) {
testData := [][2]int{
{3, 2},
{51, 9},
{9, 9},
}
expectedData := []int{3, 1916797311, 12870}
for index, data := range testData {
if res := uniquePaths(data[0], data[1]); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0063_unique_paths_2/unique_paths2.go
================================================
/*
63. Unique Paths II
Source: https://leetcode.com/problems/unique-paths-ii/
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
Note: m and n will be at most 100.
Example 1:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right
*/
package uniquepaths2
// recursion
/*
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m := len(obstacleGrid)
n := len(obstacleGrid[0])
cur := 1
if m == 1 {
for i := 0; i < n; i++ {
if obstacleGrid[0][i] == 1 {
cur = 0
}
}
return cur
}
cur = 1
if n == 1 {
for i := 0; i < m; i++ {
if obstacleGrid[i][0] == 1 {
cur = 0
}
}
return cur
}
if obstacleGrid[m-1][n-1] == 1 {
return 0
}
obstacleGridCut := make([][]int, m)
for i := range obstacleGridCut {
for j := 0; j < n-1; j++ {
obstacleGridCut[i] = append(obstacleGridCut[i], obstacleGrid[i][j])
}
}
return uniquePathsWithObstacles(obstacleGrid[:m-1]) + uniquePathsWithObstacles(obstacleGridCut)
}
*/
// memory search
/*
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m := len(obstacleGrid)
n := len(obstacleGrid[0])
memo := make([][]int, m)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
memo[i] = append(memo[i], -1)
}
}
cur := 1
for i := 0; i < m; i++ {
if obstacleGrid[i][0] == 1 {
cur = 0
}
memo[i][0] = cur
}
cur = 1
for j := 0; j < n; j++ {
if obstacleGrid[0][j] == 1 {
cur = 0
}
memo[0][j] = cur
}
return calcUniquePaths(obstacleGrid, m-1, n-1, memo)
}
func calcUniquePaths(obstacleGrid [][]int, m int, n int, memo [][]int) int {
if memo[m][n] != -1 {
return memo[m][n]
}
if obstacleGrid[m][n] == 1 {
return 0
}
res := calcUniquePaths(obstacleGrid, m-1, n, memo) + calcUniquePaths(obstacleGrid, m, n-1, memo)
memo[m][n] = res
return res
}
*/
// dynamic programming
func uniquePathsWithObstacles(obstacleGrid [][]int) int {
m := len(obstacleGrid)
n := len(obstacleGrid[0])
memo := make([][]int, m)
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
memo[i] = append(memo[i], -1)
}
}
cur := 1
for i := 0; i < m; i++ {
if obstacleGrid[i][0] == 1 {
cur = 0
}
memo[i][0] = cur
}
cur = 1
for j := 0; j < n; j++ {
if obstacleGrid[0][j] == 1 {
cur = 0
}
memo[0][j] = cur
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if obstacleGrid[i][j] == 1 {
memo[i][j] = 0
} else {
memo[i][j] = memo[i-1][j] + memo[i][j-1]
}
}
}
return memo[m-1][n-1]
}
================================================
FILE: solutions/0063_unique_paths_2/unique_paths2_test.go
================================================
package uniquepaths2
import "testing"
func TestUniquePaths2(t *testing.T) {
testData := [][][]int{
{
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
},
{
{0, 0, 0},
{0, 1, 0},
{0, 0, 0},
{0, 1, 0},
},
{
{1},
},
{
{1, 0},
},
}
expectedData := []int{2, 2, 0, 0}
for index, data := range testData {
if res := uniquePathsWithObstacles(data); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0064_minimum_path_sum/minimum_path_sum.go
================================================
/*
64. Minimum Path Sum
source: https://leetcode.com/problems/minimum-path-sum/
Description
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
Example:
Input:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
Output: 7
Explanation: Because the path 1→3→1→1→1 minimizes the sum.
*/
package minimumpathsum
// recursion dfs
/*
func minPathSum(grid [][]int) int {
if len(grid) == 0{
return 0
}
MaxUint:= ^uint(0)
MaxInt := int(MaxUint >> 1)
result := MaxInt
dfs(0,0,0, grid, &result)
return result
}
func dfs(x int, y int, sum int, grid [][]int, result *int) {
m := len(grid)
n := len(grid[0])
sum += grid[x][y]
if x+1 < m && y+1 < n {
dfs(x+1, y, sum, grid, result)
dfs(x, y+1, sum, grid, result)
}
if x +1 == m && y+1 < n {
dfs(x, y+1, sum, grid, result)
}
if y+1 == n && x+1 < m {
dfs(x+1, y, sum, grid, result)
}
if x+1 == m && y+1 == n {
if sum < *result {
*result = sum
}
return
}
}*/
// dynamic programming
func minPathSum(grid [][]int) int {
if len(grid) == 0 {
return 0
}
m := len(grid)
n := len(grid[0])
dp := make([][]int, m)
dp[0] = append(dp[0], grid[0][0])
for i := 1; i < m; i++ {
dp[i] = append(dp[i], grid[i][0]+dp[i-1][0])
}
for i := 1; i < n; i++ {
dp[0] = append(dp[0], grid[0][i]+dp[0][i-1])
}
for i := 1; i < m; i++ {
for j := 1; j < n; j++ {
if dp[i-1][j] < dp[i][j-1] {
dp[i] = append(dp[i], grid[i][j]+dp[i-1][j])
} else {
dp[i] = append(dp[i], grid[i][j]+dp[i][j-1])
}
}
}
return dp[m-1][n-1]
}
================================================
FILE: solutions/0064_minimum_path_sum/minimum_path_sum_test.go
================================================
package minimumpathsum
import "testing"
func TestMininumPathSum(t *testing.T) {
testData := [][][]int{
{
{1, 3, 1},
{1, 5, 1},
{4, 2, 1},
},
{
{3, 8, 6, 0, 5, 9, 9, 6, 3, 4, 0, 5, 7, 3, 9, 3},
{0, 9, 2, 5, 5, 4, 9, 1, 4, 6, 9, 5, 6, 7, 3, 2},
{8, 2, 2, 3, 3, 3, 1, 6, 9, 1, 1, 6, 6, 2, 1, 9},
{1, 3, 6, 9, 9, 5, 0, 3, 4, 9, 1, 0, 9, 6, 2, 7},
{8, 6, 2, 2, 1, 3, 0, 0, 7, 2, 7, 5, 4, 8, 4, 8},
{4, 1, 9, 5, 8, 9, 9, 2, 0, 2, 5, 1, 8, 7, 0, 9},
{6, 2, 1, 7, 8, 1, 8, 5, 5, 7, 0, 2, 5, 7, 2, 1},
{8, 1, 7, 6, 2, 8, 1, 2, 2, 6, 4, 0, 5, 4, 1, 3},
{9, 2, 1, 7, 6, 1, 4, 3, 8, 6, 5, 5, 3, 9, 7, 3},
{0, 6, 0, 2, 4, 3, 7, 6, 1, 3, 8, 6, 9, 0, 0, 8},
{4, 3, 7, 2, 4, 3, 6, 4, 0, 3, 9, 5, 3, 6, 9, 3},
{2, 1, 8, 8, 4, 5, 6, 5, 8, 7, 3, 7, 7, 5, 8, 3},
{0, 7, 6, 6, 1, 2, 0, 3, 5, 0, 8, 0, 8, 7, 4, 3},
{0, 4, 3, 4, 9, 0, 1, 9, 7, 7, 8, 6, 4, 6, 9, 5},
{6, 5, 1, 9, 9, 2, 2, 7, 4, 2, 7, 2, 2, 3, 7, 2},
{7, 1, 9, 6, 1, 2, 7, 0, 9, 6, 6, 4, 4, 5, 1, 0},
{3, 4, 9, 2, 8, 3, 1, 2, 6, 9, 7, 0, 2, 4, 2, 0},
{5, 1, 8, 8, 4, 6, 8, 5, 2, 4, 1, 6, 2, 2, 9, 7},
},
{},
}
expectedData := []int{7, 83, 0}
for index, data := range testData {
if mininumPathSum := minPathSum(data); expectedData[index] != mininumPathSum {
t.Errorf("expected %d, got %d", expectedData[index], mininumPathSum)
}
}
}
================================================
FILE: solutions/0066_plus_one/plus_one.go
================================================
/*
66. Plus One
https://leetcode.com/problems/plus-one/
Given a non-empty array of digits representing a non-negative integer,
plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list,
and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
*/
// time: 2019-01-02
package plusone
// time complexity: O(n)
// space complexity: O(1)
func plusOne(digits []int) []int {
var (
carry = 1
index = len(digits) - 1
)
for index >= 0 {
sum := carry + digits[index]
digits[index] = sum % 10
carry = sum / 10
index--
}
if carry > 0 {
digits = append(digits, 0)
copy(digits[1:], digits[0:])
digits[0] = carry
}
return digits
}
================================================
FILE: solutions/0066_plus_one/plus_one_test.go
================================================
package plusone
import (
"reflect"
"testing"
)
func TestPlusOne(t *testing.T) {
digits := []int{9, 9, 9, 9}
expected := []int{1, 0, 0, 0, 0}
if res := plusOne(digits); !reflect.DeepEqual(expected, res) {
t.Errorf("expected %v, got %v", expected, res)
}
}
================================================
FILE: solutions/0067_add_binary/add_binary.go
================================================
/*
67. Add Binary
https://leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example:
Input: a = "11", b = "1"
Output: "100"
*/
// time: 2018-12-19
package addbinary
import (
"strconv"
)
// Time complexity: O( max( len(a), len(b) ) )
// Space complexity: O(1)
func addBinary(a string, b string) string {
var (
lenA = len(a)
lenB = len(b)
carry int
res = ""
)
for lenA > 0 && lenB > 0 {
tmp := int(a[lenA-1]-'0') + int(b[lenB-1]-'0') + carry
res = strconv.Itoa(tmp%2) + res
carry = tmp / 2
lenA--
lenB--
}
if lenA == 0 {
for lenB > 0 {
tmp := int(b[lenB-1]-'0') + carry
res = strconv.Itoa(tmp%2) + res
carry = tmp / 2
lenB--
}
}
if lenB == 0 {
for lenA > 0 {
tmp := int(a[lenA-1]-'0') + carry
res = strconv.Itoa(tmp%2) + res
carry = tmp / 2
lenA--
}
}
if carry == 1 {
res = strconv.Itoa(carry) + res
}
return res
}
================================================
FILE: solutions/0067_add_binary/add_binary_test.go
================================================
package addbinary
import (
"testing"
)
func TestAddBinary(t *testing.T) {
type arg struct {
a string
b string
}
testCases := []arg{
{
a: "11",
b: "1",
},
{
b: "11",
a: "1",
},
}
expected := []string{
"100", "100",
}
for index, data := range testCases {
if res := addBinary(data.a, data.b); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
================================================
FILE: solutions/0069_sqrtx/sqrtx.go
================================================
/*
69. Sqrt(x)
https://leetcode.com/problems/sqrtx/
Implement int sqrt(int x).
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
*/
// time: 2018-12-20
package sqrtx
// binary search
// time complexity: O(logn)
// space complexity: O(1)
func mySqrt(x int) int {
var (
l int
r = x // 在0~x范围内寻找平凡根
)
for l <= r {
mid := l + (r-l)>>1 //位运算更高效
if mid*mid == x {
return mid
}
if mid*mid < x {
if (mid+1)*(mid+1) > x {
return mid // 返回整数部分
}
l = mid + 1
} else {
r = mid - 1
}
}
return x // 不会执行,如果x为负数,会执行到此处,但是不符合题目要求。
}
================================================
FILE: solutions/0069_sqrtx/sqrtx_test.go
================================================
package sqrtx
import "testing"
func TestMySqrt(t *testing.T) {
testCases := []int{66, 99, 9}
expected := []int{8, 9, 3}
for index, data := range testCases {
if res := mySqrt(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0070_climbing_stairs/climbing_stairs.go
================================================
/*
70. Climbing Stairs
source:https://leetcode.com/problems/climbing-stairs/
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
*/
package climbingstairs
// recursion
/*
func climbStairs(n int) int {
// if n == 1 {
// return 1
// }
// if n == 2 {
// return 2
// }
//
if n == 1 || n == 0 {
return 1
}
return climbStairs(n-1) + climbStairs(n-2)
}
*/
// memory search
/*
func climbStairs(n int) int {
var memo []int
for i := 0; i <= n; i++ {
memo = append(memo, -1)
}
return calcWays(n, memo)
}
func calcWays(n int, memo []int) int {
if n == 0 || n == 1 {
return 1
}
if memo[n] == -1 {
memo[n] = calcWays(n-1, memo) + calcWays(n-2, memo)
}
return memo[n]
}
*/
// dynamic programming
func climbStairs(n int) int {
var memo = []int{1, 1}
for i := 2; i <= n; i++ {
memo = append(memo, memo[i-1]+memo[i-2])
}
return memo[n]
}
================================================
FILE: solutions/0070_climbing_stairs/climbing_stairs_test.go
================================================
package climbingstairs
import "testing"
func TestClimbStairs(t *testing.T) {
testDatas := []int{0, 1, 2, 3, 34}
expected := []int{1, 1, 2, 3, 9227465}
for i, data := range testDatas {
if steps := climbStairs(data); steps != expected[i] {
t.Errorf("expected %d, got %d", expected[i], steps)
}
}
}
================================================
FILE: solutions/0075_sort_colors/sort_colors.go
================================================
/*
75. Sort Colors
https://leetcode.com/problems/sort-colors/
Given an array with n objects colored red, white or blue,
sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
*/
// time: 2018-12-21
package sortcolors
// 计数排序
// time complexity: O(n)
// space complexity: O(1)
func sortColorsCountSort(nums []int) {
var count = [3]int{}
for _, num := range nums {
count[num]++
}
index := 0
for i, j := range count {
for k := 0; k < j; k++ {
nums[index] = i
index++
}
}
}
// quick sort 3 ways
// time complexity: O(n)
// space complexity: O(1)
func sortColorsQuickSort3Ways(nums []int) {
var (
zero = -1
two = len(nums)
)
for i := 0; i < two; {
if 1 == nums[i] {
i++
} else if 2 == nums[i] {
two--
nums[i], nums[two] = nums[two], nums[i]
} else { // nums[i] == 0
zero++
nums[i], nums[zero] = nums[zero], nums[i]
i++
}
}
}
================================================
FILE: solutions/0075_sort_colors/sort_colors_test.go
================================================
package sortcolors
import (
"reflect"
"testing"
)
func TestSortColorsCountSort(t *testing.T) {
nums := []int{2, 0, 2, 1, 1, 0}
expected := []int{0, 0, 1, 1, 2, 2}
sortColorsCountSort(nums)
if !reflect.DeepEqual(nums, expected) {
t.Errorf("expected %v, got %v", expected, nums)
}
}
func TestSortColorsQuickSort3Ways(t *testing.T) {
nums := []int{2, 0, 2, 1, 1, 0}
expected := []int{0, 0, 1, 1, 2, 2}
sortColorsQuickSort3Ways(nums)
if !reflect.DeepEqual(nums, expected) {
t.Errorf("expected %v, got %v", expected, nums)
}
}
================================================
FILE: solutions/0076_minimum_window_substring/minimum_window_substring.go
================================================
/*
76. Minimum Window Substring
https://leetcode.com/problems/minimum-window-substring/
Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).
Example:
Input: S = "ADOBECODEBANC", T = "ABC"
Output: "BANC"
Note:
1. If there is no such window in S that covers all characters in T, return the empty string "".
2. If there is such window, you are guaranteed that there will always be only one unique minimum window in S.
*/
package minimumwindowsubstring
import "leetcode/utils"
/*
使用滑动窗口解决这一问题,使用map或者slice统计T字符串中的字母的个数,之后,开始遍历S字符串,对于S中遍历到
的每一个字母,都在map或者slice中的对应个数减一,如果减一后仍然大于等于0,说明当前遍历到的字母是T中的字母,
使用计数器count,使其加一,当count和T串字母个数相等时,说明此时的窗口已经包含了T串中的所有字母,此时记录
一下字串和字串长度,
然后开始收缩左边界,由于我们遍历的时候,对应值减了1,所以此时去除字母的时候,就要把减去的1加回来,
此时如果加1后的值大于0了,说明此时我们少了一个T中的字母,那么count值就要减1了,然后移动左边界left。
*/
// sliding window
// Time complexity: O(n)
// Space complexity: O(128) = O(1)
func minWindow(s string, t string) string {
var (
res string
letterCount = make([]int, 128)
left int
count int
minLen = utils.MaxInt
)
for i := 0; i < len(t); i++ {
letterCount[t[i]]++
}
for i := 0; i < len(s); i++ {
if letterCount[s[i]]--; letterCount[s[i]] >= 0 {
count++
}
for count == len(t) {
if minLen > i-left+1 {
minLen = i - left + 1
res = s[left : minLen+left]
}
if letterCount[s[left]]++; letterCount[s[left]] > 0 {
count--
}
left++
}
}
return res
}
================================================
FILE: solutions/0076_minimum_window_substring/minimum_window_substring_test.go
================================================
package minimumwindowsubstring
import "testing"
func TestMinWindow(t *testing.T) {
s := "ADOBECODEBANC"
l := "ABC"
expected := "BANC"
if res := minWindow(s, l); res != expected {
t.Errorf("expected %s, got %s", expected, res)
}
}
================================================
FILE: solutions/0077_combinations/combinations.go
================================================
/*
77. Combinations
https://leetcode.com/problems/combinations/
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
*/
// time: 2019-01-04
package combinations
// backtracking
// time complexity: O(n^k)
// space complexity: O(k)
func combine(n int, k int) [][]int {
if n <= 0 || k <= 0 || k > n {
return [][]int{}
}
res := make([][]int, 0)
c := make([]int, 0, k)
generateCombinations(n, k, 1, c, &res)
return res
}
// 求解C(n,k), 当前已经找到的组合存储在c中,需要从start开始搜索新元素。
func generateCombinations(n, k, start int, c []int, res *[][]int) {
if len(c) == k {
cpy := make([]int, k)
copy(cpy, c)
*res = append(*res, cpy)
return
}
// 回朔法剪枝。
// 还有k - len(c)个空位,所以, [i...n]中至少要有k - len(c)个元素
// i最多为n-(k-len(c))+1
for i := start; i <= n-(k-len(c))+1; i++ {
c = append(c, i)
generateCombinations(n, k, i+1, c, res)
c = c[:len(c)-1]
}
}
================================================
FILE: solutions/0077_combinations/combinations_test.go
================================================
package combinations
import (
"reflect"
"testing"
)
func TestCombine(t *testing.T) {
type arg struct {
n, k int
}
testCases := []arg{
{n: 0, k: 2},
{n: 2, k: 0},
{n: 1, k: 5},
{n: 4, k: 2},
}
expected := [][][]int{
{},
{},
{},
{{1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4}, {3, 4}},
}
for index, data := range testCases {
if res := combine(data.n, data.k); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
================================================
FILE: solutions/0079_word_search/word_search.go
================================================
/*
79. Word Search
https://leetcode.com/problems/word-search/
Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell,
where "adjacent" cells are those horizontally or vertically neighboring.
The same letter cell may not be used more than once.
*/
// 2019-01-04
package wordsearch
var (
d = [4][2]int{{-1, 0}, {0, 1}, {1, 0}, {0, -1}}
m, n int
visited [][]bool
)
// backtracking
// time complexity: O(m*n*m*n)
// space complexity: O(m*n)
func exist(board [][]byte, word string) bool {
m = len(board)
n = len(board[0])
visited = make([][]bool, m)
for i := 0; i < m; i++ {
visited[i] = make([]bool, n)
}
for i := 0; i < len(board); i++ {
for j := 0; j < len(board[i]); j++ {
if searchWord(board, word, 0, i, j) {
return true
}
}
}
return false
}
func searchWord(board [][]byte, word string, index, startX, startY int) bool {
if len(word)-1 == index {
return board[startX][startY] == word[index]
}
if board[startX][startY] == word[index] {
visited[startX][startY] = true
// 从startX, startY开始,向四个方向寻找
for i := 0; i < 4; i++ {
newX := startX + d[i][0]
newY := startY + d[i][1]
if inArea(newX, newY) && !visited[newX][newY] && searchWord(board, word, index+1, newX, newY) {
return true
}
}
visited[startX][startY] = false
}
return false
}
func inArea(x, y int) bool {
return x >= 0 && x < m && y >= 0 && y < n
}
================================================
FILE: solutions/0079_word_search/word_search_test.go
================================================
package wordsearch
import "testing"
func TestExist(t *testing.T) {
board := [][]byte{
{'A', 'B', 'C', 'E'},
{'S', 'F', 'C', 'S'},
{'A', 'D', 'E', 'E'},
}
testCases := []string{
"ABCCED",
"SEE",
"ABCB",
}
expected := []bool{true, true, false}
for index, word := range testCases {
if res := exist(board, word); res != expected[index] {
t.Errorf("expected %t, got %t", expected[index], res)
}
}
}
================================================
FILE: solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go
================================================
/*
80. Remove Duplicates from Sorted Array II
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
Given a sorted array nums, remove the duplicates in-place such that
duplicates appeared at most twice and return the new length.
Do not allocate extra space for another array, you must do this
by modifying the input array in-place with O(1) extra memory.
*/
// time: 2018-12-21
package rdfsa2
// double index
// time complexity: O(n)
// space complexity: O(1)
func removeDuplicates(nums []int) int {
n := len(nums)
if 0 == n || 1 == n {
return n
}
var (
res = 2
i = 2
index = nextDifferentCharacterIndex(nums, i, 2) // 寻找下一个满足条件的下标
)
for index < n {
res++
nums[i] = nums[index]
i++
index = nextDifferentCharacterIndex(nums, i, index+1)
}
return res
}
func nextDifferentCharacterIndex(nums []int, j int, p int) int {
for ; p < len(nums); p++ {
if nums[j-1] == nums[j-2] && nums[p] != nums[j-1] || nums[j-1] != nums[j-2] {
break
}
}
return p
}
================================================
FILE: solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2_test.go
================================================
package rdfsa2
import "testing"
func TestRemoveDuplicates(t *testing.T) {
testCases := [][]int{
{1, 1, 1, 2, 2, 3},
{1, 2, 2},
{0, 0, 1, 1, 1, 1, 2, 3, 3},
{},
{1},
{2, 2},
{2, 2, 2},
}
expected := []int{5, 3, 7, 0, 1, 2, 2}
for index, data := range testCases {
if res := removeDuplicates(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go
================================================
/*
82. Remove Duplicates from Sorted List II
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/
Given a sorted linked list, delete all nodes that have duplicate numbers,
leaving only distinct numbers from the original list.
*/
// time: 2019-01-04
package rdfsl
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n)
// space complexity: O(1)
func deleteDuplicates(head *ListNode) *ListNode {
dummyHead := &ListNode{}
dummyHead.Next = head
pre := dummyHead
cur := head
for cur != nil && cur.Next != nil {
if cur.Val == cur.Next.Val {
num := cur.Val
for cur != nil && cur.Val == num {
cur = cur.Next
}
pre.Next = cur
} else {
pre = cur
cur = cur.Next
}
}
return dummyHead.Next
}
================================================
FILE: solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl_test.go
================================================
package rdfsl
import (
"reflect"
"testing"
)
func TestDeleteDuplicates(t *testing.T) {
testCases := []*ListNode{
createSingleLinkedList([]int{1, 2, 3, 3, 4, 4, 5}),
createSingleLinkedList([]int{1, 1, 1, 2, 3}),
}
expected := []*ListNode{
createSingleLinkedList([]int{1, 2, 5}),
createSingleLinkedList([]int{2, 3}),
}
for index, head := range testCases {
if res := deleteDuplicates(head); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
func createSingleLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
================================================
FILE: solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go
================================================
/*
83. Remove Duplicates from Sorted List
https://leetcode.com/problems/remove-duplicates-from-sorted-list/
Given a sorted linked list, delete all duplicates such that each element appear only once.
*/
package rdfsl
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n)
// space complexity: O(1)
func deleteDuplicates(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
var (
pre = head
cur = head.Next
)
for cur != nil {
if cur.Val == pre.Val {
pre.Next = cur.Next
cur = cur.Next
} else {
pre = cur
cur = cur.Next
}
}
return head
}
================================================
FILE: solutions/0083_remove_duplicates_from_sorted_list/rdfsl_test.go
================================================
package rdfsl
import (
"reflect"
"testing"
)
func createSingleLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
func TestDeleteDuplicates(t *testing.T) {
testCases := []*ListNode{
createSingleLinkedList([]int{1, 1, 2}),
createSingleLinkedList([]int{1, 1, 2, 3, 3}),
nil,
}
expected := []*ListNode{
createSingleLinkedList([]int{1, 2}),
createSingleLinkedList([]int{1, 2, 3}),
nil,
}
for index, head := range testCases {
if res := deleteDuplicates(head); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
================================================
FILE: solutions/0086_partition_list/partition_list.go
================================================
/*
86. Partition List
https://leetcode.com/problems/partition-list/
Given a linked list and a value x,
partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
*/
// time: 2019-01-04
package partitionlist
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n)
// space complexity: O(1)
func partition(head *ListNode, x int) *ListNode {
var (
dummyHead1 = &ListNode{}
dummyHead2 = &ListNode{}
cur1 = dummyHead1
cur2 = dummyHead2
)
for cur := head; cur != nil; {
if cur.Val < x {
cur1.Next = cur
cur1 = cur1.Next
cur = cur.Next
cur1.Next = nil
} else {
cur2.Next = cur
cur2 = cur2.Next
cur = cur.Next
cur2.Next = nil
}
}
cur1.Next = dummyHead2.Next
return dummyHead1.Next
}
================================================
FILE: solutions/0086_partition_list/partition_list_test.go
================================================
package partitionlist
import (
"reflect"
"testing"
)
func createSingleLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
func TestDeleteDuplicates(t *testing.T) {
testCase := createSingleLinkedList([]int{1, 4, 3, 2, 5, 2})
expected := createSingleLinkedList([]int{1, 2, 2, 4, 3, 5})
x := 3
if res := partition(testCase, x); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
================================================
FILE: solutions/0088_merge_sorted_array/msa.go
================================================
/*
88. Merge Sorted Array
https://leetcode.com/problems/merge-sorted-array/
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note:
1. The number of elements initialized in nums1 and nums2 are m and n respectively.
2. You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.
*/
// time: 2018-12-21
package msa
// standard merge process in merge sort
// time complexity: O(n+m)
// space complexity: O(1)
func merge(nums1 []int, m int, nums2 []int, n int) {
for i := n + m - 1; i >= n; i-- {
nums1[i] = nums1[i-n]
}
var (
i = n // pointer for nums1 [n, n+m)
j = 0 // pointer for nums2 [0, n)
k = 0 // pointer for merged nums1 [0, n+m)
)
for k < n+m {
if i >= n+m {
nums1[k] = nums2[j]
k++
j++
} else if j >= n {
break
// nums1[k] = nums1[i]
// k++
// i++
} else if nums1[i] < nums2[j] {
nums1[k] = nums1[i]
i++
k++
} else { //nums1[i] >= nums2[j]
nums1[k] = nums2[j]
k++
j++
}
}
}
================================================
FILE: solutions/0088_merge_sorted_array/msa_test.go
================================================
package msa
import (
"reflect"
"testing"
)
func TestMerge(t *testing.T) {
type arg struct {
nums1 []int
m int
nums2 []int
n int
}
testCases := []arg{
{nums1: []int{1, 2, 3, 7, 0, 0, 0}, m: 4, nums2: []int{2, 5, 6}, n: 3},
{nums1: []int{2, 5, 6, 0, 0, 0}, m: 3, nums2: []int{7, 8, 9}, n: 3},
}
expected := [][]int{{1, 2, 2, 3, 5, 6, 7}, {2, 5, 6, 7, 8, 9}}
for index, data := range testCases {
if merge(data.nums1, data.m, data.nums2, data.n); !reflect.DeepEqual(expected[index], data.nums1) {
t.Errorf("expected %v, got %v", expected[index], data.nums1)
}
}
}
================================================
FILE: solutions/0092_reverse_linked_list_2/reverse_linked_list2.go
================================================
/*
92. Reverse Linked List II
https://leetcode.com/problems/reverse-linked-list-ii/
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
*/
// time: 2019-01-04
package reverselinkedlist2
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n-m)
// space complexity: O(1)
func reverseBetween(head *ListNode, m, n int) *ListNode {
var (
dummy = &ListNode{}
p = dummy
s = p
)
dummy.Next = head
// 1 ≤ m ≤ n ≤ length of list.
for s != nil && n > 0 {
s = s.Next
n--
}
for s != nil && m > 1 {
p = p.Next
m--
}
reverse(&p, &s)
return dummy.Next
}
func reverse(p, s **ListNode) {
var (
tmp *ListNode
prev = (*p).Next
tail = (*p).Next
flag = (*s).Next
)
(*p).Next = nil
for prev != flag {
tmp = (*p).Next
(*p).Next = prev
prev = prev.Next
(*p).Next.Next = tmp
}
tail.Next = prev
/*
1->2->3->4->5
1->3->2->4->5
1->4->3->2->5
1->5->4->3->2
*/
}
================================================
FILE: solutions/0092_reverse_linked_list_2/reverse_linked_list2_test.go
================================================
package reverselinkedlist2
import (
"reflect"
"testing"
)
func createSingleList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
func TestReverseBetween(t *testing.T) {
head := createSingleList([]int{1, 2, 3, 4, 5})
m := 2
n := 4
expected := createSingleList([]int{1, 4, 3, 2, 5})
if res := reverseBetween(head, m, n); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
================================================
FILE: solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go
================================================
/*
94. Binary Tree Inorder Traversal
source: https://leetcode.com/problems/binary-tree-inorder-traversal/
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
*/
package binarytreeinordertraversal
// TreeNode binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func inorderTraversal(root *TreeNode) []int {
res := make([]int, 0, 1)
inorderTraversalHelp(root, &res)
return res
}
func inorderTraversalHelp(root *TreeNode, res *[]int) {
if root == nil {
return
}
inorderTraversalHelp(root.Left, res)
*res = append(*res, root.Val)
inorderTraversalHelp(root.Right, res)
}
================================================
FILE: solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal_test.go
================================================
package binarytreeinordertraversal
import (
"reflect"
"testing"
)
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestInorderTraversal(t *testing.T) {
testData := [][]int{
{1, 2, 3},
}
expectedData := [][]int{
{2, 1, 3},
}
for index, data := range testData {
if res := inorderTraversal(createBinaryTree(data)); !reflect.DeepEqual(res, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0100_same_tree/same_tree.go
================================================
/*
100. Same Tree
https://leetcode.com/problems/same-tree/
Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
*/
package sametree
// TreeNode binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil {
return q == nil
}
if q == nil {
return p == nil
}
if p.Val == q.Val {
return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}
return false
}
================================================
FILE: solutions/0100_same_tree/same_tree_test.go
================================================
package sametree
import "testing"
type arg struct {
p []int
q []int
}
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestSameTree(t *testing.T) {
testData := []arg{
{p: []int{1, 2, 3}, q: []int{1, 2, 3}},
{p: []int{1, 2, 3}, q: []int{1, 2}},
{p: []int{1, 2, 3}, q: []int{1, 2, 4}},
}
expectedData := []bool{true, false, false}
for index, data := range testData {
if res := isSameTree(createBinaryTree(data.p), createBinaryTree(data.q)); res != expectedData[index] {
t.Errorf("expected %t, got %t", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0101_symmetric_tree/symmetric_tree.go
================================================
/*
101. Symmetric Tree
https://leetcode.com/problems/symmetric-tree/
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
*/
package symmetrictree
// TreeNode binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isSymmetric(root *TreeNode) bool {
if root == nil {
return true
}
return symmetric(root.Left, root.Right)
}
func symmetric(left *TreeNode, right *TreeNode) bool {
if left == nil && right == nil {
return true
}
if left == nil || right == nil {
return false
}
return left.Val == right.Val && symmetric(left.Left, right.Right) && symmetric(left.Right, right.Left)
}
================================================
FILE: solutions/0101_symmetric_tree/symmetric_tree_test.go
================================================
package symmetrictree
import (
"testing"
)
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestIsSymmetric(t *testing.T) {
testData := [][]int{
{1, 2, 2, 3, 4, 4, 3},
{1, 2, 2, 3, 3},
{},
}
expectedData := []bool{true, false, true}
for index, data := range testData {
if res := isSymmetric(createBinaryTree(data)); res != expectedData[index] {
t.Errorf("expected %t, got %t", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go
================================================
/*
102. Binary Tree Level Order Traversal
https://leetcode.com/problems/binary-tree-level-order-traversal/
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
*/
// time: 2019-01-04
package btlot
// TreeNode Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
type queueEle struct {
Level int
Ele *TreeNode
}
// bfs
// time complexity: O(n), where n is number of tree nodes.
// space complexity: O(n)
func levelOrder(root *TreeNode) [][]int {
if root == nil {
return [][]int{}
}
var (
queue []queueEle
res = make([][]int, 0)
)
queue = append(queue, queueEle{Level: 0, Ele: root})
for len(queue) > 0 {
node := queue[0].Ele
level := queue[0].Level
queue = queue[1:]
if len(res) > level {
res[level] = append(res[level], node.Val)
} else {
res = append(res, []int{node.Val})
}
if node.Left != nil {
queue = append(queue, queueEle{Level: level + 1, Ele: node.Left})
}
if node.Right != nil {
queue = append(queue, queueEle{Level: level + 1, Ele: node.Right})
}
}
return res
}
================================================
FILE: solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal_test.go
================================================
package btlot
import (
"reflect"
"testing"
)
func TestLevelOrder(t *testing.T) {
testCases := []*TreeNode{
createBinaryTree([]int{1, 2, 3, 4, 5}),
nil,
}
expected := [][][]int{
{{1}, {2, 3}, {4, 5}},
{},
}
for index, root := range testCases {
if res := levelOrder(root); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
================================================
FILE: solutions/0104_maximun_depth_of_binary_tree/maxdobt.go
================================================
/*
104. Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along
the longest path from the root node down to the farthest leaf node.
Note: A leaf is a node with no children.
*/
// time: 2019-01-06
package maxdobt
// TreeNode Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// Recursive
// time complexity: O(n), where n is the nodes number in the tree.
// space complexity: O(h), where h is the height of the tree.
func maxDepth(root *TreeNode) int {
if root == nil {
return 0
}
left := maxDepth(root.Left)
right := maxDepth(root.Right)
var max int
if left > right {
max = left
} else {
max = right
}
return max + 1
}
================================================
FILE: solutions/0104_maximun_depth_of_binary_tree/maxdobt_test.go
================================================
package maxdobt
import "testing"
func TestMaxDepth(t *testing.T) {
root := createBinaryTree([]int{1, 2, 3, 4, 5})
expected := 3
if res := maxDepth(root); res != expected {
t.Errorf("expected %d, got %d", expected, res)
}
}
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := &TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return tree
}
================================================
FILE: solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go
================================================
/*
107. Binary Tree Level Order Traversal II
https://leetcode.com/problems/binary-tree-level-order-traversal-ii/
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root).
*/
package binarytreelevelordertraversal2
// TreeNode binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func levelOrderBottom(root *TreeNode) [][]int {
var record [][]int
traversal(root, 0, &record)
var reversed [][]int
for i := len(record) - 1; i >= 0; i-- {
reversed = append(reversed, record[i])
}
return reversed
}
func traversal(root *TreeNode, index int, record *[][]int) {
if root == nil {
return
}
if len(*record) == index {
*record = append(*record, make([]int, 0))
}
(*record)[index] = append((*record)[index], root.Val)
traversal(root.Left, index+1, record)
traversal(root.Right, index+1, record)
// (*record)[len(*record)-1-index] = append((*record)[len(*record)-1-index], root.Val)
// 这个方法用java可以实现,go不行,猜测可能跟java的递归实现有关。
}
================================================
FILE: solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2_test.go
================================================
package binarytreelevelordertraversal2
import (
"reflect"
"testing"
)
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestBinaryTreeLevelOrderTraversal2(t *testing.T) {
testData := [][]int{
{3, 9, 20, 15, 17},
}
expectedData := [][][]int{
{
{15, 17},
{9, 20},
{3},
},
}
for index, data := range testData {
if res := levelOrderBottom(createBinaryTree(data)); !reflect.DeepEqual(res, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go
================================================
/*
111. Minimum Depth of Binary Tree
https://leetcode.com/problems/minimum-depth-of-binary-tree/
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.
*/
package minimumdepthofbinarytree
import "leetcode/utils"
// TreeNode binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func minDepth(root *TreeNode) int {
if root == nil {
return 0
}
left := minDepth(root.Left)
right := minDepth(root.Right)
if left == 0 || right == 0 {
return utils.CalcMaxInt(left, right) + 1
}
return utils.CalcMinInt(left, right) + 1
}
================================================
FILE: solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree_test.go
================================================
package minimumdepthofbinarytree
import "testing"
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestMinDepth(t *testing.T) {
testData := [][]int{
{3, 9, 20, 15, 7},
}
expectedData := []int{2}
for index, data := range testData {
if res := minDepth(createBinaryTree(data)); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0112_path_sum/path_sum.go
================================================
/*
112. Path Sum
https://leetcode.com/problems/path-sum/
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
Note: A leaf is a node with no children.
*/
package pathsum
// TreeNode binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func hasPathSum(root *TreeNode, sum int) bool {
if root == nil {
return false
}
if root.Left == nil && root.Right == nil {
return root.Val == sum
}
return hasPathSum(root.Left, sum-root.Val) || hasPathSum(root.Right, sum-root.Val)
}
================================================
FILE: solutions/0112_path_sum/path_sum_test.go
================================================
package pathsum
import (
"os"
"testing"
)
func createBinaryTree(nums []interface{}) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []interface{}, index int) *TreeNode {
if !(index < len(nums)) || nums[index] == nil {
return nil
}
tree := TreeNode{}
if num, ok := nums[index].(int); ok { // type assertion
tree.Val = num
}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
type arg struct {
nums []interface{}
sum int
}
func TestHasPathSum(t *testing.T) {
testData := []arg{
{nums: []interface{}{5, 4, 8, 11, nil, 13, 4, 7, 2, nil, nil, nil, 1}, sum: 22},
{nums: []interface{}{}, sum: 0},
}
expectedData := []bool{true, false}
for index, data := range testData {
if res := hasPathSum(createBinaryTree(data.nums), data.sum); res != expectedData[index] {
t.Errorf("expected %t, got %t", expectedData[index], res)
}
}
}
func TestMain(m *testing.M) {
os.Exit(m.Run())
}
================================================
FILE: solutions/0120_triangle/triangle.go
================================================
/*
120. Triangle
https://leetcode.com/problems/triangle/
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
*/
package triangle
import "leetcode/utils"
// dfs
/*
func minimumTotal(triangle [][]int) int {
if len(triangle) == 0 {
return 0
}
result := utils.MaxInt
dfs(0, 0, 0, triangle, &result)
return result
}
func dfs(x int, y int, sum int, triangle [][]int, result *int) {
if len(triangle) == x {
if sum < *result {
*result = sum
}
return
}
sum += triangle[x][y]
dfs(x+1, y, sum, triangle, result)
dfs(x+1, y+1, sum, triangle, result)
}
*/
// dynamic programming
func minimumTotal(triangle [][]int) int {
m := len(triangle)
if m == 0 {
return 0
}
dp := make([][]int, m)
dp[0] = append(dp[0], triangle[0][0])
for i := 1; i < m; i++ {
for j, num := range triangle[i] {
if j >= len(dp[i-1]) {
dp[i] = append(dp[i], num+dp[i-1][j-1])
} else {
if j-1 >= 0 && dp[i-1][j-1] < dp[i-1][j] {
dp[i] = append(dp[i], num+dp[i-1][j-1])
} else {
dp[i] = append(dp[i], num+dp[i-1][j])
}
}
}
}
var mininum = utils.MaxInt
for _, num := range dp[m-1] {
if num < mininum {
mininum = num
}
}
return mininum
}
================================================
FILE: solutions/0120_triangle/triangle_test.go
================================================
package triangle
import (
"testing"
)
func TestTriangle(t *testing.T) {
testData := [][][]int{
{{2}, {3, 4}, {6, 5, 7}, {4, 1, 8, 3}},
{},
{{-1}, {2, 3}, {1, -1, -3}},
}
expectedData := []int{11, 0, -1}
for index, data := range testData {
if mininum := minimumTotal(data); mininum != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], mininum)
}
}
}
================================================
FILE: solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go
================================================
/*
121. Best Time to Buy and Sell Stock
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction
(i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
*/
// time: 2018-12-28
package maxprofit
// dynamic programming
// for every price, find the max profit, then record the current minimum price.
// time complexity: O(n)
// space complexity: O(1)
func maxProfit(prices []int) int {
n := len(prices)
if 0 == n || 1 == n {
return 0
}
var (
res int
minPrice = prices[0]
)
for _, price := range prices {
if price-minPrice > res {
res = price - minPrice
}
if price < minPrice {
minPrice = price
}
}
return res
}
// brute force
// time complexity: O(n^2)
// space complexity: O(1)
func maxProfit1(prices []int) int {
n := len(prices)
if 0 == n || 1 == n {
return 0
}
res := 0
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
if prices[i]-prices[j] > res {
res = prices[i] - prices[j]
}
}
}
return res
}
================================================
FILE: solutions/0121_best_time_to_buy_and_sell_stock/maxprofit_test.go
================================================
package maxprofit
import "testing"
func TestMaxProfit(t *testing.T) {
testCases := [][]int{
{7, 1, 5, 3, 6, 4},
{5, 3, 2, 2, 5, 7, 9, 4},
{},
{3},
{5, 3, 2, 2, 5, 7, 9, 4, 5, 3, 2, 2, 5, 7, 9, 4},
{2, 4, 1, 11, 7},
}
expected := []int{5, 7, 0, 0, 7, 10}
for index, data := range testCases {
if res := maxProfit(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
func TestMaxProfit1(t *testing.T) {
testCases := [][]int{
{7, 1, 5, 3, 6, 4},
{5, 3, 2, 2, 5, 7, 9, 4},
{},
{3},
}
expected := []int{5, 7, 0, 0}
for index, data := range testCases {
if res := maxProfit1(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go
================================================
/*
122. Best Time to Buy and Sell Stock II
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit.
You may complete as many transactions as you like
(i.e., buy one and sell one share of the stock multiple times).
Note: You may not engage in multiple transactions at the same time
(i.e., you must sell the stock before you buy again).
*/
// time: 2018-12-28
package maxprofit
// greedy
// time complexity: O(n)
// space complexity: O(1)
func maxProfit(prices []int) int {
n := len(prices)
if 0 == n || 1 == n {
return 0
}
var (
res int
minPrice = prices[0]
)
for i := 1; i < n; i++ {
if prices[i] < prices[i-1] {
res += prices[i-1] - minPrice
minPrice = prices[i]
}
if i == n-1 {
res += prices[i] - minPrice
}
}
return res
}
================================================
FILE: solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit_test.go
================================================
package maxprofit
import "testing"
func TestMaxProfit(t *testing.T) {
testCases := [][]int{
{7, 1, 5, 3, 6, 4},
{1, 2, 3, 4, 5},
{7, 6, 4, 3, 1},
{}, {1},
}
expected := []int{7, 4, 0, 0, 0}
for index, data := range testCases {
if res := maxProfit(data); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0125_valid_palindrome/valid_palindrome.go
================================================
/*
125. Valid Palindrome
https://leetcode.com/problems/valid-palindrome/
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
*/
// time: 2018-12-26
package validpalindrome
// double index
// time complexity: O(n)
// space complexity: O(n)
func isPalindrome(s string) bool {
chars := make([]uint8, 0)
for i := 0; i < len(s); i++ {
if s[i] >= 65 && s[i] <= 90 {
chars = append(chars, s[i])
}
if s[i] >= 97 && s[i] <= 122 {
chars = append(chars, s[i]-32)
}
if s[i] >= 48 && s[i] <= 57 {
chars = append(chars, s[i])
}
}
var (
l int
r = len(chars) - 1
)
for r >= l {
if chars[r] != chars[l] {
return false
}
r--
l++
}
return true
}
================================================
FILE: solutions/0125_valid_palindrome/valid_palindrome_test.go
================================================
package validpalindrome
import "testing"
func TestIsPalindrome(t *testing.T) {
testCases := []string{
"A man, a plan, a canal: Panama",
"race a car",
"0P",
"",
}
expected := []bool{true, false, false, true}
for index, data := range testCases {
if res := isPalindrome(data); res != expected[index] {
t.Errorf("expected %t, got %t", expected[index], res)
}
}
}
================================================
FILE: solutions/0136_single_number/single_number.go
================================================
/*
136. Single Number
https://leetcode.com/problems/single-number/
Given a non-empty array of integers, every element appears twice except for one. Find that single one.
*/
// time: 2019-02-01
package sn
// time complexity: O(n)
// space complexity: O(n)
func singleNumber(nums []int) int {
record := make(map[int]int)
for _, num := range nums {
if _, ok := record[num]; ok {
delete(record, num)
} else {
record[num] = 1
}
}
var res int
for key := range record {
res = key
}
return res
}
// time complexity: O(n)
// space complexity: O(1)
func singleNumber1(nums []int) int {
res := 0
for _, num := range nums {
res ^= num
}
return res
}
================================================
FILE: solutions/0136_single_number/single_number_test.go
================================================
package sn
import "testing"
func TestSingleNumber(t *testing.T) {
testCases := [][]int{
{2, 2, 1},
{4, 1, 2, 1, 2},
}
expected := []int{1, 4}
testFuncs := []func([]int) int{
singleNumber, singleNumber1,
}
for _, testFunc := range testFuncs {
for index, nums := range testCases {
if res := testFunc(nums); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
}
================================================
FILE: solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go
================================================
/*
144. Binary Tree Preorder Traversal
https://leetcode.com/problems/binary-tree-preorder-traversal/
Given a binary tree, return the preorder traversal of its nodes' values.
*/
// time: 2019-01-06
package btpot
// TreeNode Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// recursive
// time complexity: O(n), where n is nodes numbers in the tree.
// space complexity: O(h), where h is the height of the tree.
func preorderTraversal(root *TreeNode) []int {
if root == nil {
return []int{}
}
if root.Left == nil && root.Right == nil {
return []int{root.Val}
}
left := preorderTraversal(root.Left)
right := preorderTraversal(root.Right)
res := []int{root.Val}
res = append(res, left...)
res = append(res, right...)
return res
}
// iterative
// time complexity: O(n), where n is nodes numbers in the tree.
// space complexity: O(h), where h is the height of the tree.
func preorderTraversal1(root *TreeNode) []int {
if root == nil {
return []int{}
}
var stack []*TreeNode
var res []int
stack = append(stack, root)
for len(stack) > 0 {
node := stack[len(stack)-1]
stack = stack[:len(stack)-1]
res = append(res, node.Val)
if node.Right != nil {
stack = append(stack, node.Right)
}
if node.Left != nil {
stack = append(stack, node.Left)
}
}
return res
}
================================================
FILE: solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal_test.go
================================================
package btpot
import (
"reflect"
"testing"
)
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestPreorderTraversal(t *testing.T) {
testCases := []*TreeNode{
nil,
createBinaryTree([]int{1, 2, 3, 4, 5, 6, 7, 8}),
}
expected := [][]int{
{},
{1, 2, 4, 8, 5, 3, 6, 7},
}
testFuncs := []func(node *TreeNode) []int{
preorderTraversal,
preorderTraversal1,
}
for _, testFunc := range testFuncs {
for index, root := range testCases {
if res := testFunc(root); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
}
================================================
FILE: solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go
================================================
/*
150. Evaluate Reverse Polish Notation
https://leetcode.com/problems/evaluate-reverse-polish-notation/
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Note:
Division between two integers should truncate toward zero.
The given RPN expression is always valid.
That means the expression would always evaluate to a result and there won't be any divide by zero operation.
*/
// time: 2019-01-07
package evaluatereversepolishnotation
import "strconv"
// stack
// time complexity: O(n)
// space complexity: O(n)
func evalRPN(tokens []string) int {
stack := make([]int, len(tokens))
top := -1
for i := 0; i < len(tokens); i++ {
switch ch := tokens[i]; ch {
case "+":
stack[top-1] += stack[top]
top--
case "-":
stack[top-1] -= stack[top]
top--
case "*":
stack[top-1] *= stack[top]
top--
case "/":
stack[top-1] /= stack[top]
top--
default:
top++
stack[top], _ = strconv.Atoi(ch)
}
}
return stack[0]
}
================================================
FILE: solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation_test.go
================================================
package evaluatereversepolishnotation
import "testing"
func TestEvalRPN(t *testing.T) {
testCases := [][]string{
{"2", "1", "+", "3", "*"},
{"4", "13", "5", "/", "+"},
{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"},
{"4", "3", "-"},
}
expected := []int{9, 6, 22, 1}
for index, tokens := range testCases {
if res := evalRPN(tokens); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go
================================================
/*
153. Find Minimum in Rotated Sorted Array
https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand.
(i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
Find the minimum element.
You may assume no duplicate exists in the array.
*/
// time: 2019-01-07
package fmirsa
// binary search
// time complexity: O( log n)
// space complexity: O(1)
func findMin(nums []int) int {
var (
low int
high = len(nums) - 1
mid int
)
for low < high {
mid = low + (high-low)>>1
if nums[high] < nums[mid] {
low = mid + 1
} else {
high = mid
}
}
return nums[low]
}
================================================
FILE: solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa_test.go
================================================
package fmirsa
import "testing"
func TestFindMin(t *testing.T) {
nums := []int{3, 4, 5, 1, 2}
expected := 1
if res := findMin(nums); res != expected {
t.Errorf("expected %d, got %d", expected, res)
}
}
================================================
FILE: solutions/0155_min_stack/min_stack.go
================================================
/*
155. Min Stack
https://leetcode.com/problems/min-stack/
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.
*/
// time: 2019-01-10
package minstack
// MinStack a stack that supports push, pop, top, and retrieving the minimum element in constant time.
type MinStack struct {
data []int
}
// Constructor initialize your data structure here.
func Constructor() MinStack {
return MinStack{}
}
// Push element x onto stack.
func (s *MinStack) Push(x int) {
s.data = append(s.data, x)
}
// Pop Removes the element on top of the stack.
func (s *MinStack) Pop() {
if !s.IsEmpty() {
s.data = s.data[:s.GetSize()-1]
}
}
// Top Get the top element.
func (s *MinStack) Top() int {
//if s.IsEmpty(){
// return 0
//}
// stack must have element.
return s.data[s.GetSize()-1]
}
// GetMin retrieving the minimum element in constant time.
// time complexity: O(n)
func (s *MinStack) GetMin() int {
//if s.IsEmpty() {
// return 0
//}
// stack must have element.
stackSize := s.GetSize()
ret := s.data[stackSize-1]
for i := stackSize - 2; i >= 0; i-- {
if s.data[i] < ret {
ret = s.data[i]
}
}
return ret
}
// GetSize get size of the stack.
func (s MinStack) GetSize() int {
return len(s.data)
}
func (s MinStack) IsEmpty() bool {
return s.GetSize() == 0
}
================================================
FILE: solutions/0155_min_stack/min_stack_test.go
================================================
package minstack
import "testing"
func TestMinStack(t *testing.T) {
obj := Constructor()
obj.Push(-2)
obj.Push(0)
obj.Push(-3)
if res := obj.GetMin(); res != -3 {
t.Errorf("expected %d, got %d", -3, res)
}
obj.Pop()
if res := obj.Top(); res != 0 {
t.Errorf("expected %d, got %d", 0, res)
}
if res := obj.GetMin(); res != -2 {
t.Errorf("expected %d, got %d", -2, res)
}
}
================================================
FILE: solutions/0165_compare_version_numbers/compare_version_numbers.go
================================================
/*
165. Compare Version Numbers
https://leetcode.com/problems/compare-version-numbers/
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5 is not "two and a half" or "half way to version three",
it is the fifth second-level revision of the second first-level revision.
You may assume the default revision number for each level of a version number to be 0.
For example, version number 3.4 has a revision number of 3 and 4 for its first and second level revision number.
Its third and fourth level revision number are both 0.
Note:
Version strings are composed of numeric strings separated by dots . and this numeric strings may have leading zeroes.
Version strings do not start or end with dots, and they will not be two consecutive dots.
*/
// time: 2019-01-07
package compareversionnumbers
import (
"strconv"
"strings"
)
// time complexity: O( max n, m )
// space complexity: O(n+m)
func compareVersion(version1 string, version2 string) int {
var (
v1 = strings.Split(version1, ".")
v2 = strings.Split(version2, ".")
)
for i := 0; i < len(v1) || i < len(v2); i++ {
var v1N, v2N int
if i < len(v1) {
v1N, _ = strconv.Atoi(v1[i])
}
if i < len(v2) {
v2N, _ = strconv.Atoi(v2[i])
}
if v1N > v2N {
return 1
} else if v1N < v2N {
return -1
}
}
return 0
}
================================================
FILE: solutions/0165_compare_version_numbers/compare_version_numbers_test.go
================================================
package compareversionnumbers
import "testing"
func TestCompareVersion(t *testing.T) {
type arg struct {
version1 string
version2 string
}
testCases := []arg{
{version1: "0.1", version2: "1.1"},
{version1: "1.0.1", version2: "1"},
{version1: "1.01", version2: "1.001"},
}
expected := []int{-1, 1, 0}
for index, data := range testCases {
if res := compareVersion(data.version1, data.version2); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0167_two_sum2/two_sum2.go
================================================
/*
167. Two Sum II - Input array is sorted
https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/
Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2.
Note:
Your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution and you may not use the same element twice.
Example:
Input: numbers = [2,7,11,15], target = 9
Output: [1,2]
Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
*/
package twosum2
func twoSum2(numbers []int, target int) []int {
n := len(numbers)
var (
l = 0
r = n - 1
)
for l < r {
if numbers[l]+numbers[r] == target {
return []int{l + 1, r + 1}
} else if numbers[l]+numbers[r] < target {
l++
} else {
r--
}
}
panic("The input has no solution.")
}
================================================
FILE: solutions/0167_two_sum2/two_sum2_test.go
================================================
package twosum2
import (
"reflect"
"testing"
)
type arg struct {
numbers []int
target int
}
func TestTwoSum2(t *testing.T) {
testData := []arg{
{
numbers: []int{2, 7, 11, 15},
target: 9,
},
}
expectedData := [][]int{
{1, 2},
}
for index, data := range testData {
if res := twoSum2(data.numbers, data.target); !reflect.DeepEqual(res, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], res)
}
}
defer func() {
if err := recover(); err == nil {
t.Errorf("there should throw a panic")
}
}()
twoSum2([]int{2, 7, 11, 15}, 90)
}
================================================
FILE: solutions/0179_largest_number/ln.go
================================================
/*
179. Largest Number
https://leetcode.com/problems/largest-number/
Given a list of non negative integers, arrange them such that they form the largest number.
Note: The result may be very large, so you need to return a string instead of an integer.
*/
// time: 2019-01-14
package ln
import (
"sort"
"strconv"
"strings"
)
type sliceString []string
// Len is the number of elements in the collection.
func (s sliceString) Len() int { return len(s) }
// Swap swaps the elements with indexes i and j.
func (s sliceString) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
// Less reports whether the element with
// index i should sort before the element with index j.
func (s sliceString) Less(i, j int) bool { return (s[i] + s[j]) > (s[j] + s[i]) }
// time complexity: O(n log n), dominated by the complexity of sort.
// space complexity: O(n)
func largestNumber(nums []int) string {
numsString := make([]string, 0)
for _, num := range nums {
numsString = append(numsString, strconv.Itoa(num))
}
sort.Sort(sliceString(numsString))
numStr := strings.Join(numsString, "")
if strings.HasPrefix(numStr, "0") {
return "0"
}
return numStr
}
================================================
FILE: solutions/0179_largest_number/ln_test.go
================================================
package ln
import "testing"
func TestLargestNumber(t *testing.T) {
testCases := [][]int{
{10, 2},
{3, 30, 34, 5, 9},
{0},
}
expected := []string{
"210",
"9534330",
"0",
}
for index, nums := range testCases {
if res := largestNumber(nums); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
================================================
FILE: solutions/0198_house_robber/house_robber.go
================================================
/*
198. House Robber
https://leetcode.com/problems/house-robber/
You are a professional robber planning to rob houses along a street. Each house has a certain amount
of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses
have security system connected and it will automatically contact the police if two adjacent houses were
broken into on the same night.
Given a list of non-negative integers representing the amount of money of each house, determine the
maximum amount of money you can rob tonight without alerting the police.
Example 1:
Input: [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
Example 2:
Input: [2,7,9,3,1]
Output: 12
Explanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).
Total amount you can rob = 2 + 9 + 1 = 12.
*/
package houserobber
import "leetcode/utils"
/*
func rob(nums []int) int {
return tryRob(nums, 0)
}
func tryRob(nums []int, index int) int {
if index >= len(nums) {
return 0
}
var res int
for i := index; i < len(nums); i++ {
res, _ = utils.CalcMaxInt(res, nums[i]+tryRob(nums, i+2))
}
return res
}
*/
// memory search
/*
func rob(nums []int) int {
memo := make([]int, len(nums))
for i := 0; i < len(nums); i++ {
memo[i] = -1
}
return tryRob(nums, 0, memo)
}
func tryRob(nums []int, index int, memo []int) int {
if index >= len(nums) {
return 0
}
if memo[index] != -1 {
return memo[index]
}
var res int
for i := index; i < len(nums); i++ {
res, _ = utils.CalcMaxInt(res, nums[i]+tryRob(nums, i+2, memo))
}
memo[index] = res
return res
}*/
// dynamic programming
func rob(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
memo := make([]int, n)
for i := 0; i < n; i++ {
memo[i] = -1
}
memo[n-1] = nums[n-1]
for i := n - 2; i >= 0; i-- {
for j := i; j < n; j++ {
if j+2 < n {
memo[i] = utils.CalcMaxInt(memo[i], nums[j]+memo[j+2])
} else {
memo[i] = utils.CalcMaxInt(memo[i], nums[j])
}
}
}
return memo[0]
}
================================================
FILE: solutions/0198_house_robber/house_robber_test.go
================================================
package houserobber
import "testing"
func TestHouseRobber(t *testing.T) {
testData := [][]int{
{1, 2, 3, 1},
{9, 1, 293, 5986, 81, 384},
{1, 2},
{},
}
expectedData := []int{4, 6379, 2, 0}
for index, data := range testData {
if res := rob(data); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0200_number_of_island/number_of_island.go
================================================
/*
200. Number of Islands
https://leetcode.com/problems/number-of-islands/
Given a 2d grid map of '1's (land) and '0's (water), count the number of islands.
An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically.
You may assume all four edges of the grid are all surrounded by water.
*/
// time: 2019-01-07
package noi
var (
d = [][]int{{0, 1}, {1, 0}, {0, -1}, {-1, 0}}
m, n int
visited [][]bool
)
// flood-fill
// time complexity: O(n*m)
// space complexity: O(n*m)
func numIslands(grid [][]byte) int {
m = len(grid)
if m <= 0 {
return 0
}
n = len(grid[0])
visited = make([][]bool, m)
for i := 0; i < m; i++ {
visited[i] = make([]bool, n)
}
var res int
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if grid[i][j] == '1' && !visited[i][j] {
res++
dfs(grid, i, j)
}
}
}
return res
}
// 从grid[x][y]的位置开始,进行floodfill。
func dfs(grid [][]byte, x, y int) {
visited[x][y] = true
for i := 0; i < len(d); i++ {
newX := x + d[i][0]
newY := y + d[i][1]
if inArea(newX, newY) && !visited[newX][newY] && grid[newX][newY] == '1' {
dfs(grid, newX, newY)
}
}
}
func inArea(x, y int) bool {
return x >= 0 && x < m && y >= 0 && y < n
}
================================================
FILE: solutions/0200_number_of_island/number_of_island_test.go
================================================
package noi
import "testing"
func TestNumIslands(t *testing.T) {
grids := [][][]byte{
{
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'},
},
{},
}
expected := []int{3, 0}
for index, grid := range grids {
if res := numIslands(grid); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go
================================================
/*
203. Remove Linked List Elements
https://leetcode.com/problems/remove-linked-list-elements/
Remove all elements from a linked list of integers that have value val.
*/
// time: 2019-01-07
package rlle
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n)
// space complexity: O(1)
func removeElements(head *ListNode, val int) *ListNode {
dummyHead := &ListNode{}
dummyHead.Next = head
cur := dummyHead
for cur.Next != nil {
if val == cur.Next.Val {
cur.Next = cur.Next.Next
} else {
cur = cur.Next
}
}
return dummyHead.Next
}
// recursive
// time complexity: O(n)
// space complexity: O(n)
func removeElements1(head *ListNode, val int) *ListNode {
if head == nil {
return head
}
head.Next = removeElements1(head.Next, val)
if head.Val == val {
return head.Next
}
return head
}
================================================
FILE: solutions/0203_remove_linked_list_elements/remove_linked_list_elements_test.go
================================================
package rlle
import (
"reflect"
"testing"
)
func TestRemoveElements(t *testing.T) {
head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6})
val := 6
expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5})
if res := removeElements(head, val); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
func TestRemoveElements1(t *testing.T) {
head := createSinglyLinkedList([]int{1, 2, 6, 3, 4, 5, 6})
val := 6
expected := createSinglyLinkedList([]int{1, 2, 3, 4, 5})
if res := removeElements1(head, val); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
func createSinglyLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
================================================
FILE: solutions/0206_reverse_linked_list/reverse_linked_list.go
================================================
/*
206. Reverse Linked List
https://leetcode.com/problems/reverse-linked-list/
Reverse a singly linked list.
*/
// time: 2019-01-07
package rll
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// recursive
// time complexity: O(n)
// space complexity: O(n)
func reverseList(head *ListNode) *ListNode {
if head == nil || head.Next == nil {
return head
}
tail := reverseList(head.Next)
head.Next.Next = head
head.Next = nil
return tail
}
// iterative
// time complexity: O(n)
// space complexity: O(1)
func reverseList1(head *ListNode) *ListNode {
var (
pre *ListNode
cur = head
)
for cur != nil {
next := cur.Next
cur.Next = pre
pre = cur
cur = next
}
return pre
}
================================================
FILE: solutions/0206_reverse_linked_list/reverse_linked_list_test.go
================================================
package rll
import (
"reflect"
"testing"
)
func TestReverseList(t *testing.T) {
head := createSinglyLinkedList([]int{1, 2, 3, 4, 5})
expected := createSinglyLinkedList([]int{5, 4, 3, 2, 1})
if res := reverseList(head); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
func TestReverseList1(t *testing.T) {
head := createSinglyLinkedList([]int{1, 2, 3, 4, 5})
expected := createSinglyLinkedList([]int{5, 4, 3, 2, 1})
if res := reverseList1(head); !reflect.DeepEqual(res, expected) {
t.Errorf("expected %v, got %v", expected, res)
}
}
func createSinglyLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
================================================
FILE: solutions/0208_implement_trie_prefix_tree/impltrie.go
================================================
/*
208. Implement Trie (Prefix Tree)
https://leetcode.com/problems/implement-trie-prefix-tree/
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
*/
// time: 2019-01-31
package impltree
type node struct {
isWord bool
next map[byte]*node
}
// Trie prefix tree
type Trie struct {
root *node
size int
}
// Constructor initialize data structure here.
func Constructor() Trie {
return Trie{root: &node{next: make(map[byte]*node)}}
}
// Insert inserts a word into the trie.
func (trie *Trie) Insert(word string) {
cur := trie.root
for i := 0; i < len(word); i++ {
if _, ok := cur.next[word[i]]; !ok {
cur.next[word[i]] = &node{next: make(map[byte]*node)}
}
cur = cur.next[word[i]]
}
if !cur.isWord {
cur.isWord = true
trie.size++
}
}
// Search returns if the word is the trie.
func (trie *Trie) Search(word string) bool {
cur := trie.root
for i := 0; i < len(word); i++ {
if _, ok := cur.next[word[i]]; !ok {
return false
}
cur = cur.next[word[i]]
}
return cur.isWord
}
// StartsWith returns if there is any word in the trie that starts with the given prefix.
func (trie *Trie) StartsWith(prefix string) bool {
cur := trie.root
for i := 0; i < len(prefix); i++ {
if _, ok := cur.next[prefix[i]]; !ok {
return false
}
cur = cur.next[prefix[i]]
}
return true
}
================================================
FILE: solutions/0208_implement_trie_prefix_tree/impltrie_test.go
================================================
package impltree
import "testing"
func TestImplTrie(t *testing.T) {
trie := Constructor()
trie.Insert("apple")
for i, j := range map[string]bool{"apple": true, "app": false, "hello": false} {
if res := trie.Search(i); res != j {
t.Errorf("expected %t, got %t", j, res)
}
}
for i, j := range map[string]bool{"app": true, "as": false} {
if res := trie.StartsWith(i); res != j {
t.Errorf("expected %t, got %t", j, res)
}
}
trie.Insert("app")
if res := trie.Search("app"); res != true {
t.Errorf("expected %t, got %t", true, res)
}
}
================================================
FILE: solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go
================================================
/*
209. Minimum Size Subarray Sum
https://leetcode.com/problems/minimum-size-subarray-sum/
Given an array of n positive integers and a positive integer s, find the minimal length of a contiguous subarray of which the sum ≥ s. If there isn't one, return 0 instead.
Example:
Input: s = 7, nums = [2,3,1,2,4,3]
Output: 2
Explanation: the subarray [4,3] has the minimal length under the problem constraint.
Follow up:
If you have figured out the O(n) solution, try coding another solution of which the time complexity is O(n log n).
*/
package minimumsizesubarraysum
func minSubArrayLen(s int, nums []int) int {
var (
l = 0
r = -1
res = len(nums) + 1
sum = 0
)
for l < len(nums) {
if sum < s && r+1 < len(nums) {
r++
sum += nums[r]
} else {
sum -= nums[l]
l++
}
if sum >= s && res > r-l+1 {
res = r - l + 1
}
}
if res == len(nums)+1 {
return 0
}
return res
}
================================================
FILE: solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum_test.go
================================================
package minimumsizesubarraysum
import "testing"
func TestMinSubArrayLen(t *testing.T) {
type arg struct {
s int
nums []int
}
testData := []arg{
{
s: 7,
nums: []int{2, 3, 1, 2, 4, 3},
},
{
s: 7,
nums: []int{7, 4, 3, 2},
},
{
s: 66,
nums: []int{7, 4, 3, 2},
},
}
expectedData := []int{2, 1, 0}
for index, data := range testData {
if res := minSubArrayLen(data.s, data.nums); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0211_add_and_search_word/add_and_search_word.go
================================================
/*
211. Add and Search Word - Data structure design
https://leetcode.com/problems/add-and-search-word-data-structure-design/
*/
// time: 2019-01-31
package aasw
type node struct {
isWord bool
next map[byte]*node
}
// WordDictionary supports two operations(addWord, search)
type WordDictionary struct {
root *node
}
// Constructor initialize data structure here.
func Constructor() WordDictionary {
return WordDictionary{&node{next: make(map[byte]*node)}}
}
// AddWord adds a word into the trie.
func (trie *WordDictionary) AddWord(word string) {
cur := trie.root
for i := 0; i < len(word); i++ {
if _, ok := cur.next[word[i]]; !ok {
cur.next[word[i]] = &node{next: make(map[byte]*node)}
}
cur = cur.next[word[i]]
}
if !cur.isWord {
cur.isWord = true
}
}
// Search returns if the word is in the trie.
// a word could contain the dot character '.' to represent any ont letter.
func (trie *WordDictionary) Search(word string) bool {
return match(trie.root, word, 0)
}
func match(n *node, word string, index int) bool {
if index == len(word) {
return n.isWord
}
if word[index] != '.' {
if _, ok := n.next[word[index]]; !ok {
return false
}
return match(n.next[word[index]], word, index+1)
} else {
for _, nextNode := range n.next {
if match(nextNode, word, index+1) {
return true
}
}
return false
}
}
================================================
FILE: solutions/0211_add_and_search_word/add_and_search_word_test.go
================================================
package aasw
import "testing"
func TestAddAndSearchWord(t *testing.T) {
obj := Constructor()
for _, word := range []string{"bad", "dad", "mad"} {
obj.AddWord(word)
}
for i, j := range map[string]bool{"pad": false, "bad": true, ".ad": true, "b..": true, "b..d": false} {
if res := obj.Search(i); res != j {
t.Errorf("expected %t, got %t", j, res)
}
}
}
================================================
FILE: solutions/0215_kth_largest_element_in_an_array/kthleiaa.go
================================================
/*
215. Kth Largest Element in an Array
https://leetcode.com/problems/kth-largest-element-in-an-array/
Find the kth largest element in an unsorted array.
Note that it is the kth largest element in the sorted order, not the kth distinct element.
You may assume k is always valid, 1 ≤ k ≤ array's length.
*/
// time: 2018-12-22
package kthleiaa
// heap sort
// time complexity: O(k * logn)
// sapce complexity: O(1)
func findKthLargest(nums []int, k int) int {
// heapify
for i := (len(nums) - 1) / 2; i >= 0; i-- {
siftDown(nums, len(nums), i)
}
for i := len(nums) - 1; i >= len(nums)-k; i-- {
nums[i], nums[0] = nums[0], nums[i]
siftDown(nums, i, 0)
}
return nums[len(nums)-k]
}
func siftDown(nums []int, n int, i int) {
for 2*i+1 < n {
j := 2*i + 1
if j+1 < n && nums[j+1] > nums[j] {
j++
}
if nums[i] >= nums[j] {
break
}
nums[j], nums[i] = nums[i], nums[j]
i = j
}
}
================================================
FILE: solutions/0215_kth_largest_element_in_an_array/kthleiaa_test.go
================================================
package kthleiaa
import "testing"
func TestFindKthLargest(t *testing.T) {
type arg struct {
nums []int
k int
}
testCases := []arg{
{nums: []int{3, 2, 1, 5, 6, 4}, k: 2},
{nums: []int{3, 2, 3, 1, 2, 4, 5, 5, 6}, k: 4},
}
expected := []int{5, 4}
for index, data := range testCases {
if res := findKthLargest(data.nums, data.k); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0217_contains_duplicate/contains_duplicate.go
================================================
/*
217. Contains Duplicate
https://leetcode.com/problems/contains-duplicate/
Given an array of integers, find if the array contains any duplicates.
Your function should return true if any value appears at least twice in the array,
and it should return false if every element is distinct.
*/
// time: 2019-01-07
package cd
// using HashTable
// time complexity: O(n)
// space complexity: O(n)
func containsDuplicate(nums []int) bool {
record := make(map[int]int)
for _, num := range nums {
if _, ok := record[num]; !ok {
record[num] = 1
} else {
return true
}
}
return false
}
================================================
FILE: solutions/0217_contains_duplicate/contains_duplicate_test.go
================================================
package cd
import "testing"
func TestContainsDuplicate(t *testing.T) {
testCases := [][]int{
{1, 2, 3, 1},
{1, 2, 3, 4},
}
expected := []bool{true, false}
for index, nums := range testCases {
if res := containsDuplicate(nums); res != expected[index] {
t.Errorf("expected %t, got %t", expected[index], res)
}
}
}
================================================
FILE: solutions/0219_contains_duplicate_2/contains_duplicate_2.go
================================================
/*
219. Contains Duplicate II
https://leetcode.com/problems/contains-duplicate-ii/
Given an array of integers and an integer k,
find out whether there are two distinct indices i and j in the array
such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
*/
// time: 2019-01-07
package cond
// using hash table
// time complexity: O(n)
// space complexity: O(n)
func containsNearbyDuplicate(nums []int, k int) bool {
record := make(map[int]int, len(nums))
for i, v := range nums {
if j, ok := record[v]; ok {
if i-j <= k {
return true
}
}
record[v] = i
}
return false
}
================================================
FILE: solutions/0219_contains_duplicate_2/contains_duplicate_2_test.go
================================================
package cond
import "testing"
func TestContainsNearbyDuplicate(t *testing.T) {
testCases := [][]int{
{1, 2, 3, 1},
{1, 0, 1, 1},
{1, 2, 3, 1, 2, 3},
}
ks := []int{3, 1, 2}
expected := []bool{true, true, false}
for index, nums := range testCases {
if res := containsNearbyDuplicate(nums, ks[index]); res != expected[index] {
t.Errorf("expected %t, got %t", expected[index], res)
}
}
}
================================================
FILE: solutions/0226_invert_binary_tree/invert_binary_tree.go
================================================
/*
226. Invert Binary Tree
https://leetcode.com/problems/invert-binary-tree/
Invert a binary tree.
*/
package invertbinarytree
// TreeNode binary tree node
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// Recursion
// Time complexity: O(n), where n is the node's number of the tree.
// Space complexity: O(h), where h is the height of the tree.
func invertTree(root *TreeNode) *TreeNode {
if root == nil {
return nil
}
root.Right, root.Left = root.Left, root.Right
invertTree(root.Left)
invertTree(root.Right)
return root
}
================================================
FILE: solutions/0226_invert_binary_tree/invert_binary_tree_test.go
================================================
package invertbinarytree
import (
"reflect"
"testing"
)
func createBinaryTree(nums []interface{}) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []interface{}, index int) *TreeNode {
if !(index < len(nums)) || nums[index] == nil {
return nil
}
tree := TreeNode{}
if num, ok := nums[index].(int); ok { // type assertion
tree.Val = num
}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func levelOrderTraversal(root *TreeNode) []interface{} {
res := make([]interface{}, 0)
queue := make([]*TreeNode, 0)
queue = append(queue, root)
for len(queue) > 0 {
node := queue[0]
queue = queue[1:]
res = append(res, node.Val)
if node.Left != nil {
queue = append(queue, node.Left)
}
if node.Right != nil {
queue = append(queue, node.Right)
}
}
return res
}
func TestInvertTree(t *testing.T) {
testData := [][]interface{}{
{4, 2, 7, 1, 3, 6, 9},
}
expectedData := [][]interface{}{
{4, 7, 2, 9, 6, 3, 1},
}
for index, data := range testData {
tree := createBinaryTree(data)
if res := levelOrderTraversal(invertTree(tree)); !reflect.DeepEqual(res, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go
================================================
/*
235. Lowest Common Ancestor of a Binary Search Tree
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia:
“The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has
both p and q as descendants (where we allow a node to be a descendant of itself).”
Note:
All of the nodes' values will be unique.
p and q are different and both values will exist in the BST.
*/
// time: 2019-01-07
package lcaoabst
// TreeNode Definition for TreeNode.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// recursive
// time complexity: O(log n), where n is the nodes number of the tree.
// space complexity: O(h), where h is the height of the tree.
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil {
return root
}
if root.Val > p.Val && root.Val > q.Val {
return lowestCommonAncestor(root.Left, p, q)
}
if root.Val < p.Val && root.Val < q.Val {
return lowestCommonAncestor(root.Right, p, q)
}
return root
}
================================================
FILE: solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst_test.go
================================================
package lcaoabst
import (
"testing"
)
func TestLowestCommonAncestor(t *testing.T) {
type arg struct {
root, p, q *TreeNode
}
testCases := []arg{
{root: createBinaryTree([]int{6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5}), p: &TreeNode{Val: 3}, q: &TreeNode{Val: 5}},
{p: &TreeNode{Val: 2}, q: &TreeNode{Val: 8}},
}
expected := []*TreeNode{{Val: 4}, nil}
for index, data := range testCases {
if res := lowestCommonAncestor(data.root, data.p, data.q); res != nil && res.Val != expected[index].Val {
t.Errorf("expected %v, got %v", expected[index], res)
} else if res == nil && res != expected[index] {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
root := &TreeNode{Val: nums[index]}
root.Left = performCreate(nums, 2*index+1)
root.Right = performCreate(nums, 2*index+2)
return root
}
================================================
FILE: solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go
================================================
/*
236. Lowest Common Ancestor of a Binary Tree
https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
*/
// 2019-02-21
package lca
// TreeNode Definition for TreeNode.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
if root == nil || root == p || root == q {
return root
}
left := lowestCommonAncestor(root.Left, p, q)
right := lowestCommonAncestor(root.Right, p, q)
if left != nil && right != nil {
return root
}
if left != nil {
return left
}
return right
}
================================================
FILE: solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca_test.go
================================================
package lca
import "testing"
func TestLCA(t *testing.T) {
type arg struct {
root, p, q *TreeNode
}
tree := createBinaryTree([]int{6, 2, 8, 0, 4, 7, 9, -1, 1, 3, 5})
testCases := []arg{
{root: tree, p: tree.Left.Right.Left, q: tree.Left.Right.Right},
{p: &TreeNode{Val: 2}, q: &TreeNode{Val: 8}},
}
expected := []*TreeNode{{Val: 4}, nil}
for index, data := range testCases {
if res := lowestCommonAncestor(data.root, data.p, data.q); res != nil && res.Val != expected[index].Val {
t.Errorf("expected %v, got %v", expected[index], res)
} else if res == nil && res != expected[index] {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
root := &TreeNode{Val: nums[index]}
root.Left = performCreate(nums, 2*index+1)
root.Right = performCreate(nums, 2*index+2)
return root
}
================================================
FILE: solutions/0237_delete_node_in_a_linked_list/dniall.go
================================================
/*
237. Delete Node in a Linked List
https://leetcode.com/problems/delete-node-in-a-linked-list/
Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.
Note:
The linked list will have at least two elements.
All of the nodes' values will be unique.
The given node will not be the tail and it will always be a valid node of the linked list.
Do not return anything from your function.
*/
// time: 2019-01-07
package dniall
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(1)
// space complexity: O(1)
func deleteNode(node *ListNode) {
// The linked list will have at least two elements.
// All the nodes' values will be unique.
// The given node will not be the tail and it will always be a valid node of the linked list.
node.Val = node.Next.Val
node.Next = node.Next.Next
}
================================================
FILE: solutions/0237_delete_node_in_a_linked_list/dniall_test.go
================================================
package dniall
import (
"reflect"
"testing"
)
func createSinglyLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
func TestDeleteNode(t *testing.T) {
root := createSinglyLinkedList([]int{4, 5, 1, 9})
node := root.Next
expected := createSinglyLinkedList([]int{4, 1, 9})
if deleteNode(node); !reflect.DeepEqual(expected, root) {
t.Errorf("expected %v, got %v", expected, root)
}
}
================================================
FILE: solutions/0257_binary_tree_paths/binary_tree_paths.go
================================================
/*
257. Binary Tree Paths
https://leetcode.com/problems/binary-tree-paths/
Given a binary tree, return all root-to-leaf paths.
Note: A leaf is a node with no children.
*/
// time: 2019-01-07
package btp
import "strconv"
// TreeNode Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// recursive
// time complexity: O(n), where n is the nodes number in the tree.
// space complexity: O(h), where h is the height of the tree.
func binaryTreePaths(root *TreeNode) []string {
if root == nil {
return []string{}
}
var res []string
if root.Left == nil && root.Right == nil {
return append(res, strconv.Itoa(root.Val))
}
if root.Left != nil {
for _, i := range binaryTreePaths(root.Left) {
res = append(res, strconv.Itoa(root.Val)+"->"+i)
}
}
if root.Right != nil {
for _, i := range binaryTreePaths(root.Right) {
res = append(res, strconv.Itoa(root.Val)+"->"+i)
}
}
return res
}
================================================
FILE: solutions/0257_binary_tree_paths/binary_tree_paths_test.go
================================================
package btp
import (
"reflect"
"testing"
)
func createBinaryTree(nums []int) *TreeNode {
return performCreate(nums, 0)
}
func performCreate(nums []int, index int) *TreeNode {
if index >= len(nums) {
return nil
}
tree := TreeNode{Val: nums[index]}
tree.Left = performCreate(nums, 2*index+1)
tree.Right = performCreate(nums, 2*index+2)
return &tree
}
func TestBinaryTreePaths(t *testing.T) {
testCases := []*TreeNode{
createBinaryTree([]int{1, 2, 3, 4, 5}),
nil,
}
expected := [][]string{
{"1->2->4", "1->2->5", "1->3"},
{},
}
for index, root := range testCases {
if res := binaryTreePaths(root); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
================================================
FILE: solutions/0258_add_digits/add_digits.go
================================================
/*
258. Add Digits
https://leetcode.com/problems/add-digits/
Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
*/
// time: 2019-01-07
package ad
// time complexity: O( log num )
// space complexity: O(1)
func addDigits(num int) int {
// num is a non-negative integer
for num > 9 {
num = performAdd(num)
}
return num
}
func performAdd(num int) (res int) {
for num > 0 {
res += num % 10
num /= 10
}
return
}
// time complexity: O(1)
// space complexity: O(1)
func addDigits1(num int) int {
/*
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
1 2 3 4 5 6 7 8 9 10/1
20 21 22 23 24 25 26 27 28 29
2 3 4 5 6 7 8 9 10/1 11/2
*/
return (num-1)%9 + 1
}
================================================
FILE: solutions/0258_add_digits/add_digits_test.go
================================================
package ad
import "testing"
func TestAddDigits(t *testing.T) {
num := 38
expected := 2
testFuncs := []func(int) int{
addDigits,
addDigits1,
}
for _, function := range testFuncs {
if res := function(num); res != expected {
t.Errorf("expected %d, got %d", expected, res)
}
}
}
================================================
FILE: solutions/0283_move_zeroes/move_zeroes.go
================================================
/*
283. Move Zeroes
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
*/
package movezeroes
// Time complexity: O(n)
// Space complexity: O(1)
func moveZeroes(nums []int) {
var k int
for i := range nums {
if nums[i] != 0 {
if k != i {
nums[i], nums[k] = nums[k], nums[i]
}
k++
}
}
}
================================================
FILE: solutions/0283_move_zeroes/move_zeroes2.go
================================================
/*
283. Move Zeroes
https://leetcode.com/problems/move-zeroes/
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative order of the non-zero elements.
*/
package movezeroes
// Time complexity: O(n)
// Space complexity: O(1)
func moveZeroes2(nums []int) {
var k int
for i := range nums {
if nums[i] != 0 {
if k != i {
nums[k] = nums[i]
}
k++
}
}
for i := k; i < len(nums); i++ {
nums[i] = 0
}
}
================================================
FILE: solutions/0283_move_zeroes/move_zeroes2_test.go
================================================
package movezeroes
import (
"reflect"
"testing"
)
func TestMoveZeroes2(t *testing.T) {
testData := [][]int{
{0, 1, 0, 3, 12},
}
expectedData := [][]int{
{1, 3, 12, 0, 0},
}
for index, data := range testData {
if moveZeroes2(data); !reflect.DeepEqual(data, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], data)
}
}
}
================================================
FILE: solutions/0283_move_zeroes/move_zeroes_test.go
================================================
package movezeroes
import (
"reflect"
"testing"
)
func TestMoveZeroes(t *testing.T) {
testData := [][]int{
{0, 1, 0, 3, 12},
}
expectedData := [][]int{
{1, 3, 12, 0, 0},
}
for index, data := range testData {
if moveZeroes(data); !reflect.DeepEqual(data, expectedData[index]) {
t.Errorf("expected %v, got %v", expectedData[index], data)
}
}
}
================================================
FILE: solutions/0300_longest_increasing_subsequence/lis.go
================================================
/*
300. Longest Increasing Subsequence
https://leetcode.com/problems/longest-increasing-subsequence/
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
Follow up:
Could you improve it to O(n log n) time complexity?
*/
package lis
import "leetcode/utils"
// Dynamic Programming
// TIme complexity: O(n^2)
// Space Complexity: O(n)
func lengthOfLIS(nums []int) int {
n := len(nums)
if n == 0 {
return 0
}
memo := make([]int, n)
for i := 0; i < n; i++ {
memo[i] = 1
}
for i := 1; i < n; i++ {
for j := 0; j < i; j++ {
if nums[j] < nums[i] {
memo[i] = utils.CalcMaxInt(memo[i], 1+memo[j])
}
}
}
return utils.CalcMaxInt(memo...)
}
================================================
FILE: solutions/0300_longest_increasing_subsequence/lis_test.go
================================================
package lis
import (
"os"
"testing"
)
func TestLIS(t *testing.T) {
testData := [][]int{
{10, 9, 2, 5, 3, 7, 101, 18},
{},
}
expectedData := []int{4, 0}
for index, data := range testData {
if res := lengthOfLIS(data); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
func TestMain(m *testing.M) {
os.Exit(m.Run())
}
================================================
FILE: solutions/0303_range_sum_query/rsqim.go
================================================
/*
303. Range Sum Query - Immutable
https://leetcode.com/problems/range-sum-query-immutable/
Given an integer array nums,
find the sum of the elements between indices i and j (i ≤ j), inclusive.
*/
// time: 2018-12-28
package rsqim
// NumArray store sum of nums sub-list.
type NumArray struct {
sum []int
}
// Constructor make NumArray instance.
func Constructor(nums []int) NumArray {
nA := NumArray{sum: make([]int, 1)}
for _, num := range nums {
nA.sum = append(nA.sum, nA.sum[len(nA.sum)-1]+num)
}
return nA
}
// SumRange find the sum of the elements between indices i and j(i <= j), inclusive.
func (na *NumArray) SumRange(i int, j int) int {
j++
return na.sum[j] - na.sum[i]
}
================================================
FILE: solutions/0303_range_sum_query/rsqim_test.go
================================================
package rsqim
import "testing"
func TestSumRange(t *testing.T) {
nums := []int{-2, 0, 3, -5, 2, -1}
ranges := [][]int{
{0, 2},
{2, 5},
{0, 5},
}
expected := []int{1, -1, -3}
obj := Constructor(nums)
for index, section := range ranges {
if res := obj.SumRange(section[0], section[1]); res != expected[index] {
t.Errorf("expected %d, got %d", expected[index], res)
}
}
}
================================================
FILE: solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut.go
================================================
/*
307. Range Sum Query - Mutable
https://leetcode.com/problems/range-sum-query-mutable/
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
The update(i, val) function modifies nums by updating the element at index i to val.
Note:
The array is only modifiable by the update function.
You may assume the number of calls to update and sumRange function is distributed evenly.
*/
// time: 2019-01-29
// 线段树时间复杂度为:O(log n)
package rsqm
// NumArray 线段树
type NumArray struct {
segmentTree []int
data []int
}
// Constructor 线段树生成函数
func Constructor(nums []int) NumArray {
na := NumArray{segmentTree: make([]int, len(nums)*4), data: nums[:]}
na.buildSegmentTree(0, 0, len(na.data)-1)
return na
}
func (na *NumArray) buildSegmentTree(treeIndex, left, right int) {
// 线段树处理的数据不能为空。
//if right < left {
// return
//}
if left == right {
na.segmentTree[treeIndex] = na.data[left]
return
}
mid := left + (right-left)>>1
leftTreeIndex := 2*treeIndex + 1
rightTreeIndex := 2*treeIndex + 2
na.buildSegmentTree(leftTreeIndex, left, mid)
na.buildSegmentTree(rightTreeIndex, mid+1, right)
na.segmentTree[treeIndex] = na.segmentTree[leftTreeIndex] + na.segmentTree[rightTreeIndex]
}
// Update 线段树更新操作。
func (na *NumArray) Update(i int, val int) {
na.setter(0, 0, len(na.data)-1, i, val)
}
func (na *NumArray) setter(treeIndex, left, right, index, val int) {
if left == right {
na.segmentTree[treeIndex] = val
return
}
mid := left + (right-left)>>1
leftTreeIndex := 2*treeIndex + 1
rightTreeIndex := 2*treeIndex + 2
if index >= mid+1 {
na.setter(rightTreeIndex, mid+1, right, index, val)
} else {
na.setter(leftTreeIndex, left, mid, index, val)
}
na.segmentTree[treeIndex] = na.segmentTree[leftTreeIndex] + na.segmentTree[rightTreeIndex]
}
// SumRange 线段树查询
func (na *NumArray) SumRange(i int, j int) int {
return na.query(0, 0, len(na.data)-1, i, j)
}
func (na *NumArray) query(treeIndex, left, right, queryL, queryR int) int {
if left == queryL && right == queryR {
return na.segmentTree[treeIndex]
}
mid := left + (right-left)>>1
leftTreeIndex := 2*treeIndex + 1
rightTreeIndex := 2*treeIndex + 2
if queryL >= mid+1 {
return na.query(rightTreeIndex, mid+1, right, queryL, queryR)
} else if queryR <= mid {
return na.query(leftTreeIndex, left, mid, queryL, queryR)
} else {
return na.query(leftTreeIndex, left, mid, queryL, mid) + na.query(rightTreeIndex, mid+1, right, mid+1, queryR)
}
}
================================================
FILE: solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut_test.go
================================================
package rsqm
import "testing"
func TestNumArray(t *testing.T) {
nums := []int{1, 2, 3, 6, 7, 8, 9, 3, 4, 2, 5}
na := Constructor(nums)
if res := na.SumRange(4, 9); res != 33 {
t.Errorf("expected %d, got %d", 43, res)
}
na.Update(6, 10)
if res := na.SumRange(4, 9); res != 34 {
t.Errorf("expected %d, got %d", 44, res)
}
}
================================================
FILE: solutions/0328_odd_even_linked_list/odd_even_linked_list.go
================================================
/*
328. Odd Even Linked List
https://leetcode.com/problems/odd-even-linked-list/
Given a singly linked list, group all odd nodes together followed by the even nodes.
Please note here we are talking about the node number and not the value in the nodes.
You should try to do it in place.
The program should run in O(1) space complexity and O(nodes) time complexity.
Note:
The relative order inside both the even and odd groups should remain as it was in the input.
The first node is considered odd, the second node even and so on ...
*/
// time: 2019-01-07
package oddevenlinkedlist
// ListNode Definition for singly-linked list.
type ListNode struct {
Val int
Next *ListNode
}
// time complexity: O(n)
// space complexity: O(1)
func oddEvenList(head *ListNode) *ListNode {
if head == nil {
return head
}
var (
odd = head
evenHead = head.Next
even = evenHead
)
for even != nil && even.Next != nil {
odd.Next = even.Next
odd = odd.Next
even.Next = odd.Next
even = even.Next
}
odd.Next = evenHead
return head
}
================================================
FILE: solutions/0328_odd_even_linked_list/odd_even_linked_list_test.go
================================================
package oddevenlinkedlist
import (
"reflect"
"testing"
)
func createSinglyLinkedList(nums []int) *ListNode {
head := &ListNode{}
cur := head
for _, num := range nums {
cur.Next = &ListNode{Val: num}
cur = cur.Next
}
return head.Next
}
func TestOddEvenList(t *testing.T) {
testCases := []*ListNode{
createSinglyLinkedList([]int{2, 1, 3, 5, 6, 4, 7}),
nil,
}
expected := []*ListNode{
createSinglyLinkedList([]int{2, 3, 6, 7, 1, 5, 4}),
nil,
}
for index, head := range testCases {
if res := oddEvenList(head); !reflect.DeepEqual(res, expected[index]) {
t.Errorf("expected %v, got %v", expected[index], res)
}
}
}
================================================
FILE: solutions/0343_integer_break/integer_break.go
================================================
/*
343. Integer Break
https://leetcode.com/problems/integer-break
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.
*/
package integerbreak
import "leetcode/utils"
// recursion
/*
func integerBreak(n int) int {
if n == 1 {
return 1
}
res := utils.MinInt
for i := 1; i < n; i++ {
res, _ = utils.CalcMaxInt(res, i*(n-i), i*integerBreak(n-i))
}
return res
}
*/
// memory search
/*
func integerBreak(n int) int {
memo := make([]int, n+1)
for i := 0; i <= n; i++ {
memo[i] = -1
}
return breakInt(n, memo)
}
func breakInt(n int, memo []int) int {
if n == 1 {
return 1
}
if memo[n] != -1 {
return memo[n]
}
res := utils.MinInt
for i := 1; i < n; i++ {
res, _ = utils.CalcMaxInt(res, i*(n-i), i*breakInt(n-i, memo))
}
memo[n] = res
return res
}
*/
// dynamic programming
// Time complexity: O(n^2)
// Space complexity: O(n+1)
func integerBreak(n int) int {
// memo[i]表示将数字i分割(至少分割成两部分)后得到的最大乘积.
memo := make([]int, n+1)
memo[1] = 1
for i := 2; i <= n; i++ {
// 求解memo[i]
for j := 1; j <= i-1; j++ {
memo[i] = utils.CalcMaxInt(memo[i], j*(i-j), j*memo[i-j])
}
}
return memo[n]
}
================================================
FILE: solutions/0343_integer_break/integer_break_test.go
================================================
package integerbreak
import "testing"
func TestIntegerBreak(t *testing.T) {
testData := []int{2, 10, 34}
expectedData := []int{1, 36, 236196}
for index, data := range testData {
if res := integerBreak(data); res != expectedData[index] {
t.Errorf("expected %d, got %d", expectedData[index], res)
}
}
}
================================================
FILE: solutions/0344_reverse_string/reverse_string.go
================================================
/*
344. Reverse String
https://leetcode.com/problems/reverse-string/
Write a function that takes a string as input and returns the string reversed.
*/
// time: 2018-12-26
package reversestring
// double index
// time complexity: O(n)
// space complexity: O(1)
func reverseString(s string) string {
var (
l int
r = len(s) - 1
)
for r > l {
charL := s[l]
charR := s[r]
s = s[:r] + string(charL) + s[r+1:]
s = s[:l] + string(charR) + s[l+1:]
r--
l++
}
return s
}
// double index
// time complexity: O(n)
// space complexity: O(n)
func reverseString1(s string) string {
sLen := len(s)
bytes := []byte(s)
for i := 0; i < sLen/2; i++ {
bytes[i], bytes[sLen-i-1] = bytes[sLen-i-1], bytes[i]
}
return string(bytes)
}
================================================
FILE: solutions/0344_reverse_string/reverse_string_test.go
================================================
package reversestring
import "testing"
func TestReverseString(t *testing.T) {
testCases := []string{
"hello",
"A man, a plan, a canal: Panama",
"",
"ab",
}
expected := []string{
"olleh",
"amanaP :lanac a ,nalp a ,nam A",
"",
"ba",
}
for index, data := range testCases {
if res := reverseString(data); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
func TestReverseString1(t *testing.T) {
testCases := []string{
"hello",
"A man, a plan, a canal: Panama",
"",
"ab",
}
expected := []string{
"olleh",
"amanaP :lanac a ,nalp a ,nam A",
"",
"ba",
}
for index, data := range testCases {
if res := reverseString1(data); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
================================================
FILE: solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go
================================================
/*
345. Reverse Vowels of a String
https://leetcode.com/problems/reverse-vowels-of-a-string/
Write a function that takes a string as input and reverse only the vowels of a string.
*/
// time: 2018-12-26
package reversevowels
// time complexity: O(n)
// space complexity: O(1)
func reverseVowels(s string) string {
var (
l int
r = len(s) - 1
)
for r > l {
for r >= 0 && !isVowel(s[r]) {
r--
}
for l < len(s) && !isVowel(s[l]) {
l++
}
if l >= r {
break
}
charL := s[l]
charR := s[r]
s = s[:r] + string(charL) + s[r+1:]
s = s[:l] + string(charR) + s[l+1:]
r--
l++
}
return s
}
// time complexity: O(n)
// space complexity: O(n)
func reverseVowels1(s string) string {
bytes := []byte(s)
var (
l int
r = len(bytes) - 1
)
for r > l {
for r >= 0 && !isVowel(s[r]) {
r--
}
for l < len(bytes) && !isVowel(s[l]) {
l++
}
if l >= r {
break
}
bytes[l], bytes[r] = bytes[r], bytes[l]
l++
r--
}
return string(bytes)
}
func isVowel(char byte) bool {
vowels := [...]byte{'a', 'o', 'e', 'i', 'u', 'A', 'O', 'E', 'I', 'U'}
for _, k := range vowels {
if char == k {
return true
}
}
return false
}
================================================
FILE: solutions/0345_reverse_vowels_of_a_string/reverse_vowels_test.go
================================================
package reversevowels
import "testing"
func TestReverseVowels(t *testing.T) {
testCases := []string{
"hello",
"leetcode",
"aA",
"a.b,.",
}
expected := []string{
"holle",
"leotcede",
"Aa",
"a.b,.",
}
for index, data := range testCases {
if res := reverseVowels(data); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
func TestReverseVowels1(t *testing.T) {
testCases := []string{
"hello",
"leetcode",
"aA",
"a.b,.",
}
expected := []string{
"holle",
"leotcede",
"Aa",
"a.b,.",
}
for index, data := range testCases {
if res := reverseVowels1(data); res != expected[index] {
t.Errorf("expected %s, got %s", expected[index], res)
}
}
}
================================================
FILE: solutions/0347_top_k_frequent_elements/topkfe.go
================================================
/*
347. Top K Frequent Elements
https://leetcode.com/problems/top-k-frequent-elements/
Given a non-empty array of integers, return the k most frequent elements.
Note:
You may assume k is always valid, 1 ≤ k ≤ number of unique elements.
Your algorithm's time complexity must be better than O(n log n), where n is the array's size.
*/
// time: 2019-01-08
package topkfe
import "container/heap"
// using priority
// time complexity: O(n log n)
// space complexity: O(n)
func topKFrequent(nums []int, k int) []int {
count := make(map[int]int)
for _, num := range nums {
if _, ok := count[num]; !ok {
count[num] = 1
} else {
count[num]++
}
}
nums_ := make(Nums, 0)
for num, cnt := range count {
nums_ = append(nums_, Num{Val: num, Count: cnt})
}
heap.Init(&nums_)
var res []int
for i := 0; i < k; i++ {
num := heap.Pop(&nums_).(Num)
res = append(res, num.Val)
}
return res
}
// Num stores its value and frequency as Count.
type Num struct {
Val int
Count int
}
// Nums struct for impl Interface
type Nums []Num
// Len sort Interface
func (n Nums) Len() int { return len(n) }
// Swap sort Interface
func (n Nums) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
// Less sort Interface
func (n Nums) Less(i, j int) bool { return n[i].Count >= n[j].Count }
// Push heap Interface
func (n *Nums) Push(num interface{}) {
m := num.(Num)
*n = append(*n, m)
}
// Pop heap Interface
func (n *Nums) Pop() interface{} {
res := (*n)[len(*n)-1]
*n = (*n)[:len(*n)-1]
return res
}
================================================
FILE: solutions/0347_top_k_frequent_elements/topkfe_test.go
================================================
package topkfe
import (
"reflect"
"testing"
)
func TestTopKFrequent(t *testing.T) {
nu
gitextract_t27zlmsi/
├── .codacy.yml
├── .codecov.yml
├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── _config.yml
├── bak.README.md
├── docs/
│ ├── _config.yml
│ └── index.md
├── go.mod
├── solutions/
│ ├── 0001_two_sum/
│ │ ├── twosum.go
│ │ └── twosum_test.go
│ ├── 0002_add_two_numbers/
│ │ ├── add_two_numbers.go
│ │ └── add_two_numbers_test.go
│ ├── 0003_longest_substring_without_repeating_characters/
│ │ ├── longest_substring_without_repeating_characters.go
│ │ └── longest_substring_without_repeating_characters_test.go
│ ├── 0004_median_of_two_sorted_arrays/
│ │ ├── motsa.go
│ │ └── motsa_test.go
│ ├── 0007_reverse_integer/
│ │ ├── reverse_integer.go
│ │ └── reverse_integer_test.go
│ ├── 0009_palindrome_number/
│ │ ├── palindrome_number.go
│ │ └── palindrome_number_test.go
│ ├── 0011_container_with_most_water/
│ │ ├── container_with_most_water.go
│ │ └── container_with_most_water_test.go
│ ├── 0013_roman_to_integer/
│ │ ├── roman_to_integer.go
│ │ └── roman_to_integer_test.go
│ ├── 0014_longest_common_prefix/
│ │ ├── lcp.go
│ │ └── lcp_test.go
│ ├── 0015_3Sum/
│ │ ├── 3sum.go
│ │ └── 3sum_test.go
│ ├── 0017_letter_combination_of_a_phone_number/
│ │ ├── letter_combination_of_phone_number.go
│ │ └── letter_combination_of_phone_number_test.go
│ ├── 0019_remove_nth_node_from_end_of_list/
│ │ ├── remove_nth_node_from_end_of_list.go
│ │ └── remove_nth_node_from_end_of_list_test.go
│ ├── 0020_valid_parentheses/
│ │ ├── valid_parentheses.go
│ │ └── valid_parentheses_test.go
│ ├── 0021_merge_two_sorted_lists/
│ │ ├── mergeTwoLists.go
│ │ └── mergeTwoLists_test.go
│ ├── 0023_merge_k_sorted_lists/
│ │ ├── mksl.go
│ │ └── mksl_test.go
│ ├── 0024_swap_nodes_in_pairs/
│ │ ├── swap_nodes_in_pairs.go
│ │ └── swap_nodes_in_pairs_test.go
│ ├── 0025_reverse_nodes_in_k_group/
│ │ ├── reverse_node_k_group.go
│ │ └── reverse_node_k_group_test.go
│ ├── 0026_remove_duplicates_from_sorted_array/
│ │ ├── rdfsa.go
│ │ └── rdfsa_test.go
│ ├── 0027_remove_element/
│ │ ├── remove_element.go
│ │ └── remove_element_test.go
│ ├── 0028_implement_strstr/
│ │ ├── implement_strstr.go
│ │ └── implement_strstr_test.go
│ ├── 0033_search_in_rotated_sorted_array/
│ │ ├── search_in_rotated_sorted_array.go
│ │ └── search_in_rotated_sorted_array_test.go
│ ├── 0034_find_first_and_last_position_of_element_in_sorted_array/
│ │ ├── find_first_and_last_position_of_element_in_sorted_array.go
│ │ └── find_first_and_last_position_of_element_in_sorted_array_test.go
│ ├── 0035_search_insert_position/
│ │ ├── search_insert_position.go
│ │ └── search_insert_position_test.go
│ ├── 0048_rotate_image/
│ │ ├── rotate_image.go
│ │ └── rotate_image_test.go
│ ├── 0053_maximum_subarray/
│ │ ├── maximum_subarray.go
│ │ └── maximum_subarray_test.go
│ ├── 0058_length_of_last_word/
│ │ ├── len_of_last_word.go
│ │ └── len_of_last_word_test.go
│ ├── 0061_rotate_list/
│ │ ├── rotate_list.go
│ │ └── rotate_list_test.go
│ ├── 0062_unique_paths/
│ │ ├── unique_paths.go
│ │ └── unique_paths_test.go
│ ├── 0063_unique_paths_2/
│ │ ├── unique_paths2.go
│ │ └── unique_paths2_test.go
│ ├── 0064_minimum_path_sum/
│ │ ├── minimum_path_sum.go
│ │ └── minimum_path_sum_test.go
│ ├── 0066_plus_one/
│ │ ├── plus_one.go
│ │ └── plus_one_test.go
│ ├── 0067_add_binary/
│ │ ├── add_binary.go
│ │ └── add_binary_test.go
│ ├── 0069_sqrtx/
│ │ ├── sqrtx.go
│ │ └── sqrtx_test.go
│ ├── 0070_climbing_stairs/
│ │ ├── climbing_stairs.go
│ │ └── climbing_stairs_test.go
│ ├── 0075_sort_colors/
│ │ ├── sort_colors.go
│ │ └── sort_colors_test.go
│ ├── 0076_minimum_window_substring/
│ │ ├── minimum_window_substring.go
│ │ └── minimum_window_substring_test.go
│ ├── 0077_combinations/
│ │ ├── combinations.go
│ │ └── combinations_test.go
│ ├── 0079_word_search/
│ │ ├── word_search.go
│ │ └── word_search_test.go
│ ├── 0080_remove_duplicates_from_sorted_array2/
│ │ ├── rdfsa2.go
│ │ └── rdfsa2_test.go
│ ├── 0082_remove_duplicates_from_sorted_list_2/
│ │ ├── rdfsl.go
│ │ └── rdfsl_test.go
│ ├── 0083_remove_duplicates_from_sorted_list/
│ │ ├── rdfsl.go
│ │ └── rdfsl_test.go
│ ├── 0086_partition_list/
│ │ ├── partition_list.go
│ │ └── partition_list_test.go
│ ├── 0088_merge_sorted_array/
│ │ ├── msa.go
│ │ └── msa_test.go
│ ├── 0092_reverse_linked_list_2/
│ │ ├── reverse_linked_list2.go
│ │ └── reverse_linked_list2_test.go
│ ├── 0094_binary_tree_inorder_traversal/
│ │ ├── binary_tree_inorder_traversal.go
│ │ └── binary_tree_inorder_traversal_test.go
│ ├── 0100_same_tree/
│ │ ├── same_tree.go
│ │ └── same_tree_test.go
│ ├── 0101_symmetric_tree/
│ │ ├── symmetric_tree.go
│ │ └── symmetric_tree_test.go
│ ├── 0102_binary_tree_level_order_traversal/
│ │ ├── binary_tree_level_order_traversal.go
│ │ └── binary_tree_level_order_traversal_test.go
│ ├── 0104_maximun_depth_of_binary_tree/
│ │ ├── maxdobt.go
│ │ └── maxdobt_test.go
│ ├── 0107_binary_tree_level_order_traversal_2/
│ │ ├── binary_tree_level_order_traversal2.go
│ │ └── binary_tree_level_order_traversal2_test.go
│ ├── 0111_minimum_depth_of_binary_tree/
│ │ ├── minimum_depth_of_binary_tree.go
│ │ └── minimum_depth_of_binary_tree_test.go
│ ├── 0112_path_sum/
│ │ ├── path_sum.go
│ │ └── path_sum_test.go
│ ├── 0120_triangle/
│ │ ├── triangle.go
│ │ └── triangle_test.go
│ ├── 0121_best_time_to_buy_and_sell_stock/
│ │ ├── maxprofit.go
│ │ └── maxprofit_test.go
│ ├── 0122_best_time_to_buy_and_sell_stock_2/
│ │ ├── maxprofit.go
│ │ └── maxprofit_test.go
│ ├── 0125_valid_palindrome/
│ │ ├── valid_palindrome.go
│ │ └── valid_palindrome_test.go
│ ├── 0136_single_number/
│ │ ├── single_number.go
│ │ └── single_number_test.go
│ ├── 0144_binary_tree_preorder_traversal/
│ │ ├── binary_tree_preorder_traversal.go
│ │ └── binary_tree_preorder_traversal_test.go
│ ├── 0150_evaluate_reverse_polish_notation/
│ │ ├── evaluate_reverse_polish_notation.go
│ │ └── evaluate_reverse_polish_notation_test.go
│ ├── 0153_find_minimum_in_rotated_sorted_array/
│ │ ├── fmirsa.go
│ │ └── fmirsa_test.go
│ ├── 0155_min_stack/
│ │ ├── min_stack.go
│ │ └── min_stack_test.go
│ ├── 0165_compare_version_numbers/
│ │ ├── compare_version_numbers.go
│ │ └── compare_version_numbers_test.go
│ ├── 0167_two_sum2/
│ │ ├── two_sum2.go
│ │ └── two_sum2_test.go
│ ├── 0179_largest_number/
│ │ ├── ln.go
│ │ └── ln_test.go
│ ├── 0198_house_robber/
│ │ ├── house_robber.go
│ │ └── house_robber_test.go
│ ├── 0200_number_of_island/
│ │ ├── number_of_island.go
│ │ └── number_of_island_test.go
│ ├── 0203_remove_linked_list_elements/
│ │ ├── remove_linked_list_elements.go
│ │ └── remove_linked_list_elements_test.go
│ ├── 0206_reverse_linked_list/
│ │ ├── reverse_linked_list.go
│ │ └── reverse_linked_list_test.go
│ ├── 0208_implement_trie_prefix_tree/
│ │ ├── impltrie.go
│ │ └── impltrie_test.go
│ ├── 0209_minimum_size_subarray_sum/
│ │ ├── minimum_size_subarray_sum.go
│ │ └── minimum_size_subarray_sum_test.go
│ ├── 0211_add_and_search_word/
│ │ ├── add_and_search_word.go
│ │ └── add_and_search_word_test.go
│ ├── 0215_kth_largest_element_in_an_array/
│ │ ├── kthleiaa.go
│ │ └── kthleiaa_test.go
│ ├── 0217_contains_duplicate/
│ │ ├── contains_duplicate.go
│ │ └── contains_duplicate_test.go
│ ├── 0219_contains_duplicate_2/
│ │ ├── contains_duplicate_2.go
│ │ └── contains_duplicate_2_test.go
│ ├── 0226_invert_binary_tree/
│ │ ├── invert_binary_tree.go
│ │ └── invert_binary_tree_test.go
│ ├── 0235_lowest_common_ancestor_of_a_binary_search_tree/
│ │ ├── lcaoabst.go
│ │ └── lcaoabst_test.go
│ ├── 0236_Lowest_Common_Ancestor_of_a_Binary_Tree/
│ │ ├── lca.go
│ │ └── lca_test.go
│ ├── 0237_delete_node_in_a_linked_list/
│ │ ├── dniall.go
│ │ └── dniall_test.go
│ ├── 0257_binary_tree_paths/
│ │ ├── binary_tree_paths.go
│ │ └── binary_tree_paths_test.go
│ ├── 0258_add_digits/
│ │ ├── add_digits.go
│ │ └── add_digits_test.go
│ ├── 0283_move_zeroes/
│ │ ├── move_zeroes.go
│ │ ├── move_zeroes2.go
│ │ ├── move_zeroes2_test.go
│ │ └── move_zeroes_test.go
│ ├── 0300_longest_increasing_subsequence/
│ │ ├── lis.go
│ │ └── lis_test.go
│ ├── 0303_range_sum_query/
│ │ ├── rsqim.go
│ │ └── rsqim_test.go
│ ├── 0307_Range_Sum_Query_Mutable/
│ │ ├── range_sum_query_mut.go
│ │ └── range_sum_query_mut_test.go
│ ├── 0328_odd_even_linked_list/
│ │ ├── odd_even_linked_list.go
│ │ └── odd_even_linked_list_test.go
│ ├── 0343_integer_break/
│ │ ├── integer_break.go
│ │ └── integer_break_test.go
│ ├── 0344_reverse_string/
│ │ ├── reverse_string.go
│ │ └── reverse_string_test.go
│ ├── 0345_reverse_vowels_of_a_string/
│ │ ├── reverse_vowels.go
│ │ └── reverse_vowels_test.go
│ ├── 0347_top_k_frequent_elements/
│ │ ├── topkfe.go
│ │ └── topkfe_test.go
│ ├── 0349_intersection_of_2_arrays/
│ │ ├── intersection_of_two_arrays.go
│ │ └── intersection_of_two_arrays_test.go
│ ├── 0350_intersection_of_two_arrays2/
│ │ ├── intersection_of_two_arrays2.go
│ │ └── intersection_of_two_arrays2_test.go
│ ├── 0376_wiggle_subsequence/
│ │ ├── wiggle_subsequence.go
│ │ └── wiggle_subsequence_test.go
│ ├── 0392_is_subsequence/
│ │ ├── is_subsequence.go
│ │ └── is_subsequence_test.go
│ ├── 0404_sum_of_left_leaves/
│ │ ├── sum_of_left_leaves.go
│ │ └── sum_of_left_leaves_test.go
│ ├── 0416_partition_equal_subset_sum/
│ │ ├── partition_equal_subset_sum.go
│ │ └── partition_equal_subset_sum_test.go
│ ├── 0435_non_overlapping_intervals/
│ │ ├── dp_solution.go
│ │ ├── greedy_solution.go
│ │ ├── interval.go
│ │ └── solution_test.go
│ ├── 0437_path_sum_3/
│ │ ├── path_sum_3.go
│ │ └── path_sum_3_test.go
│ ├── 0438_all_anagrams_in_a_string/
│ │ ├── all_anagrams_in_a_string.go
│ │ └── all_anagrams_in_a_string_test.go
│ ├── 0447_number_of_boomerangs/
│ │ ├── number_of_boomerangs.go
│ │ └── number_of_boomerangs_test.go
│ ├── 0454_4sum2/
│ │ ├── 4sum2.go
│ │ └── 4sum2_test.go
│ ├── 0455_assign_cookies/
│ │ ├── assign_cookies.go
│ │ └── assign_cookies_test.go
│ ├── 0557_reverse_words_in_a_string_3/
│ │ ├── reverse_words_in_a_string_3.go
│ │ └── reverse_words_in_a_string_3_test.go
│ ├── 0674_longest_continuous_increasing_subsequence/
│ │ ├── lcis.go
│ │ └── lcis_test.go
│ ├── 0677_map_sum_pairs/
│ │ ├── map_sum_pairs.go
│ │ └── map_sum_pairs_test.go
│ ├── 0704_binary_search/
│ │ ├── binary_search.go
│ │ └── binary_search_test.go
│ ├── 0713_subarray_product_less_than_k/
│ │ ├── spltk.go
│ │ └── spltk_test.go
│ ├── 0717_1_bit_and_2_bit_characters/
│ │ ├── 1bitand2bitc.go
│ │ └── 1bitand2bitc_test.go
│ ├── 0728_self_dividing_numbers/
│ │ ├── self_dividing_numbers.go
│ │ └── self_dividing_numbers_test.go
│ ├── 0735_asteroid_collision/
│ │ ├── ac.go
│ │ └── ac_test.go
│ ├── 0747_largest_number_at_least_twice_of_others/
│ │ ├── largest_number_at_least_twice_of_others.go
│ │ └── largest_number_at_least_twice_of_others_test.go
│ ├── 0872_leaf_similar_trees/
│ │ ├── leaf_similar_trees.go
│ │ └── leaf_similar_trees_test.go
│ ├── 1021_Remove_Outermost_Parentheses/
│ │ ├── remove_outmost_parentheses.go
│ │ └── remove_outmost_parentheses_test.go
│ ├── 148_Sort_List/
│ │ ├── sortlist.go
│ │ └── sortlist_test.go
│ ├── 304_Range_Sum_Query_2D/
│ │ ├── rsq.go
│ │ └── rsq_test.go
│ └── README.md
├── ut.bash
└── utils/
├── infinite.go
├── maxint.go
├── maxint_test.go
├── minint.go
├── minint_test.go
├── set.go
└── set_test.go
SYMBOL INDEX (451 symbols across 239 files)
FILE: solutions/0001_two_sum/twosum.go
function twoSum (line 23) | func twoSum(nums []int, target int) []int {
function twoSum1 (line 39) | func twoSum1(nums []int, target int) []int {
FILE: solutions/0001_two_sum/twosum_test.go
function TestTwoSum (line 8) | func TestTwoSum(t *testing.T) {
FILE: solutions/0002_add_two_numbers/add_two_numbers.go
type ListNode (line 20) | type ListNode struct
function addTwoNumbers1 (line 26) | func addTwoNumbers1(l1 *ListNode, l2 *ListNode) *ListNode {
function addTwoNumbers2 (line 78) | func addTwoNumbers2(l1 *ListNode, l2 *ListNode) *ListNode {
FILE: solutions/0002_add_two_numbers/add_two_numbers_test.go
function createSingleLinkedList (line 9) | func createSingleLinkedList(arr []int) *ListNode {
function TestAddTwoNumbers1 (line 20) | func TestAddTwoNumbers1(t *testing.T) {
function TestAddTwoNumbers2 (line 74) | func TestAddTwoNumbers2(t *testing.T) {
function TestMain (line 128) | func TestMain(m *testing.M) {
FILE: solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go
function lengthOfLongestSubstring (line 30) | func lengthOfLongestSubstring(s string) int {
FILE: solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters_test.go
function TestLengthOfLongestSubstring (line 5) | func TestLengthOfLongestSubstring(t *testing.T) {
FILE: solutions/0004_median_of_two_sorted_arrays/motsa.go
function findMedianSortedArrays (line 20) | func findMedianSortedArrays(nums1 []int, nums2 []int) float64 {
function findKth (line 56) | func findKth(nums1 []int, i int, nums2 []int, j int, k int) int {
FILE: solutions/0004_median_of_two_sorted_arrays/motsa_test.go
function TestFindMedianSortedArrays (line 7) | func TestFindMedianSortedArrays(t *testing.T) {
FILE: solutions/0007_reverse_integer/reverse_integer.go
function reverse (line 13) | func reverse(x int) int {
FILE: solutions/0007_reverse_integer/reverse_integer_test.go
function TestReverse (line 5) | func TestReverse(t *testing.T) {
FILE: solutions/0009_palindrome_number/palindrome_number.go
function isPalindrome (line 14) | func isPalindrome(x int) bool {
FILE: solutions/0009_palindrome_number/palindrome_number_test.go
function TestIsPalindrome (line 5) | func TestIsPalindrome(t *testing.T) {
FILE: solutions/0011_container_with_most_water/container_with_most_water.go
function maxArea (line 21) | func maxArea(height []int) int {
function maxArea1 (line 43) | func maxArea1(height []int) int {
function maxArea2 (line 61) | func maxArea2(height []int) int {
FILE: solutions/0011_container_with_most_water/container_with_most_water_test.go
function TestMaxArea (line 5) | func TestMaxArea(t *testing.T) {
function TestMaxArea1 (line 21) | func TestMaxArea1(t *testing.T) {
function TestMaxArea2 (line 37) | func TestMaxArea2(t *testing.T) {
FILE: solutions/0013_roman_to_integer/roman_to_integer.go
function romanToInt (line 11) | func romanToInt(s string) int {
FILE: solutions/0013_roman_to_integer/roman_to_integer_test.go
function TestRomanToInt (line 5) | func TestRomanToInt(t *testing.T) {
FILE: solutions/0014_longest_common_prefix/lcp.go
function longestCommonPrefix (line 15) | func longestCommonPrefix(strs []string) string {
FILE: solutions/0014_longest_common_prefix/lcp_test.go
function TestLongestCommonPrefix (line 5) | func TestLongestCommonPrefix(t *testing.T) {
FILE: solutions/0015_3Sum/3sum.go
function threeSum (line 12) | func threeSum(nums []int) [][]int {
FILE: solutions/0015_3Sum/3sum_test.go
function TestThreeSum (line 8) | func TestThreeSum(t *testing.T) {
FILE: solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go
function letterCombinations (line 39) | func letterCombinations(digits string) []string {
function findCombinations (line 49) | func findCombinations(digits string, index int, s string) {
FILE: solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number_test.go
function TestLetterCombinations (line 8) | func TestLetterCombinations(t *testing.T) {
FILE: solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go
type ListNode (line 12) | type ListNode struct
function removeNthFromEnd (line 19) | func removeNthFromEnd(head *ListNode, n int) *ListNode {
FILE: solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list_test.go
function TestRemoveNthFromEnd (line 8) | func TestRemoveNthFromEnd(t *testing.T) {
function createSingleLinkedList (line 31) | func createSingleLinkedList(arr []int) *ListNode {
FILE: solutions/0020_valid_parentheses/valid_parentheses.go
function isValid (line 41) | func isValid(s string) bool {
FILE: solutions/0020_valid_parentheses/valid_parentheses_test.go
function TestIsValid (line 5) | func TestIsValid(t *testing.T) {
FILE: solutions/0021_merge_two_sorted_lists/mergeTwoLists.go
type ListNode (line 16) | type ListNode struct
function mergeTwoLists (line 24) | func mergeTwoLists(l1 *ListNode, l2 *ListNode) *ListNode {
FILE: solutions/0021_merge_two_sorted_lists/mergeTwoLists_test.go
function createSingleLinkedList (line 8) | func createSingleLinkedList(arr []int) *ListNode {
function TestMergeTwoLists (line 19) | func TestMergeTwoLists(t *testing.T) {
FILE: solutions/0023_merge_k_sorted_lists/mksl.go
type ListNode (line 16) | type ListNode struct
function mergeKLists (line 24) | func mergeKLists(lists []*ListNode) *ListNode {
function siftUp (line 53) | func siftUp(lists []*ListNode, n int, k int) {
function mergeKLists1 (line 71) | func mergeKLists1(lists []*ListNode) *ListNode {
FILE: solutions/0023_merge_k_sorted_lists/mksl_test.go
function TestMergeKLists (line 8) | func TestMergeKLists(t *testing.T) {
function TestMergeKLists1 (line 46) | func TestMergeKLists1(t *testing.T) {
function createSingleList (line 78) | func createSingleList(nums []int) *ListNode {
FILE: solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go
type ListNode (line 12) | type ListNode struct
function swapPairs (line 19) | func swapPairs(head *ListNode) *ListNode {
FILE: solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs_test.go
function TestSwapPairs (line 8) | func TestSwapPairs(t *testing.T) {
function createSingleList (line 16) | func createSingleList(nums []int) *ListNode {
FILE: solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go
type ListNode (line 26) | type ListNode struct
function reverseKGroup (line 31) | func reverseKGroup(head *ListNode, k int) *ListNode {
function reverse (line 59) | func reverse(p **ListNode, s **ListNode) {
FILE: solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group_test.go
function createSingleLinkedList (line 8) | func createSingleLinkedList(arr []int) *ListNode {
function TestReverseKGroup (line 19) | func TestReverseKGroup(t *testing.T) {
FILE: solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go
function removeDuplicates (line 16) | func removeDuplicates(nums []int) int {
function nextDifferentCharacterIndex (line 38) | func nextDifferentCharacterIndex(nums []int, p int) int {
FILE: solutions/0026_remove_duplicates_from_sorted_array/rdfsa_test.go
function TestRemoveDuplicates (line 5) | func TestRemoveDuplicates(t *testing.T) {
FILE: solutions/0027_remove_element/remove_element.go
function removeElement (line 18) | func removeElement(nums []int, val int) int {
FILE: solutions/0027_remove_element/remove_element_test.go
function TestRemoveElement (line 5) | func TestRemoveElement(t *testing.T) {
FILE: solutions/0028_implement_strstr/implement_strstr.go
function strStr (line 19) | func strStr(haystack string, needle string) int {
FILE: solutions/0028_implement_strstr/implement_strstr_test.go
function TestStrStr (line 5) | func TestStrStr(t *testing.T) {
FILE: solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go
function search (line 35) | func search(nums []int, target int) int {
FILE: solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array_test.go
function TestSearch (line 5) | func TestSearch(t *testing.T) {
FILE: solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go
function searchRange (line 18) | func searchRange(nums []int, target int) []int {
function firstOccurance (line 35) | func firstOccurance(nums []int, target int) int {
function lastOccurance (line 52) | func lastOccurance(nums []int, target int) int {
function searchRange1 (line 71) | func searchRange1(nums []int, target int) []int {
function searchRange2 (line 100) | func searchRange2(nums []int, target int) []int {
FILE: solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array_test.go
function TestSearchRange (line 9) | func TestSearchRange(t *testing.T) {
FILE: solutions/0035_search_insert_position/search_insert_position.go
function searchInsert (line 18) | func searchInsert(nums []int, target int) int {
FILE: solutions/0035_search_insert_position/search_insert_position_test.go
function TestSearchInsert (line 5) | func TestSearchInsert(t *testing.T) {
FILE: solutions/0048_rotate_image/rotate_image.go
function rotate (line 19) | func rotate(matrix [][]int) {
FILE: solutions/0048_rotate_image/rotate_image_test.go
function TestRotate (line 8) | func TestRotate(t *testing.T) {
FILE: solutions/0053_maximum_subarray/maximum_subarray.go
function maxSubArray (line 19) | func maxSubArray(nums []int) int {
FILE: solutions/0053_maximum_subarray/maximum_subarray_test.go
function TestMaxSubarray (line 5) | func TestMaxSubarray(t *testing.T) {
FILE: solutions/0058_length_of_last_word/len_of_last_word.go
function lengthOfLastWord (line 17) | func lengthOfLastWord(s string) int {
FILE: solutions/0058_length_of_last_word/len_of_last_word_test.go
function TestLengthOfLastWord (line 5) | func TestLengthOfLastWord(t *testing.T) {
FILE: solutions/0061_rotate_list/rotate_list.go
type ListNode (line 28) | type ListNode struct
function rotateRight (line 33) | func rotateRight(head *ListNode, k int) *ListNode {
FILE: solutions/0061_rotate_list/rotate_list_test.go
function createSingleLinkedList (line 8) | func createSingleLinkedList(arr []int) *ListNode {
function TestRotateList (line 19) | func TestRotateList(t *testing.T) {
FILE: solutions/0062_unique_paths/unique_paths.go
function uniquePaths (line 71) | func uniquePaths(m int, n int) int {
FILE: solutions/0062_unique_paths/unique_paths_test.go
function TestUniquePaths (line 5) | func TestUniquePaths(t *testing.T) {
FILE: solutions/0063_unique_paths_2/unique_paths2.go
function uniquePathsWithObstacles (line 122) | func uniquePathsWithObstacles(obstacleGrid [][]int) int {
FILE: solutions/0063_unique_paths_2/unique_paths2_test.go
function TestUniquePaths2 (line 5) | func TestUniquePaths2(t *testing.T) {
FILE: solutions/0064_minimum_path_sum/minimum_path_sum.go
function minPathSum (line 68) | func minPathSum(grid [][]int) int {
FILE: solutions/0064_minimum_path_sum/minimum_path_sum_test.go
function TestMininumPathSum (line 5) | func TestMininumPathSum(t *testing.T) {
FILE: solutions/0066_plus_one/plus_one.go
function plusOne (line 19) | func plusOne(digits []int) []int {
FILE: solutions/0066_plus_one/plus_one_test.go
function TestPlusOne (line 8) | func TestPlusOne(t *testing.T) {
FILE: solutions/0067_add_binary/add_binary.go
function addBinary (line 22) | func addBinary(a string, b string) string {
FILE: solutions/0067_add_binary/add_binary_test.go
function TestAddBinary (line 7) | func TestAddBinary(t *testing.T) {
FILE: solutions/0069_sqrtx/sqrtx.go
function mySqrt (line 19) | func mySqrt(x int) int {
FILE: solutions/0069_sqrtx/sqrtx_test.go
function TestMySqrt (line 5) | func TestMySqrt(t *testing.T) {
FILE: solutions/0070_climbing_stairs/climbing_stairs.go
function climbStairs (line 74) | func climbStairs(n int) int {
FILE: solutions/0070_climbing_stairs/climbing_stairs_test.go
function TestClimbStairs (line 5) | func TestClimbStairs(t *testing.T) {
FILE: solutions/0075_sort_colors/sort_colors.go
function sortColorsCountSort (line 20) | func sortColorsCountSort(nums []int) {
function sortColorsQuickSort3Ways (line 40) | func sortColorsQuickSort3Ways(nums []int) {
FILE: solutions/0075_sort_colors/sort_colors_test.go
function TestSortColorsCountSort (line 8) | func TestSortColorsCountSort(t *testing.T) {
function TestSortColorsQuickSort3Ways (line 18) | func TestSortColorsQuickSort3Ways(t *testing.T) {
FILE: solutions/0076_minimum_window_substring/minimum_window_substring.go
function minWindow (line 32) | func minWindow(s string, t string) string {
FILE: solutions/0076_minimum_window_substring/minimum_window_substring_test.go
function TestMinWindow (line 5) | func TestMinWindow(t *testing.T) {
FILE: solutions/0077_combinations/combinations.go
function combine (line 14) | func combine(n int, k int) [][]int {
function generateCombinations (line 25) | func generateCombinations(n, k, start int, c []int, res *[][]int) {
FILE: solutions/0077_combinations/combinations_test.go
function TestCombine (line 8) | func TestCombine(t *testing.T) {
FILE: solutions/0079_word_search/word_search.go
function exist (line 23) | func exist(board [][]byte, word string) bool {
function searchWord (line 40) | func searchWord(board [][]byte, word string, index, startX, startY int) ...
function inArea (line 59) | func inArea(x, y int) bool {
FILE: solutions/0079_word_search/word_search_test.go
function TestExist (line 5) | func TestExist(t *testing.T) {
FILE: solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go
function removeDuplicates (line 18) | func removeDuplicates(nums []int) int {
function nextDifferentCharacterIndex (line 39) | func nextDifferentCharacterIndex(nums []int, j int, p int) int {
FILE: solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2_test.go
function TestRemoveDuplicates (line 5) | func TestRemoveDuplicates(t *testing.T) {
FILE: solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go
type ListNode (line 13) | type ListNode struct
function deleteDuplicates (line 20) | func deleteDuplicates(head *ListNode) *ListNode {
FILE: solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl_test.go
function TestDeleteDuplicates (line 8) | func TestDeleteDuplicates(t *testing.T) {
function createSingleLinkedList (line 26) | func createSingleLinkedList(nums []int) *ListNode {
FILE: solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go
type ListNode (line 11) | type ListNode struct
function deleteDuplicates (line 18) | func deleteDuplicates(head *ListNode) *ListNode {
FILE: solutions/0083_remove_duplicates_from_sorted_list/rdfsl_test.go
function createSingleLinkedList (line 8) | func createSingleLinkedList(nums []int) *ListNode {
function TestDeleteDuplicates (line 19) | func TestDeleteDuplicates(t *testing.T) {
FILE: solutions/0086_partition_list/partition_list.go
type ListNode (line 15) | type ListNode struct
function partition (line 22) | func partition(head *ListNode, x int) *ListNode {
FILE: solutions/0086_partition_list/partition_list_test.go
function createSingleLinkedList (line 8) | func createSingleLinkedList(nums []int) *ListNode {
function TestDeleteDuplicates (line 19) | func TestDeleteDuplicates(t *testing.T) {
FILE: solutions/0088_merge_sorted_array/msa.go
function merge (line 19) | func merge(nums1 []int, m int, nums2 []int, n int) {
FILE: solutions/0088_merge_sorted_array/msa_test.go
function TestMerge (line 8) | func TestMerge(t *testing.T) {
FILE: solutions/0092_reverse_linked_list_2/reverse_linked_list2.go
type ListNode (line 13) | type ListNode struct
function reverseBetween (line 20) | func reverseBetween(head *ListNode, m, n int) *ListNode {
function reverse (line 41) | func reverse(p, s **ListNode) {
FILE: solutions/0092_reverse_linked_list_2/reverse_linked_list2_test.go
function createSingleList (line 8) | func createSingleList(nums []int) *ListNode {
function TestReverseBetween (line 18) | func TestReverseBetween(t *testing.T) {
FILE: solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go
type TreeNode (line 23) | type TreeNode struct
function inorderTraversal (line 29) | func inorderTraversal(root *TreeNode) []int {
function inorderTraversalHelp (line 35) | func inorderTraversalHelp(root *TreeNode, res *[]int) {
FILE: solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 12) | func performCreate(nums []int, index int) *TreeNode {
function TestInorderTraversal (line 23) | func TestInorderTraversal(t *testing.T) {
FILE: solutions/0100_same_tree/same_tree.go
type TreeNode (line 14) | type TreeNode struct
function isSameTree (line 20) | func isSameTree(p *TreeNode, q *TreeNode) bool {
FILE: solutions/0100_same_tree/same_tree_test.go
type arg (line 5) | type arg struct
function createBinaryTree (line 10) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 14) | func performCreate(nums []int, index int) *TreeNode {
function TestSameTree (line 25) | func TestSameTree(t *testing.T) {
FILE: solutions/0101_symmetric_tree/symmetric_tree.go
type TreeNode (line 11) | type TreeNode struct
function isSymmetric (line 17) | func isSymmetric(root *TreeNode) bool {
function symmetric (line 24) | func symmetric(left *TreeNode, right *TreeNode) bool {
FILE: solutions/0101_symmetric_tree/symmetric_tree_test.go
function createBinaryTree (line 7) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 11) | func performCreate(nums []int, index int) *TreeNode {
function TestIsSymmetric (line 22) | func TestIsSymmetric(t *testing.T) {
FILE: solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go
type TreeNode (line 12) | type TreeNode struct
type queueEle (line 18) | type queueEle struct
function levelOrder (line 26) | func levelOrder(root *TreeNode) [][]int {
FILE: solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal_test.go
function TestLevelOrder (line 8) | func TestLevelOrder(t *testing.T) {
function createBinaryTree (line 25) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 29) | func performCreate(nums []int, index int) *TreeNode {
FILE: solutions/0104_maximun_depth_of_binary_tree/maxdobt.go
type TreeNode (line 17) | type TreeNode struct
function maxDepth (line 26) | func maxDepth(root *TreeNode) int {
FILE: solutions/0104_maximun_depth_of_binary_tree/maxdobt_test.go
function TestMaxDepth (line 5) | func TestMaxDepth(t *testing.T) {
function createBinaryTree (line 15) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 19) | func performCreate(nums []int, index int) *TreeNode {
FILE: solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go
type TreeNode (line 11) | type TreeNode struct
function levelOrderBottom (line 17) | func levelOrderBottom(root *TreeNode) [][]int {
function traversal (line 27) | func traversal(root *TreeNode, index int, record *[][]int) {
FILE: solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 12) | func performCreate(nums []int, index int) *TreeNode {
function TestBinaryTreeLevelOrderTraversal2 (line 23) | func TestBinaryTreeLevelOrderTraversal2(t *testing.T) {
FILE: solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go
type TreeNode (line 18) | type TreeNode struct
function minDepth (line 24) | func minDepth(root *TreeNode) int {
FILE: solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree_test.go
function createBinaryTree (line 5) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 9) | func performCreate(nums []int, index int) *TreeNode {
function TestMinDepth (line 19) | func TestMinDepth(t *testing.T) {
FILE: solutions/0112_path_sum/path_sum.go
type TreeNode (line 13) | type TreeNode struct
function hasPathSum (line 19) | func hasPathSum(root *TreeNode, sum int) bool {
FILE: solutions/0112_path_sum/path_sum_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []interface{}) *TreeNode {
function performCreate (line 12) | func performCreate(nums []interface{}, index int) *TreeNode {
type arg (line 26) | type arg struct
function TestHasPathSum (line 31) | func TestHasPathSum(t *testing.T) {
function TestMain (line 44) | func TestMain(m *testing.M) {
FILE: solutions/0120_triangle/triangle.go
function minimumTotal (line 39) | func minimumTotal(triangle [][]int) int {
FILE: solutions/0120_triangle/triangle_test.go
function TestTriangle (line 7) | func TestTriangle(t *testing.T) {
FILE: solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go
function maxProfit (line 20) | func maxProfit(prices []int) int {
function maxProfit1 (line 45) | func maxProfit1(prices []int) int {
FILE: solutions/0121_best_time_to_buy_and_sell_stock/maxprofit_test.go
function TestMaxProfit (line 5) | func TestMaxProfit(t *testing.T) {
function TestMaxProfit1 (line 24) | func TestMaxProfit1(t *testing.T) {
FILE: solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go
function maxProfit (line 21) | func maxProfit(prices []int) int {
FILE: solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit_test.go
function TestMaxProfit (line 5) | func TestMaxProfit(t *testing.T) {
FILE: solutions/0125_valid_palindrome/valid_palindrome.go
function isPalindrome (line 17) | func isPalindrome(s string) bool {
FILE: solutions/0125_valid_palindrome/valid_palindrome_test.go
function TestIsPalindrome (line 5) | func TestIsPalindrome(t *testing.T) {
FILE: solutions/0136_single_number/single_number.go
function singleNumber (line 13) | func singleNumber(nums []int) int {
function singleNumber1 (line 31) | func singleNumber1(nums []int) int {
FILE: solutions/0136_single_number/single_number_test.go
function TestSingleNumber (line 5) | func TestSingleNumber(t *testing.T) {
FILE: solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go
type TreeNode (line 12) | type TreeNode struct
function preorderTraversal (line 21) | func preorderTraversal(root *TreeNode) []int {
function preorderTraversal1 (line 42) | func preorderTraversal1(root *TreeNode) []int {
FILE: solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 12) | func performCreate(nums []int, index int) *TreeNode {
function TestPreorderTraversal (line 23) | func TestPreorderTraversal(t *testing.T) {
FILE: solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go
function evalRPN (line 24) | func evalRPN(tokens []string) int {
FILE: solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation_test.go
function TestEvalRPN (line 5) | func TestEvalRPN(t *testing.T) {
FILE: solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go
function findMin (line 20) | func findMin(nums []int) int {
FILE: solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa_test.go
function TestFindMin (line 5) | func TestFindMin(t *testing.T) {
FILE: solutions/0155_min_stack/min_stack.go
type MinStack (line 17) | type MinStack struct
method Push (line 27) | func (s *MinStack) Push(x int) {
method Pop (line 32) | func (s *MinStack) Pop() {
method Top (line 39) | func (s *MinStack) Top() int {
method GetMin (line 49) | func (s *MinStack) GetMin() int {
method GetSize (line 66) | func (s MinStack) GetSize() int {
method IsEmpty (line 70) | func (s MinStack) IsEmpty() bool {
function Constructor (line 22) | func Constructor() MinStack {
FILE: solutions/0155_min_stack/min_stack_test.go
function TestMinStack (line 5) | func TestMinStack(t *testing.T) {
FILE: solutions/0165_compare_version_numbers/compare_version_numbers.go
function compareVersion (line 35) | func compareVersion(version1 string, version2 string) int {
FILE: solutions/0165_compare_version_numbers/compare_version_numbers_test.go
function TestCompareVersion (line 5) | func TestCompareVersion(t *testing.T) {
FILE: solutions/0167_two_sum2/two_sum2.go
function twoSum2 (line 22) | func twoSum2(numbers []int, target int) []int {
FILE: solutions/0167_two_sum2/two_sum2_test.go
type arg (line 8) | type arg struct
function TestTwoSum2 (line 13) | func TestTwoSum2(t *testing.T) {
FILE: solutions/0179_largest_number/ln.go
type sliceString (line 18) | type sliceString
method Len (line 21) | func (s sliceString) Len() int { return len(s) }
method Swap (line 24) | func (s sliceString) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
method Less (line 28) | func (s sliceString) Less(i, j int) bool { return (s[i] + s[j]) > (s[j...
function largestNumber (line 32) | func largestNumber(nums []int) string {
FILE: solutions/0179_largest_number/ln_test.go
function TestLargestNumber (line 5) | func TestLargestNumber(t *testing.T) {
FILE: solutions/0198_house_robber/house_robber.go
function rob (line 77) | func rob(nums []int) int {
FILE: solutions/0198_house_robber/house_robber_test.go
function TestHouseRobber (line 5) | func TestHouseRobber(t *testing.T) {
FILE: solutions/0200_number_of_island/number_of_island.go
function numIslands (line 22) | func numIslands(grid [][]byte) int {
function dfs (line 48) | func dfs(grid [][]byte, x, y int) {
function inArea (line 59) | func inArea(x, y int) bool {
FILE: solutions/0200_number_of_island/number_of_island_test.go
function TestNumIslands (line 5) | func TestNumIslands(t *testing.T) {
FILE: solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go
type ListNode (line 12) | type ListNode struct
function removeElements (line 19) | func removeElements(head *ListNode, val int) *ListNode {
function removeElements1 (line 38) | func removeElements1(head *ListNode, val int) *ListNode {
FILE: solutions/0203_remove_linked_list_elements/remove_linked_list_elements_test.go
function TestRemoveElements (line 8) | func TestRemoveElements(t *testing.T) {
function TestRemoveElements1 (line 18) | func TestRemoveElements1(t *testing.T) {
function createSinglyLinkedList (line 28) | func createSinglyLinkedList(nums []int) *ListNode {
FILE: solutions/0206_reverse_linked_list/reverse_linked_list.go
type ListNode (line 12) | type ListNode struct
function reverseList (line 20) | func reverseList(head *ListNode) *ListNode {
function reverseList1 (line 34) | func reverseList1(head *ListNode) *ListNode {
FILE: solutions/0206_reverse_linked_list/reverse_linked_list_test.go
function TestReverseList (line 8) | func TestReverseList(t *testing.T) {
function TestReverseList1 (line 16) | func TestReverseList1(t *testing.T) {
function createSinglyLinkedList (line 24) | func createSinglyLinkedList(nums []int) *ListNode {
FILE: solutions/0208_implement_trie_prefix_tree/impltrie.go
type node (line 15) | type node struct
type Trie (line 21) | type Trie struct
method Insert (line 32) | func (trie *Trie) Insert(word string) {
method Search (line 48) | func (trie *Trie) Search(word string) bool {
method StartsWith (line 61) | func (trie *Trie) StartsWith(prefix string) bool {
function Constructor (line 27) | func Constructor() Trie {
FILE: solutions/0208_implement_trie_prefix_tree/impltrie_test.go
function TestImplTrie (line 5) | func TestImplTrie(t *testing.T) {
FILE: solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go
function minSubArrayLen (line 19) | func minSubArrayLen(s int, nums []int) int {
FILE: solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum_test.go
function TestMinSubArrayLen (line 5) | func TestMinSubArrayLen(t *testing.T) {
FILE: solutions/0211_add_and_search_word/add_and_search_word.go
type node (line 9) | type node struct
type WordDictionary (line 15) | type WordDictionary struct
method AddWord (line 25) | func (trie *WordDictionary) AddWord(word string) {
method Search (line 40) | func (trie *WordDictionary) Search(word string) bool {
function Constructor (line 20) | func Constructor() WordDictionary {
function match (line 44) | func match(n *node, word string, index int) bool {
FILE: solutions/0211_add_and_search_word/add_and_search_word_test.go
function TestAddAndSearchWord (line 5) | func TestAddAndSearchWord(t *testing.T) {
FILE: solutions/0215_kth_largest_element_in_an_array/kthleiaa.go
function findKthLargest (line 19) | func findKthLargest(nums []int, k int) int {
function siftDown (line 32) | func siftDown(nums []int, n int, i int) {
FILE: solutions/0215_kth_largest_element_in_an_array/kthleiaa_test.go
function TestFindKthLargest (line 5) | func TestFindKthLargest(t *testing.T) {
FILE: solutions/0217_contains_duplicate/contains_duplicate.go
function containsDuplicate (line 17) | func containsDuplicate(nums []int) bool {
FILE: solutions/0217_contains_duplicate/contains_duplicate_test.go
function TestContainsDuplicate (line 5) | func TestContainsDuplicate(t *testing.T) {
FILE: solutions/0219_contains_duplicate_2/contains_duplicate_2.go
function containsNearbyDuplicate (line 16) | func containsNearbyDuplicate(nums []int, k int) bool {
FILE: solutions/0219_contains_duplicate_2/contains_duplicate_2_test.go
function TestContainsNearbyDuplicate (line 5) | func TestContainsNearbyDuplicate(t *testing.T) {
FILE: solutions/0226_invert_binary_tree/invert_binary_tree.go
type TreeNode (line 11) | type TreeNode struct
function invertTree (line 20) | func invertTree(root *TreeNode) *TreeNode {
FILE: solutions/0226_invert_binary_tree/invert_binary_tree_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []interface{}) *TreeNode {
function performCreate (line 12) | func performCreate(nums []interface{}, index int) *TreeNode {
function levelOrderTraversal (line 26) | func levelOrderTraversal(root *TreeNode) []interface{} {
function TestInvertTree (line 44) | func TestInvertTree(t *testing.T) {
FILE: solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go
type TreeNode (line 20) | type TreeNode struct
function lowestCommonAncestor (line 29) | func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
FILE: solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst_test.go
function TestLowestCommonAncestor (line 7) | func TestLowestCommonAncestor(t *testing.T) {
function createBinaryTree (line 27) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 31) | func performCreate(nums []int, index int) *TreeNode {
FILE: solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go
type TreeNode (line 10) | type TreeNode struct
function lowestCommonAncestor (line 16) | func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
FILE: solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca_test.go
function TestLCA (line 5) | func TestLCA(t *testing.T) {
function createBinaryTree (line 27) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 31) | func performCreate(nums []int, index int) *TreeNode {
FILE: solutions/0237_delete_node_in_a_linked_list/dniall.go
type ListNode (line 18) | type ListNode struct
function deleteNode (line 25) | func deleteNode(node *ListNode) {
FILE: solutions/0237_delete_node_in_a_linked_list/dniall_test.go
function createSinglyLinkedList (line 8) | func createSinglyLinkedList(nums []int) *ListNode {
function TestDeleteNode (line 19) | func TestDeleteNode(t *testing.T) {
FILE: solutions/0257_binary_tree_paths/binary_tree_paths.go
type TreeNode (line 16) | type TreeNode struct
function binaryTreePaths (line 25) | func binaryTreePaths(root *TreeNode) []string {
FILE: solutions/0257_binary_tree_paths/binary_tree_paths_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 12) | func performCreate(nums []int, index int) *TreeNode {
function TestBinaryTreePaths (line 23) | func TestBinaryTreePaths(t *testing.T) {
FILE: solutions/0258_add_digits/add_digits.go
function addDigits (line 13) | func addDigits(num int) int {
function performAdd (line 21) | func performAdd(num int) (res int) {
function addDigits1 (line 31) | func addDigits1(num int) int {
FILE: solutions/0258_add_digits/add_digits_test.go
function TestAddDigits (line 5) | func TestAddDigits(t *testing.T) {
FILE: solutions/0283_move_zeroes/move_zeroes.go
function moveZeroes (line 12) | func moveZeroes(nums []int) {
FILE: solutions/0283_move_zeroes/move_zeroes2.go
function moveZeroes2 (line 12) | func moveZeroes2(nums []int) {
FILE: solutions/0283_move_zeroes/move_zeroes2_test.go
function TestMoveZeroes2 (line 8) | func TestMoveZeroes2(t *testing.T) {
FILE: solutions/0283_move_zeroes/move_zeroes_test.go
function TestMoveZeroes (line 8) | func TestMoveZeroes(t *testing.T) {
FILE: solutions/0300_longest_increasing_subsequence/lis.go
function lengthOfLIS (line 28) | func lengthOfLIS(nums []int) int {
FILE: solutions/0300_longest_increasing_subsequence/lis_test.go
function TestLIS (line 8) | func TestLIS(t *testing.T) {
function TestMain (line 22) | func TestMain(m *testing.M) {
FILE: solutions/0303_range_sum_query/rsqim.go
type NumArray (line 13) | type NumArray struct
method SumRange (line 27) | func (na *NumArray) SumRange(i int, j int) int {
function Constructor (line 18) | func Constructor(nums []int) NumArray {
FILE: solutions/0303_range_sum_query/rsqim_test.go
function TestSumRange (line 5) | func TestSumRange(t *testing.T) {
FILE: solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut.go
type NumArray (line 19) | type NumArray struct
method buildSegmentTree (line 31) | func (na *NumArray) buildSegmentTree(treeIndex, left, right int) {
method Update (line 49) | func (na *NumArray) Update(i int, val int) {
method setter (line 53) | func (na *NumArray) setter(treeIndex, left, right, index, val int) {
method SumRange (line 70) | func (na *NumArray) SumRange(i int, j int) int {
method query (line 74) | func (na *NumArray) query(treeIndex, left, right, queryL, queryR int) ...
function Constructor (line 25) | func Constructor(nums []int) NumArray {
FILE: solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut_test.go
function TestNumArray (line 5) | func TestNumArray(t *testing.T) {
FILE: solutions/0328_odd_even_linked_list/odd_even_linked_list.go
type ListNode (line 20) | type ListNode struct
function oddEvenList (line 27) | func oddEvenList(head *ListNode) *ListNode {
FILE: solutions/0328_odd_even_linked_list/odd_even_linked_list_test.go
function createSinglyLinkedList (line 8) | func createSinglyLinkedList(nums []int) *ListNode {
function TestOddEvenList (line 19) | func TestOddEvenList(t *testing.T) {
FILE: solutions/0343_integer_break/integer_break.go
function integerBreak (line 72) | func integerBreak(n int) int {
FILE: solutions/0343_integer_break/integer_break_test.go
function TestIntegerBreak (line 5) | func TestIntegerBreak(t *testing.T) {
FILE: solutions/0344_reverse_string/reverse_string.go
function reverseString (line 14) | func reverseString(s string) string {
function reverseString1 (line 34) | func reverseString1(s string) string {
FILE: solutions/0344_reverse_string/reverse_string_test.go
function TestReverseString (line 5) | func TestReverseString(t *testing.T) {
function TestReverseString1 (line 26) | func TestReverseString1(t *testing.T) {
FILE: solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go
function reverseVowels (line 14) | func reverseVowels(s string) string {
function reverseVowels1 (line 44) | func reverseVowels1(s string) string {
function isVowel (line 68) | func isVowel(char byte) bool {
FILE: solutions/0345_reverse_vowels_of_a_string/reverse_vowels_test.go
function TestReverseVowels (line 5) | func TestReverseVowels(t *testing.T) {
function TestReverseVowels1 (line 27) | func TestReverseVowels1(t *testing.T) {
FILE: solutions/0347_top_k_frequent_elements/topkfe.go
function topKFrequent (line 20) | func topKFrequent(nums []int, k int) []int {
type Num (line 45) | type Num struct
type Nums (line 51) | type Nums
method Len (line 54) | func (n Nums) Len() int { return len(n) }
method Swap (line 57) | func (n Nums) Swap(i, j int) { n[i], n[j] = n[j], n[i] }
method Less (line 60) | func (n Nums) Less(i, j int) bool { return n[i].Count >= n[j].Count }
method Push (line 63) | func (n *Nums) Push(num interface{}) {
method Pop (line 69) | func (n *Nums) Pop() interface{} {
FILE: solutions/0347_top_k_frequent_elements/topkfe_test.go
function TestTopKFrequent (line 8) | func TestTopKFrequent(t *testing.T) {
FILE: solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays.go
function intersection (line 25) | func intersection(nums1 []int, nums2 []int) []int {
FILE: solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays_test.go
function TestIntersection (line 8) | func TestIntersection(t *testing.T) {
FILE: solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go
function intersect (line 9) | func intersect(nums1 []int, nums2 []int) []int {
FILE: solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2_test.go
function TestInteract (line 8) | func TestInteract(t *testing.T) {
FILE: solutions/0376_wiggle_subsequence/wiggle_subsequence.go
function wiggleMaxLength (line 46) | func wiggleMaxLength(nums []int) int {
FILE: solutions/0376_wiggle_subsequence/wiggle_subsequence_test.go
function TestWiggleSubsequence (line 5) | func TestWiggleSubsequence(t *testing.T) {
FILE: solutions/0392_is_subsequence/is_subsequence.go
function isSubsequence (line 33) | func isSubsequence(s string, t string) bool {
FILE: solutions/0392_is_subsequence/is_subsequence_test.go
type args (line 5) | type args struct
function TestAssignCookies (line 10) | func TestAssignCookies(t *testing.T) {
FILE: solutions/0404_sum_of_left_leaves/sum_of_left_leaves.go
type TreeNode (line 12) | type TreeNode struct
function sumOfLeftLeaves (line 20) | func sumOfLeftLeaves(root *TreeNode) int {
function performSum (line 24) | func performSum(root *TreeNode, isLeft bool) int {
FILE: solutions/0404_sum_of_left_leaves/sum_of_left_leaves_test.go
function createBinaryTree (line 5) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 9) | func performCreate(nums []int, index int) *TreeNode {
function TestSumOfLeftLeaves (line 20) | func TestSumOfLeftLeaves(t *testing.T) {
FILE: solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum.go
function canPartition (line 23) | func canPartition(nums []int) bool {
FILE: solutions/0416_partition_equal_subset_sum/partition_equal_subset_sum_test.go
function TestPartitionEqualSubsetSum (line 5) | func TestPartitionEqualSubsetSum(t *testing.T) {
FILE: solutions/0435_non_overlapping_intervals/dp_solution.go
function eraseOverlapIntervalsDp (line 19) | func eraseOverlapIntervalsDp(intervals []Interval) int {
FILE: solutions/0435_non_overlapping_intervals/greedy_solution.go
function eraseOverlapIntervalsGreedy (line 16) | func eraseOverlapIntervalsGreedy(intervals []Interval) int {
FILE: solutions/0435_non_overlapping_intervals/interval.go
type Interval (line 4) | type Interval struct
type IntervalSliceCompareWithStart (line 10) | type IntervalSliceCompareWithStart
method Len (line 13) | func (i IntervalSliceCompareWithStart) Len() int { return len(i) }
method Less (line 16) | func (i IntervalSliceCompareWithStart) Less(j, k int) bool {
method Swap (line 23) | func (i IntervalSliceCompareWithStart) Swap(j, k int) { i[j], i[k] = i...
type IntervalSliceCompareWithEnd (line 26) | type IntervalSliceCompareWithEnd
method Len (line 29) | func (i IntervalSliceCompareWithEnd) Len() int { return len(i) }
method Less (line 32) | func (i IntervalSliceCompareWithEnd) Less(j, k int) bool {
method Swap (line 39) | func (i IntervalSliceCompareWithEnd) Swap(j, k int) { i[j], i[k] = i[k...
FILE: solutions/0435_non_overlapping_intervals/solution_test.go
function TestEraseOverlapIntervals (line 5) | func TestEraseOverlapIntervals(t *testing.T) {
FILE: solutions/0437_path_sum_3/path_sum_3.go
type TreeNode (line 19) | type TreeNode struct
function pathSum (line 28) | func pathSum(root *TreeNode, sum int) int {
function findPath (line 35) | func findPath(node *TreeNode, val int) int {
FILE: solutions/0437_path_sum_3/path_sum_3_test.go
function createBinaryTree (line 5) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 9) | func performCreate(nums []int, index int) *TreeNode {
function TestPathSum (line 20) | func TestPathSum(t *testing.T) {
FILE: solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string.go
function findAnagrams (line 44) | func findAnagrams(s string, p string) []int {
function isSame (line 77) | func isSame(p []int, q []int) bool {
FILE: solutions/0438_all_anagrams_in_a_string/all_anagrams_in_a_string_test.go
function TestFindAnagrams (line 8) | func TestFindAnagrams(t *testing.T) {
FILE: solutions/0447_number_of_boomerangs/number_of_boomerangs.go
function numberOfBoomerangs (line 18) | func numberOfBoomerangs(points [][]int) int {
function dis (line 40) | func dis(point1 []int, point2 []int) int {
FILE: solutions/0447_number_of_boomerangs/number_of_boomerangs_test.go
function TestNumberOfBoomerangs (line 5) | func TestNumberOfBoomerangs(t *testing.T) {
FILE: solutions/0454_4sum2/4sum2.go
function fourSumCount (line 14) | func fourSumCount(A []int, B []int, C []int, D []int) int {
FILE: solutions/0454_4sum2/4sum2_test.go
function TestFourSumCount (line 5) | func TestFourSumCount(t *testing.T) {
FILE: solutions/0455_assign_cookies/assign_cookies.go
function findContentChildren (line 23) | func findContentChildren(g []int, s []int) int {
FILE: solutions/0455_assign_cookies/assign_cookies_test.go
type args (line 5) | type args struct
function TestAssignCookies (line 10) | func TestAssignCookies(t *testing.T) {
FILE: solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3.go
function reverseWords (line 19) | func reverseWords(s string) string {
function reverseString (line 29) | func reverseString(s string) string {
FILE: solutions/0557_reverse_words_in_a_string_3/reverse_words_in_a_string_3_test.go
function TestReverseWords (line 5) | func TestReverseWords(t *testing.T) {
FILE: solutions/0674_longest_continuous_increasing_subsequence/lcis.go
function findLengthOfLCIS (line 14) | func findLengthOfLCIS(nums []int) int {
function findLengthOfLCIS1 (line 36) | func findLengthOfLCIS1(nums []int) int {
FILE: solutions/0674_longest_continuous_increasing_subsequence/lcis_test.go
function TestFindLengthOfLCIS (line 5) | func TestFindLengthOfLCIS(t *testing.T) {
FILE: solutions/0677_map_sum_pairs/map_sum_pairs.go
type node (line 18) | type node struct
type MapSum (line 24) | type MapSum struct
method Insert (line 34) | func (ms *MapSum) Insert(key string, val int) {
method Sum (line 46) | func (ms *MapSum) Sum(prefix string) int {
function Constructor (line 29) | func Constructor() MapSum {
function sum (line 57) | func sum(n *node) int {
FILE: solutions/0677_map_sum_pairs/map_sum_pairs_test.go
function TestMapSumPairs (line 5) | func TestMapSumPairs(t *testing.T) {
FILE: solutions/0704_binary_search/binary_search.go
function search (line 21) | func search(nums []int, target int) int {
FILE: solutions/0704_binary_search/binary_search_test.go
function TestSearch (line 5) | func TestSearch(t *testing.T) {
FILE: solutions/0713_subarray_product_less_than_k/spltk.go
function numSubArrayProductLessThanK (line 18) | func numSubArrayProductLessThanK(nums []int, k int) int {
function numSubArrayProductLessThanK2 (line 47) | func numSubArrayProductLessThanK2(nums []int, k int) int {
FILE: solutions/0713_subarray_product_less_than_k/spltk_test.go
function TestNumSubArrayProductLessThanK (line 5) | func TestNumSubArrayProductLessThanK(t *testing.T) {
FILE: solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc.go
function isOneBitCharacter (line 23) | func isOneBitCharacter(bits []int) bool {
FILE: solutions/0717_1_bit_and_2_bit_characters/1bitand2bitc_test.go
function TestIsOneBitCharacter (line 5) | func TestIsOneBitCharacter(t *testing.T) {
FILE: solutions/0728_self_dividing_numbers/self_dividing_numbers.go
function selfDividingNumbers (line 31) | func selfDividingNumbers(left int, right int) []int {
FILE: solutions/0728_self_dividing_numbers/self_dividing_numbers_test.go
function TestSelfDividingNumbers (line 8) | func TestSelfDividingNumbers(t *testing.T) {
FILE: solutions/0735_asteroid_collision/ac.go
function asteroidCollision (line 26) | func asteroidCollision(asteroids []int) []int {
FILE: solutions/0735_asteroid_collision/ac_test.go
function TestAsteroidCollision (line 8) | func TestAsteroidCollision(t *testing.T) {
FILE: solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others.go
function dominantIndex (line 41) | func dominantIndex(nums []int) int {
FILE: solutions/0747_largest_number_at_least_twice_of_others/largest_number_at_least_twice_of_others_test.go
function TestDominantIndex (line 5) | func TestDominantIndex(t *testing.T) {
FILE: solutions/0872_leaf_similar_trees/leaf_similar_trees.go
type TreeNode (line 14) | type TreeNode struct
function leafSimilar (line 22) | func leafSimilar(root1 *TreeNode, root2 *TreeNode) bool {
function dfs (line 32) | func dfs(root *TreeNode, l *[]int) {
FILE: solutions/0872_leaf_similar_trees/leaf_similar_trees_test.go
function createBinaryTree (line 8) | func createBinaryTree(nums []int) *TreeNode {
function performCreate (line 12) | func performCreate(nums []int, index int) *TreeNode {
function TestLeafSimilar (line 23) | func TestLeafSimilar(t *testing.T) {
FILE: solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses.go
function removeOuterParentheses (line 53) | func removeOuterParentheses(S string) string {
FILE: solutions/1021_Remove_Outermost_Parentheses/remove_outmost_parentheses_test.go
function TestRemoveOuterParentheses (line 7) | func TestRemoveOuterParentheses(t *testing.T) {
FILE: solutions/148_Sort_List/sortlist.go
type ListNode (line 10) | type ListNode struct
function sortList (line 18) | func sortList(head *ListNode) *ListNode {
function merge (line 33) | func merge(headA, headB *ListNode) *ListNode {
FILE: solutions/148_Sort_List/sortlist_test.go
function TestSortList (line 8) | func TestSortList(t *testing.T) {
function createSingleLinkedList (line 16) | func createSingleLinkedList(nums []int) *ListNode {
FILE: solutions/304_Range_Sum_Query_2D/rsq.go
type NumMatrix (line 10) | type NumMatrix struct
method SumRegion (line 33) | func (nm *NumMatrix) SumRegion(row1 int, col1 int, row2 int, col2 int)...
function Constructor (line 15) | func Constructor(matrix [][]int) NumMatrix {
FILE: solutions/304_Range_Sum_Query_2D/rsq_test.go
function TestSunRegion (line 5) | func TestSunRegion(t *testing.T) {
FILE: utils/infinite.go
constant MaxUint (line 5) | MaxUint = ^uint(0)
constant MaxInt (line 7) | MaxInt = int(MaxUint >> 1)
constant MinUint (line 10) | MinUint = 0
constant MinInt (line 13) | MinInt = -MaxInt - 1
FILE: utils/maxint.go
function CalcMaxInt (line 4) | func CalcMaxInt(nums ...int) (res int) {
FILE: utils/maxint_test.go
function TestCalcMaxInt (line 5) | func TestCalcMaxInt(t *testing.T) {
function BenchmarkCalcMaxInt (line 19) | func BenchmarkCalcMaxInt(b *testing.B) {
FILE: utils/minint.go
function CalcMinInt (line 4) | func CalcMinInt(nums ...int) (res int) {
FILE: utils/minint_test.go
function TestCalcMinInt (line 5) | func TestCalcMinInt(t *testing.T) {
FILE: utils/set.go
type Set (line 7) | type Set
method Add (line 17) | func (s Set) Add(items ...interface{}) error {
method Contains (line 25) | func (s Set) Contains(item interface{}) bool {
method Size (line 31) | func (s Set) Size() int {
method Clear (line 36) | func (s *Set) Clear() {
method Equal (line 41) | func (s Set) Equal(other Set) bool {
method IsSubset (line 54) | func (s Set) IsSubset(other Set) bool {
function NewSet (line 10) | func NewSet(items ...interface{}) Set {
FILE: utils/set_test.go
function TestEmptyStruct (line 8) | func TestEmptyStruct(t *testing.T) {
function TestContains (line 14) | func TestContains(t *testing.T) {
function TestSize (line 26) | func TestSize(t *testing.T) {
function TestEqual (line 34) | func TestEqual(t *testing.T) {
function TestIsSubset (line 48) | func TestIsSubset(t *testing.T) {
function TestClear (line 63) | func TestClear(t *testing.T) {
Condensed preview — 252 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (279K chars).
[
{
"path": ".codacy.yml",
"chars": 49,
"preview": "---\nexclude_paths:\n - '**/*.md'\n - 'README.md'\n"
},
{
"path": ".codecov.yml",
"chars": 463,
"preview": "codecov:\n notify:\n require_ci_to_pass: yes\n\ncoverage:\n round: up\n range: 0..10\n precision: 2\n\n status:\n proje"
},
{
"path": ".gitignore",
"chars": 250,
"preview": "# Binaries for programs and plugins\n*.exe\n*.exe~\n*.dll\n*.so\n*.dylib\n\n# Test binary, build with `go test -c`\n*.test\n\n# Ou"
},
{
"path": ".travis.yml",
"chars": 262,
"preview": "language: go\n\ngo:\n - \"1.12.x\"\n\ngo_import_path: leetcode\n\ninstall:\n - go get -t -v ./...\n\nscript:\n - go test ./... -ra"
},
{
"path": "LICENSE",
"chars": 1210,
"preview": "This is free and unencumbered software released into the public domain.\n\nAnyone is free to copy, modify, publish, use, c"
},
{
"path": "Makefile",
"chars": 274,
"preview": "# Basic go commands\nGOCMD=go\nGOBUILD=$(GOCMD) build\nGOCLEAN=$(GOCMD) clean\nGOTEST=$(GOCMD) test\nGOGET=$(GOCMD) get\nGOFMT"
},
{
"path": "_config.yml",
"chars": 29,
"preview": "theme: jekyll-theme-architect"
},
{
"path": "bak.README.md",
"chars": 14659,
"preview": "# Go Solution for Leetcode algorithm problems\n\n["
},
{
"path": "docs/_config.yml",
"chars": 26,
"preview": "theme: jekyll-theme-hacker"
},
{
"path": "docs/index.md",
"chars": 1295,
"preview": "## Welcome to GitHub Pages\n\nYou can use the [editor on GitHub](https://github.com/keep-in-practice/leetcode-go/edit/mast"
},
{
"path": "go.mod",
"chars": 25,
"preview": "module leetcode\n\ngo 1.13\n"
},
{
"path": "solutions/0001_two_sum/twosum.go",
"chars": 950,
"preview": "/*\n1. Two Sum\n\nSource: https://leetcode.com/problems/two-sum/\n\nGiven an array of integers, return indices of the two num"
},
{
"path": "solutions/0001_two_sum/twosum_test.go",
"chars": 409,
"preview": "package twosum\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestTwoSum(t *testing.T) {\n\tnums := []int{2, 7, 11, 15}\n\n\tfuncs :"
},
{
"path": "solutions/0002_add_two_numbers/add_two_numbers.go",
"chars": 1937,
"preview": "/*\n2. Add Two Numbers\n\nSource: https://leetcode.com/problems/add-two-numbers/\n\nYou are given two non-empty linked lists "
},
{
"path": "solutions/0002_add_two_numbers/add_two_numbers_test.go",
"chars": 3344,
"preview": "package addtwonumbers\n\nimport (\n\t\"os\"\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleLinkedList(arr []int) *ListNode {\n\thead "
},
{
"path": "solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters.go",
"chars": 1098,
"preview": "/*\n3. Longest Substring Without Repeating Characters\n\nSource: https://leetcode.com/problems/longest-substring-without-re"
},
{
"path": "solutions/0003_longest_substring_without_repeating_characters/longest_substring_without_repeating_characters_test.go",
"chars": 396,
"preview": "package longestsubstringwithoutrepeatingcharacters\n\nimport \"testing\"\n\nfunc TestLengthOfLongestSubstring(t *testing.T) {\n"
},
{
"path": "solutions/0004_median_of_two_sorted_arrays/motsa.go",
"chars": 2033,
"preview": "/*\n4. Median of Two Sorted Arrays\nhttps://leetcode.com/problems/median-of-two-sorted-arrays/\n\nThere are two sorted array"
},
{
"path": "solutions/0004_median_of_two_sorted_arrays/motsa_test.go",
"chars": 957,
"preview": "package motsa\n\nimport (\n\t\"testing\"\n)\n\nfunc TestFindMedianSortedArrays(t *testing.T) {\n\ttype arg struct {\n\t\tnums1 []int\n\t"
},
{
"path": "solutions/0007_reverse_integer/reverse_integer.go",
"chars": 530,
"preview": "/*\n7. Reverse Integer\nhttps://leetcode.com/problems/reverse-integer/\nGiven a 32-bit signed integer, reverse digits of an"
},
{
"path": "solutions/0007_reverse_integer/reverse_integer_test.go",
"chars": 331,
"preview": "package reverseinteger\n\nimport \"testing\"\n\nfunc TestReverse(t *testing.T) {\n\ttestCases := []int{\n\t\t123, -123, 10, 0, 1223"
},
{
"path": "solutions/0009_palindrome_number/palindrome_number.go",
"chars": 422,
"preview": "/*\n9. Palindrome Number\nhttps://leetcode.com/problems/palindrome-number/\n\nDetermine whether an integer is a palindrome.\n"
},
{
"path": "solutions/0009_palindrome_number/palindrome_number_test.go",
"chars": 327,
"preview": "package palindromenumber\n\nimport \"testing\"\n\nfunc TestIsPalindrome(t *testing.T) {\n\ttestCases := []int{121, -121, 10, 0}\n"
},
{
"path": "solutions/0011_container_with_most_water/container_with_most_water.go",
"chars": 1587,
"preview": "/*\n11. Container With Most Water\nhttps://leetcode.com/problems/container-with-most-water/\n\nGiven n non-negative integers"
},
{
"path": "solutions/0011_container_with_most_water/container_with_most_water_test.go",
"chars": 1064,
"preview": "package containerwithmostwater\n\nimport \"testing\"\n\nfunc TestMaxArea(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{1, 8, 6, 2,"
},
{
"path": "solutions/0013_roman_to_integer/roman_to_integer.go",
"chars": 501,
"preview": "/*\n13. Roman to Integer\nhttps://leetcode.com/problems/roman-to-integer/\n*/\n// time: 2018-12-31\n\npackage rti\n\n// time com"
},
{
"path": "solutions/0013_roman_to_integer/roman_to_integer_test.go",
"chars": 344,
"preview": "package rti\n\nimport \"testing\"\n\nfunc TestRomanToInt(t *testing.T) {\n\ttestCases := []string{\n\t\t\"III\",\n\t\t\"IV\",\n\t\t\"IX\",\n\t\t\"L"
},
{
"path": "solutions/0014_longest_common_prefix/lcp.go",
"chars": 635,
"preview": "/*\n14. Longest Common Prefix\nhttps://leetcode.com/problems/longest-common-prefix/\n\nWrite a function to find the longest "
},
{
"path": "solutions/0014_longest_common_prefix/lcp_test.go",
"chars": 402,
"preview": "package lcp\n\nimport \"testing\"\n\nfunc TestLongestCommonPrefix(t *testing.T) {\n\ttestCases := [][]string{\n\t\t{\"flower\", \"flow"
},
{
"path": "solutions/0015_3Sum/3sum.go",
"chars": 712,
"preview": "/*\n15. 3Sum\nhttps://leetcode.com/problems/3sum/\n*/\n// time: 2019-03-01\n\npackage threesum\n\nimport \"sort\"\n\n// time complex"
},
{
"path": "solutions/0015_3Sum/3sum_test.go",
"chars": 403,
"preview": "package threesum\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestThreeSum(t *testing.T) {\n\ttestData := [][]int{\n\t\t{-1, 0, 1,"
},
{
"path": "solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number.go",
"chars": 1220,
"preview": "/*\n17. Letter Combinations of a Phone Number\n\nSource: https://leetcode.com/problems/letter-combinations-of-a-phone-numbe"
},
{
"path": "solutions/0017_letter_combination_of_a_phone_number/letter_combination_of_phone_number_test.go",
"chars": 454,
"preview": "package lettercombinationsofaphonenumber\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestLetterCombinations(t *testing.T) {\n"
},
{
"path": "solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list.go",
"chars": 683,
"preview": "/*\n19. Remove Nth Node From End of List\nhttps://leetcode.com/problems/remove-nth-node-from-end-of-list/\n\nGiven a linked "
},
{
"path": "solutions/0019_remove_nth_node_from_end_of_list/remove_nth_node_from_end_of_list_test.go",
"chars": 762,
"preview": "package rnthnfeol\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestRemoveNthFromEnd(t *testing.T) {\n\ttype arg struct {\n\t\thead"
},
{
"path": "solutions/0020_valid_parentheses/valid_parentheses.go",
"chars": 1166,
"preview": "/*\n20. Valid Parentheses\n\nSource: https://leetcode.com/problems/valid-parentheses/\n\nGiven a string containing just the c"
},
{
"path": "solutions/0020_valid_parentheses/valid_parentheses_test.go",
"chars": 395,
"preview": "package validparentheses\n\nimport \"testing\"\n\nfunc TestIsValid(t *testing.T) {\n\ttestData := []string{\"()\", \"(((((())))))\","
},
{
"path": "solutions/0021_merge_two_sorted_lists/mergeTwoLists.go",
"chars": 796,
"preview": "/*\n21. Merge Two Sorted Lists\nSource: https://leetcode.com/problems/merge-two-sorted-lists/\n\nMerge two sorted linked lis"
},
{
"path": "solutions/0021_merge_two_sorted_lists/mergeTwoLists_test.go",
"chars": 1329,
"preview": "package mergetwolists\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleLinkedList(arr []int) *ListNode {\n\thead := &Li"
},
{
"path": "solutions/0023_merge_k_sorted_lists/mksl.go",
"chars": 1800,
"preview": "/*\n23. Merge k Sorted Lists\nhttps://leetcode.com/problems/merge-k-sorted-lists/\n\nMerge k sorted linked lists and return "
},
{
"path": "solutions/0023_merge_k_sorted_lists/mksl_test.go",
"chars": 1777,
"preview": "package mksl\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestMergeKLists(t *testing.T) {\n\ttestCases := [][]*ListNode{\n\t\t{\n\t\t"
},
{
"path": "solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs.go",
"chars": 695,
"preview": "/*\n24. Swap Nodes in Pairs\nhttps://leetcode.com/problems/swap-nodes-in-pairs/\n\nGiven a linked list, swap every two adjac"
},
{
"path": "solutions/0024_swap_nodes_in_pairs/swap_nodes_in_pairs_test.go",
"chars": 485,
"preview": "package swapnodesinpairs\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSwapPairs(t *testing.T) {\n\thead := createSingleList"
},
{
"path": "solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group.go",
"chars": 1422,
"preview": "/*\n25. Reverse Nodes in k-Group\n\nSource: https://leetcode.com/problems/reverse-nodes-in-k-group/\n\nGiven a linked list, r"
},
{
"path": "solutions/0025_reverse_nodes_in_k_group/reverse_node_k_group_test.go",
"chars": 1183,
"preview": "package reversenodesinkgroup\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleLinkedList(arr []int) *ListNode {\n\thead"
},
{
"path": "solutions/0026_remove_duplicates_from_sorted_array/rdfsa.go",
"chars": 917,
"preview": "/*\n26. Remove Duplicates from Sorted Array\nhttps://leetcode.com/problems/remove-duplicates-from-sorted-array/\n\nGiven a s"
},
{
"path": "solutions/0026_remove_duplicates_from_sorted_array/rdfsa_test.go",
"chars": 407,
"preview": "package rdfsa\n\nimport \"testing\"\n\nfunc TestRemoveDuplicates(t *testing.T) {\n\t// removeDuplicates([]int{0, 0, 1, 1, 1, 2, "
},
{
"path": "solutions/0027_remove_element/remove_element.go",
"chars": 879,
"preview": "/*\n27. Remove Element\nhttps://leetcode.com/problems/remove-element/\n\nGiven an array nums and a value val, remove all ins"
},
{
"path": "solutions/0027_remove_element/remove_element_test.go",
"chars": 254,
"preview": "package removeelement\n\nimport \"testing\"\n\nfunc TestRemoveElement(t *testing.T) {\n\tnums := []int{0, 1, 2, 2, 3, 0, 4, 2}\n\t"
},
{
"path": "solutions/0028_implement_strstr/implement_strstr.go",
"chars": 736,
"preview": "/*\n28. Implement strStr()\nhttps://leetcode.com/problems/implement-strstr/\n\nImplement strStr().\n\nReturn the index of the "
},
{
"path": "solutions/0028_implement_strstr/implement_strstr_test.go",
"chars": 455,
"preview": "package implstr\n\nimport \"testing\"\n\nfunc TestStrStr(t *testing.T) {\n\ttype arg struct {\n\t\thaystack string\n\t\tneedle strin"
},
{
"path": "solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array.go",
"chars": 1351,
"preview": "/*\n33. Search in Rotated Sorted Array\nhttps://leetcode.com/problems/search-in-rotated-sorted-array/\n\nSuppose an array so"
},
{
"path": "solutions/0033_search_in_rotated_sorted_array/search_in_rotated_sorted_array_test.go",
"chars": 700,
"preview": "package searchinrotatedsortedarray\n\nimport \"testing\"\n\nfunc TestSearch(t *testing.T) {\n\ttype arg struct {\n\t\tnums []int\n"
},
{
"path": "solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array.go",
"chars": 2455,
"preview": "/*\n34. Find First and Last Position of Element in Sorted Array\nhttps://leetcode.com/problems/find-first-and-last-positio"
},
{
"path": "solutions/0034_find_first_and_last_position_of_element_in_sorted_array/find_first_and_last_position_of_element_in_sorted_array_test.go",
"chars": 1022,
"preview": "package findfirstandlastpositionofelementinsortedarray\n\nimport (\n\t\"reflect\"\n\t\"runtime\"\n\t\"testing\"\n)\n\nfunc TestSearchRang"
},
{
"path": "solutions/0035_search_insert_position/search_insert_position.go",
"chars": 649,
"preview": "/*\n35. Search Insert Position\nhttps://leetcode.com/problems/search-insert-position/\n\nGiven a sorted array and a target v"
},
{
"path": "solutions/0035_search_insert_position/search_insert_position_test.go",
"chars": 399,
"preview": "package sip\n\nimport \"testing\"\n\nfunc TestSearchInsert(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{1, 3, 5, 6},\n\t\t{1, 3, 5, "
},
{
"path": "solutions/0048_rotate_image/rotate_image.go",
"chars": 904,
"preview": "/*\n48. Rotate Image\nhttps://leetcode.com/problems/rotate-image/\n\nYou are given an n x n 2D matrix representing an image."
},
{
"path": "solutions/0048_rotate_image/rotate_image_test.go",
"chars": 386,
"preview": "package ri\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestRotate(t *testing.T) {\n\tmatrix := [][]int{\n\t\t{5, 1, 9, 11},\n\t\t{2,"
},
{
"path": "solutions/0053_maximum_subarray/maximum_subarray.go",
"chars": 704,
"preview": "/*\n53. Maximum Subarray\nhttps://leetcode.com/problems/maximum-subarray/\n\nGiven an integer array nums,\nfind the contiguou"
},
{
"path": "solutions/0053_maximum_subarray/maximum_subarray_test.go",
"chars": 244,
"preview": "package maximumsubarray\n\nimport \"testing\"\n\nfunc TestMaxSubarray(t *testing.T) {\n\tnums := []int{-2, 1, -3, 4, -1, 2, 1, -"
},
{
"path": "solutions/0058_length_of_last_word/len_of_last_word.go",
"chars": 680,
"preview": "/*\n58. Length of Last Word\nhttps://leetcode.com/problems/length-of-last-word/\n\nGiven a string s consists of upper/lower-"
},
{
"path": "solutions/0058_length_of_last_word/len_of_last_word_test.go",
"chars": 223,
"preview": "package lenoflastword\n\nimport \"testing\"\n\nfunc TestLengthOfLastWord(t *testing.T) {\n\ts := \"hello world \"\n\texpected := 5\n\t"
},
{
"path": "solutions/0061_rotate_list/rotate_list.go",
"chars": 1270,
"preview": "/*\n61. Rotate List\n\nSource: https://leetcode.com/problems/rotate-list/\n\nGiven a linked list, rotate the list to the righ"
},
{
"path": "solutions/0061_rotate_list/rotate_list_test.go",
"chars": 1479,
"preview": "package rotatelist\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleLinkedList(arr []int) *ListNode {\n\thead := &ListN"
},
{
"path": "solutions/0062_unique_paths/unique_paths.go",
"chars": 1793,
"preview": "/*\n62. Unique Paths\nSource: https://leetcode.com/problems/unique-paths/\n\nA robot is located at the top-left corner of a "
},
{
"path": "solutions/0062_unique_paths/unique_paths_test.go",
"chars": 359,
"preview": "package uniquepaths\n\nimport \"testing\"\n\nfunc TestUniquePaths(t *testing.T) {\n\ttestData := [][2]int{\n\t\t{3, 2},\n\t\t{51, 9},\n"
},
{
"path": "solutions/0063_unique_paths_2/unique_paths2.go",
"chars": 3013,
"preview": "/*\n63. Unique Paths II\n\nSource: https://leetcode.com/problems/unique-paths-ii/\n\nA robot is located at the top-left corne"
},
{
"path": "solutions/0063_unique_paths_2/unique_paths2_test.go",
"chars": 475,
"preview": "package uniquepaths2\n\nimport \"testing\"\n\nfunc TestUniquePaths2(t *testing.T) {\n\ttestData := [][][]int{\n\t\t{\n\t\t\t{0, 0, 0},\n"
},
{
"path": "solutions/0064_minimum_path_sum/minimum_path_sum.go",
"chars": 1779,
"preview": "/*\n64. Minimum Path Sum\nsource: https://leetcode.com/problems/minimum-path-sum/\n\nDescription\nGiven a m x n grid filled w"
},
{
"path": "solutions/0064_minimum_path_sum/minimum_path_sum_test.go",
"chars": 1363,
"preview": "package minimumpathsum\n\nimport \"testing\"\n\nfunc TestMininumPathSum(t *testing.T) {\n\ttestData := [][][]int{\n\t\t{\n\t\t\t{1, 3, "
},
{
"path": "solutions/0066_plus_one/plus_one.go",
"chars": 786,
"preview": "/*\n66. Plus One\nhttps://leetcode.com/problems/plus-one/\n\nGiven a non-empty array of digits representing a non-negative i"
},
{
"path": "solutions/0066_plus_one/plus_one_test.go",
"chars": 265,
"preview": "package plusone\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestPlusOne(t *testing.T) {\n\tdigits := []int{9, 9, 9, 9}\n\texpect"
},
{
"path": "solutions/0067_add_binary/add_binary.go",
"chars": 1019,
"preview": "/*\n67. Add Binary\nhttps://leetcode.com/problems/add-binary/\n\nGiven two binary strings, return their sum (also a binary s"
},
{
"path": "solutions/0067_add_binary/add_binary_test.go",
"chars": 422,
"preview": "package addbinary\n\nimport (\n\t\"testing\"\n)\n\nfunc TestAddBinary(t *testing.T) {\n\ttype arg struct {\n\t\ta string\n\t\tb string\n\t}"
},
{
"path": "solutions/0069_sqrtx/sqrtx.go",
"chars": 731,
"preview": "/*\n69. Sqrt(x)\nhttps://leetcode.com/problems/sqrtx/\n\nImplement int sqrt(int x).\n\nCompute and return the square root of x"
},
{
"path": "solutions/0069_sqrtx/sqrtx_test.go",
"chars": 280,
"preview": "package sqrtx\n\nimport \"testing\"\n\nfunc TestMySqrt(t *testing.T) {\n\ttestCases := []int{66, 99, 9}\n\texpected := []int{8, 9,"
},
{
"path": "solutions/0070_climbing_stairs/climbing_stairs.go",
"chars": 1293,
"preview": "/*\n70. Climbing Stairs\n\nsource:https://leetcode.com/problems/climbing-stairs/\n\nYou are climbing a stair case. It takes n"
},
{
"path": "solutions/0070_climbing_stairs/climbing_stairs_test.go",
"chars": 310,
"preview": "package climbingstairs\n\nimport \"testing\"\n\nfunc TestClimbStairs(t *testing.T) {\n\ttestDatas := []int{0, 1, 2, 3, 34}\n\texpe"
},
{
"path": "solutions/0075_sort_colors/sort_colors.go",
"chars": 1126,
"preview": "/*\n75. Sort Colors\nhttps://leetcode.com/problems/sort-colors/\n\nGiven an array with n objects colored red, white or blue,"
},
{
"path": "solutions/0075_sort_colors/sort_colors_test.go",
"chars": 544,
"preview": "package sortcolors\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestSortColorsCountSort(t *testing.T) {\n\tnums := []int{2, 0, "
},
{
"path": "solutions/0076_minimum_window_substring/minimum_window_substring.go",
"chars": 1483,
"preview": "/*\n76. Minimum Window Substring\nhttps://leetcode.com/problems/minimum-window-substring/\n\nGiven a string S and a string T"
},
{
"path": "solutions/0076_minimum_window_substring/minimum_window_substring_test.go",
"chars": 241,
"preview": "package minimumwindowsubstring\n\nimport \"testing\"\n\nfunc TestMinWindow(t *testing.T) {\n\ts := \"ADOBECODEBANC\"\n\tl := \"ABC\"\n\t"
},
{
"path": "solutions/0077_combinations/combinations.go",
"chars": 887,
"preview": "/*\n77. Combinations\nhttps://leetcode.com/problems/combinations/\n\nGiven two integers n and k, return all possible combina"
},
{
"path": "solutions/0077_combinations/combinations_test.go",
"chars": 493,
"preview": "package combinations\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestCombine(t *testing.T) {\n\ttype arg struct {\n\t\tn, k int\n\t"
},
{
"path": "solutions/0079_word_search/word_search.go",
"chars": 1463,
"preview": "/*\n79. Word Search\nhttps://leetcode.com/problems/word-search/\n\nGiven a 2D board and a word, find if the word exists in t"
},
{
"path": "solutions/0079_word_search/word_search_test.go",
"chars": 422,
"preview": "package wordsearch\n\nimport \"testing\"\n\nfunc TestExist(t *testing.T) {\n\tboard := [][]byte{\n\t\t{'A', 'B', 'C', 'E'},\n\t\t{'S',"
},
{
"path": "solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2.go",
"chars": 1006,
"preview": "/*\n80. Remove Duplicates from Sorted Array II\nhttps://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/\n\nGiv"
},
{
"path": "solutions/0080_remove_duplicates_from_sorted_array2/rdfsa2_test.go",
"chars": 410,
"preview": "package rdfsa2\n\nimport \"testing\"\n\nfunc TestRemoveDuplicates(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{1, 1, 1, 2, 2, 3},"
},
{
"path": "solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl.go",
"chars": 804,
"preview": "/*\n82. Remove Duplicates from Sorted List II\nhttps://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/\n\nGiven"
},
{
"path": "solutions/0082_remove_duplicates_from_sorted_list_2/rdfsl_test.go",
"chars": 706,
"preview": "package rdfsl\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestDeleteDuplicates(t *testing.T) {\n\ttestCases := []*ListNode{\n\t\t"
},
{
"path": "solutions/0083_remove_duplicates_from_sorted_list/rdfsl.go",
"chars": 666,
"preview": "/*\n83. Remove Duplicates from Sorted List\nhttps://leetcode.com/problems/remove-duplicates-from-sorted-list/\n\nGiven a sor"
},
{
"path": "solutions/0083_remove_duplicates_from_sorted_list/rdfsl_test.go",
"chars": 707,
"preview": "package rdfsl\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleLinkedList(nums []int) *ListNode {\n\thead := &ListNode{"
},
{
"path": "solutions/0086_partition_list/partition_list.go",
"chars": 928,
"preview": "/*\n86. Partition List\nhttps://leetcode.com/problems/partition-list/\n\nGiven a linked list and a value x,\npartition it suc"
},
{
"path": "solutions/0086_partition_list/partition_list_test.go",
"chars": 544,
"preview": "package partitionlist\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleLinkedList(nums []int) *ListNode {\n\thead := &L"
},
{
"path": "solutions/0088_merge_sorted_array/msa.go",
"chars": 1061,
"preview": "/*\n88. Merge Sorted Array\nhttps://leetcode.com/problems/merge-sorted-array/\n\nGiven two sorted integer arrays nums1 and n"
},
{
"path": "solutions/0088_merge_sorted_array/msa_test.go",
"chars": 600,
"preview": "package msa\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestMerge(t *testing.T) {\n\ttype arg struct {\n\t\tnums1 []int\n\t\tm i"
},
{
"path": "solutions/0092_reverse_linked_list_2/reverse_linked_list2.go",
"chars": 1016,
"preview": "/*\n92. Reverse Linked List II\nhttps://leetcode.com/problems/reverse-linked-list-ii/\n\nReverse a linked list from position"
},
{
"path": "solutions/0092_reverse_linked_list_2/reverse_linked_list2_test.go",
"chars": 530,
"preview": "package reverselinkedlist2\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSingleList(nums []int) *ListNode {\n\thead := &Li"
},
{
"path": "solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal.go",
"chars": 785,
"preview": "/*\n94. Binary Tree Inorder Traversal\nsource: https://leetcode.com/problems/binary-tree-inorder-traversal/\n\nGiven a binar"
},
{
"path": "solutions/0094_binary_tree_inorder_traversal/binary_tree_inorder_traversal_test.go",
"chars": 719,
"preview": "package binarytreeinordertraversal\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []int) *TreeNode {\n\tret"
},
{
"path": "solutions/0100_same_tree/same_tree.go",
"chars": 604,
"preview": "/*\n100. Same Tree\nhttps://leetcode.com/problems/same-tree/\n\nGiven two binary trees, write a function to check if they ar"
},
{
"path": "solutions/0100_same_tree/same_tree_test.go",
"chars": 831,
"preview": "package sametree\n\nimport \"testing\"\n\ntype arg struct {\n\tp []int\n\tq []int\n}\n\nfunc createBinaryTree(nums []int) *TreeNode {"
},
{
"path": "solutions/0101_symmetric_tree/symmetric_tree.go",
"chars": 677,
"preview": "/*\n101. Symmetric Tree\nhttps://leetcode.com/problems/symmetric-tree/\n\nGiven a binary tree, check whether it is a mirror "
},
{
"path": "solutions/0101_symmetric_tree/symmetric_tree_test.go",
"chars": 705,
"preview": "package symmetrictree\n\nimport (\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []int) *TreeNode {\n\treturn performCreate(nums, "
},
{
"path": "solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal.go",
"chars": 1153,
"preview": "/*\n102. Binary Tree Level Order Traversal\nhttps://leetcode.com/problems/binary-tree-level-order-traversal/\n\nGiven a bina"
},
{
"path": "solutions/0102_binary_tree_level_order_traversal/binary_tree_level_order_traversal_test.go",
"chars": 717,
"preview": "package btlot\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestLevelOrder(t *testing.T) {\n\ttestCases := []*TreeNode{\n\t\tcreate"
},
{
"path": "solutions/0104_maximun_depth_of_binary_tree/maxdobt.go",
"chars": 821,
"preview": "/*\n104. Maximum Depth of Binary Tree\nhttps://leetcode.com/problems/maximum-depth-of-binary-tree/\n\nGiven a binary tree, f"
},
{
"path": "solutions/0104_maximun_depth_of_binary_tree/maxdobt_test.go",
"chars": 550,
"preview": "package maxdobt\n\nimport \"testing\"\n\nfunc TestMaxDepth(t *testing.T) {\n\troot := createBinaryTree([]int{1, 2, 3, 4, 5})\n\tex"
},
{
"path": "solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2.go",
"chars": 1060,
"preview": "/*\n107. Binary Tree Level Order Traversal II\nhttps://leetcode.com/problems/binary-tree-level-order-traversal-ii/\n\nGiven "
},
{
"path": "solutions/0107_binary_tree_level_order_traversal_2/binary_tree_level_order_traversal2_test.go",
"chars": 777,
"preview": "package binarytreelevelordertraversal2\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []int) *TreeNode {\n"
},
{
"path": "solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree.go",
"chars": 715,
"preview": "/*\n111. Minimum Depth of Binary Tree\nhttps://leetcode.com/problems/minimum-depth-of-binary-tree/\n\nGiven a binary tree, f"
},
{
"path": "solutions/0111_minimum_depth_of_binary_tree/minimum_depth_of_binary_tree_test.go",
"chars": 659,
"preview": "package minimumdepthofbinarytree\n\nimport \"testing\"\n\nfunc createBinaryTree(nums []int) *TreeNode {\n\treturn performCreate("
},
{
"path": "solutions/0112_path_sum/path_sum.go",
"chars": 614,
"preview": "/*\n112. Path Sum\nhttps://leetcode.com/problems/path-sum/\n\nGiven a binary tree and a sum, determine if the tree has a roo"
},
{
"path": "solutions/0112_path_sum/path_sum_test.go",
"chars": 980,
"preview": "package pathsum\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []interface{}) *TreeNode {\n\treturn performCreat"
},
{
"path": "solutions/0120_triangle/triangle.go",
"chars": 1256,
"preview": "/*\n120. Triangle\nhttps://leetcode.com/problems/triangle/\n\nGiven a triangle, find the minimum path sum from top to bottom"
},
{
"path": "solutions/0120_triangle/triangle_test.go",
"chars": 397,
"preview": "package triangle\n\nimport (\n\t\"testing\"\n)\n\nfunc TestTriangle(t *testing.T) {\n\ttestData := [][][]int{\n\t\t{{2}, {3, 4}, {6, 5"
},
{
"path": "solutions/0121_best_time_to_buy_and_sell_stock/maxprofit.go",
"chars": 1215,
"preview": "/*\n121. Best Time to Buy and Sell Stock\nhttps://leetcode.com/problems/best-time-to-buy-and-sell-stock/\n\nSay you have an "
},
{
"path": "solutions/0121_best_time_to_buy_and_sell_stock/maxprofit_test.go",
"chars": 749,
"preview": "package maxprofit\n\nimport \"testing\"\n\nfunc TestMaxProfit(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{7, 1, 5, 3, 6, 4},\n\t\t{"
},
{
"path": "solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit.go",
"chars": 913,
"preview": "/*\n122. Best Time to Buy and Sell Stock II\nhttps://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/\n\nSay you ha"
},
{
"path": "solutions/0122_best_time_to_buy_and_sell_stock_2/maxprofit_test.go",
"chars": 362,
"preview": "package maxprofit\n\nimport \"testing\"\n\nfunc TestMaxProfit(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{7, 1, 5, 3, 6, 4},\n\t\t{"
},
{
"path": "solutions/0125_valid_palindrome/valid_palindrome.go",
"chars": 820,
"preview": "/*\n125. Valid Palindrome\nhttps://leetcode.com/problems/valid-palindrome/\n\nGiven a string, determine if it is a palindrom"
},
{
"path": "solutions/0125_valid_palindrome/valid_palindrome_test.go",
"chars": 383,
"preview": "package validpalindrome\n\nimport \"testing\"\n\nfunc TestIsPalindrome(t *testing.T) {\n\ttestCases := []string{\n\t\t\"A man, a pla"
},
{
"path": "solutions/0136_single_number/single_number.go",
"chars": 669,
"preview": "/*\n136. Single Number\nhttps://leetcode.com/problems/single-number/\n\nGiven a non-empty array of integers, every element a"
},
{
"path": "solutions/0136_single_number/single_number_test.go",
"chars": 422,
"preview": "package sn\n\nimport \"testing\"\n\nfunc TestSingleNumber(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{2, 2, 1},\n\t\t{4, 1, 2, 1, 2"
},
{
"path": "solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal.go",
"chars": 1362,
"preview": "/*\n144. Binary Tree Preorder Traversal\nhttps://leetcode.com/problems/binary-tree-preorder-traversal/\n\nGiven a binary tre"
},
{
"path": "solutions/0144_binary_tree_preorder_traversal/binary_tree_preorder_traversal_test.go",
"chars": 869,
"preview": "package btpot\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []int) *TreeNode {\n\treturn performCreate(num"
},
{
"path": "solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation.go",
"chars": 1062,
"preview": "/*\n150. Evaluate Reverse Polish Notation\nhttps://leetcode.com/problems/evaluate-reverse-polish-notation/\n\nEvaluate the v"
},
{
"path": "solutions/0150_evaluate_reverse_polish_notation/evaluate_reverse_polish_notation_test.go",
"chars": 464,
"preview": "package evaluatereversepolishnotation\n\nimport \"testing\"\n\nfunc TestEvalRPN(t *testing.T) {\n\ttestCases := [][]string{\n\t\t{\""
},
{
"path": "solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa.go",
"chars": 687,
"preview": "/*\n153. Find Minimum in Rotated Sorted Array\nhttps://leetcode.com/problems/find-minimum-in-rotated-sorted-array/\n\nSuppos"
},
{
"path": "solutions/0153_find_minimum_in_rotated_sorted_array/fmirsa_test.go",
"chars": 210,
"preview": "package fmirsa\n\nimport \"testing\"\n\nfunc TestFindMin(t *testing.T) {\n\tnums := []int{3, 4, 5, 1, 2}\n\texpected := 1\n\tif res "
},
{
"path": "solutions/0155_min_stack/min_stack.go",
"chars": 1502,
"preview": "/*\n155. Min Stack\nhttps://leetcode.com/problems/min-stack/\n\nDesign a stack that supports push, pop, top, and retrieving "
},
{
"path": "solutions/0155_min_stack/min_stack_test.go",
"chars": 391,
"preview": "package minstack\n\nimport \"testing\"\n\nfunc TestMinStack(t *testing.T) {\n\tobj := Constructor()\n\tobj.Push(-2)\n\tobj.Push(0)\n\t"
},
{
"path": "solutions/0165_compare_version_numbers/compare_version_numbers.go",
"chars": 1595,
"preview": "/*\n165. Compare Version Numbers\nhttps://leetcode.com/problems/compare-version-numbers/\n\nCompare two version numbers vers"
},
{
"path": "solutions/0165_compare_version_numbers/compare_version_numbers_test.go",
"chars": 506,
"preview": "package compareversionnumbers\n\nimport \"testing\"\n\nfunc TestCompareVersion(t *testing.T) {\n\ttype arg struct {\n\t\tversion1 s"
},
{
"path": "solutions/0167_two_sum2/two_sum2.go",
"chars": 1023,
"preview": "/*\n167. Two Sum II - Input array is sorted\nhttps://leetcode.com/problems/two-sum-ii-input-array-is-sorted/\n\nGiven an arr"
},
{
"path": "solutions/0167_two_sum2/two_sum2_test.go",
"chars": 595,
"preview": "package twosum2\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\ntype arg struct {\n\tnumbers []int\n\ttarget int\n}\n\nfunc TestTwoSum2(t *"
},
{
"path": "solutions/0179_largest_number/ln.go",
"chars": 1153,
"preview": "/*\n179. Largest Number\nhttps://leetcode.com/problems/largest-number/\n\nGiven a list of non negative integers, arrange the"
},
{
"path": "solutions/0179_largest_number/ln_test.go",
"chars": 353,
"preview": "package ln\n\nimport \"testing\"\n\nfunc TestLargestNumber(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{10, 2},\n\t\t{3, 30, 34, 5, "
},
{
"path": "solutions/0198_house_robber/house_robber.go",
"chars": 2126,
"preview": "/*\n198. House Robber\nhttps://leetcode.com/problems/house-robber/\n\nYou are a professional robber planning to rob houses a"
},
{
"path": "solutions/0198_house_robber/house_robber_test.go",
"chars": 361,
"preview": "package houserobber\n\nimport \"testing\"\n\nfunc TestHouseRobber(t *testing.T) {\n\ttestData := [][]int{\n\t\t{1, 2, 3, 1},\n\t\t{9, "
},
{
"path": "solutions/0200_number_of_island/number_of_island.go",
"chars": 1240,
"preview": "/*\n200. Number of Islands\nhttps://leetcode.com/problems/number-of-islands/\n\nGiven a 2d grid map of '1's (land) and '0's "
},
{
"path": "solutions/0200_number_of_island/number_of_island_test.go",
"chars": 409,
"preview": "package noi\n\nimport \"testing\"\n\nfunc TestNumIslands(t *testing.T) {\n\tgrids := [][][]byte{\n\t\t{\n\t\t\t{'1', '1', '0', '0', '0'"
},
{
"path": "solutions/0203_remove_linked_list_elements/remove_linked_list_elements.go",
"chars": 883,
"preview": "/*\n203. Remove Linked List Elements\nhttps://leetcode.com/problems/remove-linked-list-elements/\n\nRemove all elements from"
},
{
"path": "solutions/0203_remove_linked_list_elements/remove_linked_list_elements_test.go",
"chars": 834,
"preview": "package rlle\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestRemoveElements(t *testing.T) {\n\thead := createSinglyLinkedList("
},
{
"path": "solutions/0206_reverse_linked_list/reverse_linked_list.go",
"chars": 744,
"preview": "/*\n206. Reverse Linked List\nhttps://leetcode.com/problems/reverse-linked-list/\n\nReverse a singly linked list.\n*/\n// time"
},
{
"path": "solutions/0206_reverse_linked_list/reverse_linked_list_test.go",
"chars": 777,
"preview": "package rll\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestReverseList(t *testing.T) {\n\thead := createSinglyLinkedList([]in"
},
{
"path": "solutions/0208_implement_trie_prefix_tree/impltrie.go",
"chars": 1453,
"preview": "/*\n208. Implement Trie (Prefix Tree)\nhttps://leetcode.com/problems/implement-trie-prefix-tree/\n\nImplement a trie with in"
},
{
"path": "solutions/0208_implement_trie_prefix_tree/impltrie_test.go",
"chars": 560,
"preview": "package impltree\n\nimport \"testing\"\n\nfunc TestImplTrie(t *testing.T) {\n\ttrie := Constructor()\n\ttrie.Insert(\"apple\")\n\n\tfor"
},
{
"path": "solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum.go",
"chars": 908,
"preview": "/*\n209. Minimum Size Subarray Sum\nhttps://leetcode.com/problems/minimum-size-subarray-sum/\n\nGiven an array of n positive"
},
{
"path": "solutions/0209_minimum_size_subarray_sum/minimum_size_subarray_sum_test.go",
"chars": 530,
"preview": "package minimumsizesubarraysum\n\nimport \"testing\"\n\nfunc TestMinSubArrayLen(t *testing.T) {\n\ttype arg struct {\n\t\ts int\n"
},
{
"path": "solutions/0211_add_and_search_word/add_and_search_word.go",
"chars": 1359,
"preview": "/*\n211. Add and Search Word - Data structure design\nhttps://leetcode.com/problems/add-and-search-word-data-structure-des"
},
{
"path": "solutions/0211_add_and_search_word/add_and_search_word_test.go",
"chars": 370,
"preview": "package aasw\n\nimport \"testing\"\n\nfunc TestAddAndSearchWord(t *testing.T) {\n\tobj := Constructor()\n\n\tfor _, word := range ["
},
{
"path": "solutions/0215_kth_largest_element_in_an_array/kthleiaa.go",
"chars": 914,
"preview": "/*\n215. Kth Largest Element in an Array\nhttps://leetcode.com/problems/kth-largest-element-in-an-array/\n\nFind the kth lar"
},
{
"path": "solutions/0215_kth_largest_element_in_an_array/kthleiaa_test.go",
"chars": 441,
"preview": "package kthleiaa\n\nimport \"testing\"\n\nfunc TestFindKthLargest(t *testing.T) {\n\ttype arg struct {\n\t\tnums []int\n\t\tk int\n\t"
},
{
"path": "solutions/0217_contains_duplicate/contains_duplicate.go",
"chars": 597,
"preview": "/*\n217. Contains Duplicate\nhttps://leetcode.com/problems/contains-duplicate/\n\nGiven an array of integers, find if the ar"
},
{
"path": "solutions/0217_contains_duplicate/contains_duplicate_test.go",
"chars": 331,
"preview": "package cd\n\nimport \"testing\"\n\nfunc TestContainsDuplicate(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{1, 2, 3, 1},\n\t\t{1, 2,"
},
{
"path": "solutions/0219_contains_duplicate_2/contains_duplicate_2.go",
"chars": 621,
"preview": "/*\n219. Contains Duplicate II\nhttps://leetcode.com/problems/contains-duplicate-ii/\n\nGiven an array of integers and an in"
},
{
"path": "solutions/0219_contains_duplicate_2/contains_duplicate_2_test.go",
"chars": 406,
"preview": "package cond\n\nimport \"testing\"\n\nfunc TestContainsNearbyDuplicate(t *testing.T) {\n\ttestCases := [][]int{\n\t\t{1, 2, 3, 1},\n"
},
{
"path": "solutions/0226_invert_binary_tree/invert_binary_tree.go",
"chars": 560,
"preview": "/*\n226. Invert Binary Tree\nhttps://leetcode.com/problems/invert-binary-tree/\n\nInvert a binary tree.\n*/\n\npackage invertbi"
},
{
"path": "solutions/0226_invert_binary_tree/invert_binary_tree_test.go",
"chars": 1262,
"preview": "package invertbinarytree\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []interface{}) *TreeNode {\n\tretur"
},
{
"path": "solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst.go",
"chars": 1172,
"preview": "/*\n235. Lowest Common Ancestor of a Binary Search Tree\nhttps://leetcode.com/problems/lowest-common-ancestor-of-a-binary-"
},
{
"path": "solutions/0235_lowest_common_ancestor_of_a_binary_search_tree/lcaoabst_test.go",
"chars": 996,
"preview": "package lcaoabst\n\nimport (\n\t\"testing\"\n)\n\nfunc TestLowestCommonAncestor(t *testing.T) {\n\ttype arg struct {\n\t\troot, p, q *"
},
{
"path": "solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca.go",
"chars": 578,
"preview": "/*\n236. Lowest Common Ancestor of a Binary Tree\nhttps://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/\n*"
},
{
"path": "solutions/0236_Lowest_Common_Ancestor_of_a_Binary_Tree/lca_test.go",
"chars": 991,
"preview": "package lca\n\nimport \"testing\"\n\nfunc TestLCA(t *testing.T) {\n\ttype arg struct {\n\t\troot, p, q *TreeNode\n\t}\n\n\ttree := creat"
},
{
"path": "solutions/0237_delete_node_in_a_linked_list/dniall.go",
"chars": 908,
"preview": "/*\n237. Delete Node in a Linked List\nhttps://leetcode.com/problems/delete-node-in-a-linked-list/\n\nWrite a function to de"
},
{
"path": "solutions/0237_delete_node_in_a_linked_list/dniall_test.go",
"chars": 511,
"preview": "package dniall\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSinglyLinkedList(nums []int) *ListNode {\n\thead := &ListNode"
},
{
"path": "solutions/0257_binary_tree_paths/binary_tree_paths.go",
"chars": 965,
"preview": "/*\n257. Binary Tree Paths\nhttps://leetcode.com/problems/binary-tree-paths/\n\nGiven a binary tree, return all root-to-leaf"
},
{
"path": "solutions/0257_binary_tree_paths/binary_tree_paths_test.go",
"chars": 735,
"preview": "package btp\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createBinaryTree(nums []int) *TreeNode {\n\treturn performCreate(nums,"
},
{
"path": "solutions/0258_add_digits/add_digits.go",
"chars": 756,
"preview": "/*\n258. Add Digits\nhttps://leetcode.com/problems/add-digits/\n\nGiven a non-negative integer num, repeatedly add all its d"
},
{
"path": "solutions/0258_add_digits/add_digits_test.go",
"chars": 296,
"preview": "package ad\n\nimport \"testing\"\n\nfunc TestAddDigits(t *testing.T) {\n\tnum := 38\n\texpected := 2\n\n\ttestFuncs := []func(int) in"
},
{
"path": "solutions/0283_move_zeroes/move_zeroes.go",
"chars": 433,
"preview": "/*\n283. Move Zeroes\nhttps://leetcode.com/problems/move-zeroes/\n\nGiven an array nums, write a function to move all 0's to"
},
{
"path": "solutions/0283_move_zeroes/move_zeroes2.go",
"chars": 468,
"preview": "/*\n283. Move Zeroes\nhttps://leetcode.com/problems/move-zeroes/\n\nGiven an array nums, write a function to move all 0's to"
},
{
"path": "solutions/0283_move_zeroes/move_zeroes2_test.go",
"chars": 367,
"preview": "package movezeroes\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestMoveZeroes2(t *testing.T) {\n\ttestData := [][]int{\n\t\t{0, 1"
},
{
"path": "solutions/0283_move_zeroes/move_zeroes_test.go",
"chars": 365,
"preview": "package movezeroes\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestMoveZeroes(t *testing.T) {\n\ttestData := [][]int{\n\t\t{0, 1,"
},
{
"path": "solutions/0300_longest_increasing_subsequence/lis.go",
"chars": 988,
"preview": "/*\n300. Longest Increasing Subsequence\nhttps://leetcode.com/problems/longest-increasing-subsequence/\n\nGiven an unsorted "
},
{
"path": "solutions/0300_longest_increasing_subsequence/lis_test.go",
"chars": 382,
"preview": "package lis\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\nfunc TestLIS(t *testing.T) {\n\ttestData := [][]int{\n\t\t{10, 9, 2, 5, 3, 7, 101, "
},
{
"path": "solutions/0303_range_sum_query/rsqim.go",
"chars": 697,
"preview": "/*\n303. Range Sum Query - Immutable\nhttps://leetcode.com/problems/range-sum-query-immutable/\n\nGiven an integer array num"
},
{
"path": "solutions/0303_range_sum_query/rsqim_test.go",
"chars": 394,
"preview": "package rsqim\n\nimport \"testing\"\n\nfunc TestSumRange(t *testing.T) {\n\tnums := []int{-2, 0, 3, -5, 2, -1}\n\tranges := [][]in"
},
{
"path": "solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut.go",
"chars": 2495,
"preview": "/*\n307. Range Sum Query - Mutable\nhttps://leetcode.com/problems/range-sum-query-mutable/\n\nGiven an integer array nums, f"
},
{
"path": "solutions/0307_Range_Sum_Query_Mutable/range_sum_query_mut_test.go",
"chars": 335,
"preview": "package rsqm\n\nimport \"testing\"\n\nfunc TestNumArray(t *testing.T) {\n\tnums := []int{1, 2, 3, 6, 7, 8, 9, 3, 4, 2, 5}\n\tna :="
},
{
"path": "solutions/0328_odd_even_linked_list/odd_even_linked_list.go",
"chars": 1049,
"preview": "/*\n328. Odd Even Linked List\nhttps://leetcode.com/problems/odd-even-linked-list/\n\nGiven a singly linked list, group all "
},
{
"path": "solutions/0328_odd_even_linked_list/odd_even_linked_list_test.go",
"chars": 647,
"preview": "package oddevenlinkedlist\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc createSinglyLinkedList(nums []int) *ListNode {\n\thead :"
},
{
"path": "solutions/0343_integer_break/integer_break.go",
"chars": 1464,
"preview": "/*\n343. Integer Break\nhttps://leetcode.com/problems/integer-break\n\nGiven a positive integer n, break it into the sum of "
},
{
"path": "solutions/0343_integer_break/integer_break_test.go",
"chars": 315,
"preview": "package integerbreak\n\nimport \"testing\"\n\nfunc TestIntegerBreak(t *testing.T) {\n\ttestData := []int{2, 10, 34}\n\texpectedDat"
},
{
"path": "solutions/0344_reverse_string/reverse_string.go",
"chars": 742,
"preview": "/*\n344. Reverse String\nhttps://leetcode.com/problems/reverse-string/\n\nWrite a function that takes a string as input and "
},
{
"path": "solutions/0344_reverse_string/reverse_string_test.go",
"chars": 798,
"preview": "package reversestring\n\nimport \"testing\"\n\nfunc TestReverseString(t *testing.T) {\n\ttestCases := []string{\n\t\t\"hello\",\n\t\t\"A "
},
{
"path": "solutions/0345_reverse_vowels_of_a_string/reverse_vowels.go",
"chars": 1178,
"preview": "/*\n345. Reverse Vowels of a String\nhttps://leetcode.com/problems/reverse-vowels-of-a-string/\n\nWrite a function that take"
},
{
"path": "solutions/0345_reverse_vowels_of_a_string/reverse_vowels_test.go",
"chars": 732,
"preview": "package reversevowels\n\nimport \"testing\"\n\nfunc TestReverseVowels(t *testing.T) {\n\ttestCases := []string{\n\t\t\"hello\",\n\t\t\"le"
},
{
"path": "solutions/0347_top_k_frequent_elements/topkfe.go",
"chars": 1508,
"preview": "/*\n347. Top K Frequent Elements\nhttps://leetcode.com/problems/top-k-frequent-elements/\n\nGiven a non-empty array of integ"
},
{
"path": "solutions/0347_top_k_frequent_elements/topkfe_test.go",
"chars": 278,
"preview": "package topkfe\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestTopKFrequent(t *testing.T) {\n\tnums := []int{1, 1, 1, 2, 2, 3}"
},
{
"path": "solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays.go",
"chars": 794,
"preview": "/*\n349. Intersection of Two Arrays\nhttps://leetcode.com/problems/intersection-of-two-arrays\n\nGiven two arrays, write a f"
},
{
"path": "solutions/0349_intersection_of_2_arrays/intersection_of_two_arrays_test.go",
"chars": 317,
"preview": "package intersectionof2arrays\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestIntersection(t *testing.T) {\n\tnums1 := []int{1"
},
{
"path": "solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2.go",
"chars": 496,
"preview": "/*\n350. Intersection of Two Arrays II\nhttps://leetcode.com/problems/intersection-of-two-arrays-ii/\n\n*/\n\npackage intersec"
},
{
"path": "solutions/0350_intersection_of_two_arrays2/intersection_of_two_arrays2_test.go",
"chars": 315,
"preview": "package intersectionof2arrays2\n\nimport (\n\t\"reflect\"\n\t\"testing\"\n)\n\nfunc TestInteract(t *testing.T) {\n\tnums1 := []int{1, 2"
},
{
"path": "solutions/0376_wiggle_subsequence/wiggle_subsequence.go",
"chars": 2244,
"preview": "/*\n376. Wiggle Subsequence\nhttps://leetcode.com/problems/wiggle-subsequence/\n\nA sequence of numbers is called a wiggle s"
},
{
"path": "solutions/0376_wiggle_subsequence/wiggle_subsequence_test.go",
"chars": 2957,
"preview": "package wigglesubsequence\n\nimport \"testing\"\n\nfunc TestWiggleSubsequence(t *testing.T) {\n\ttestData := [][]int{\n\t\t{1, 17, "
},
{
"path": "solutions/0392_is_subsequence/is_subsequence.go",
"chars": 1269,
"preview": "/*\n392. Is Subsequence\nhttps://leetcode.com/problems/is-subsequence/\n\nGiven a string s and a string t, check if s is sub"
},
{
"path": "solutions/0392_is_subsequence/is_subsequence_test.go",
"chars": 439,
"preview": "package issubsequence\n\nimport \"testing\"\n\ntype args struct {\n\ts string\n\tt string\n}\n\nfunc TestAssignCookies(t *testing.T) "
},
{
"path": "solutions/0404_sum_of_left_leaves/sum_of_left_leaves.go",
"chars": 719,
"preview": "/*\n404. Sum of Left Leaves\nhttps://leetcode.com/problems/sum-of-left-leaves/\n\nFind the sum of all left leaves in a given"
}
]
// ... and 52 more files (download for full content)
About this extraction
This page contains the full source code of the keep-practicing/leetcode-go GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 252 files (229.4 KB), approximately 88.8k tokens, and a symbol index with 451 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.