├── LICENSE ├── README.MD └── leetcode ├── 1 - twosum ├── README.MD ├── TwoSum.java ├── TwoSum.scala ├── TwoSumSolution.cs ├── tow-sum.cs ├── two-sum.dart ├── two-sum.go ├── twoSum.js ├── twoSum.ts ├── two_sum.c ├── two_sum.cpp ├── two_sum.ex ├── two_sum.php ├── two_sum.py └── two_sum.rs └── 20 - validparenthesis ├── README.MD └── valid-parenthesis.go /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 X-Team 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | # Community Coding Challenge Handbook 2 | 3 | > This repository focuses on helping X-Teamers and community members to thrive through coding challenges offering solutions in as many languages you can think of. 4 | > 5 | 6 | ## 🚀 Collaborating to the handbook 7 | 8 | 1. You need to fork this repo 9 | 10 | 2. Then you need to clone the repository locally: 11 | 12 | - Using Https: 13 | ``` 14 | git clone https://github.com/{your-github-username}/community-coding-challenges.git 15 | ``` 16 | - Using SSH: 17 | ``` 18 | git clone git@github.com:{your-github-username}/community-coding-challenges.git 19 | ``` 20 | 3. Then you choose the challenge you want to expand and create a new branch using the convention: `{platform}-{challengename}/{language}` 21 | Example: 22 | ``` 23 | git checkout -b leetcode-twosum/go 24 | ``` 25 | 4. Commit your changes using [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) 26 | 5. Create a Pull Request and wait for reviews. If you need help, refer to github documentation on [creating new pull requests](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request). 27 | 28 | ## 🤝 Collaborators 29 | 30 | We thank everybody that help this project reach better places of our community: 31 | 32 | 33 | 34 | 35 | 43 | 44 | 45 | 53 | 54 | 55 | 63 | 64 | 65 | 73 | 74 | 75 |
36 | 37 | Arthur404dev github avatar
38 | 39 | Arthur 40 | 41 |
42 |
46 | 47 | d-leme github avatar
48 | 49 | Diego 50 | 51 |
52 |
56 | 57 | BrenoGO github avatar
58 | 59 | Breno 60 | 61 |
62 |
66 | 67 | toreti github avatar
68 | 69 | Felipe 70 | 71 |
72 |
76 | 77 | ## 📝 License 78 | 79 | This project compliances can be found under the [LICENSE](LICENSE) for any further details. 80 | 81 | [⬆ To the top](#community-coding-challenges)
82 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/README.MD: -------------------------------------------------------------------------------- 1 | # Challenge Description 2 | 3 | [1 - Two Sum](https://leetcode.com/problems/two-sum/) | Difficulty: Easy 4 | 5 | ### Description: 6 | --- 7 | Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. 8 | 9 | You may assume that each input would have exactly one solution, and you may not use the same element twice. 10 | 11 | You can return the answer in any order. 12 | 13 | Example 1: 14 | 15 | ``` 16 | Input: nums = [2,7,11,15], target = 9 17 | Output: [0,1] 18 | Output: Because nums[0] + nums[1] == 9, we return [0, 1]. 19 | ``` 20 | Example 2: 21 | 22 | ``` 23 | Input: nums = [3,2,4], target = 6 24 | Output: [1,2] 25 | ``` 26 | Example 3: 27 | 28 | ``` 29 | Input: nums = [3,3], target = 6 30 | Output: [0,1] 31 | ``` 32 | 33 | **Constraints:** 34 | 35 | - 2 <= nums.length <= 104 36 | - -109 <= nums[i] <= 109 37 | - -109 <= target <= 109 38 | - **Only one valid answer exists.** 39 | 40 | **Follow-up:** Can you come up with an algorithm that is less than O(n2) time complexity? -------------------------------------------------------------------------------- /leetcode/1 - twosum/TwoSum.java: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum/ 2 | # -> Challenge: 3 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | 5 | # You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | # Example: 8 | 9 | # Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | # Because nums[0] + nums[1] = 2 + 7 = 9, 12 | # return [0, 1]. 13 | 14 | package Algoritms; 15 | 16 | import java.util.Arrays; 17 | import java.util.HashMap; 18 | import java.util.Map; 19 | 20 | public class TwoSum { 21 | 22 | public static void main(String[] args) { 23 | int[] inputArray = new int[]{2,7,11,15}; 24 | int inputTarget = 9; 25 | int[] ints = twoSum(inputArray, inputTarget); 26 | Arrays.stream(ints).forEach(System.out::println); 27 | } 28 | 29 | private static int[] twoSum(int[] inputNumbers, int target) { 30 | Map map = new HashMap<>(); 31 | for(int index = 0; index < inputNumbers.length; index++){ 32 | 33 | int targetFound = target - inputNumbers[index]; 34 | if (map.containsKey(targetFound)){ 35 | return new int[]{map.get(targetFound), index}; 36 | } 37 | map.put(inputNumbers[index], index); 38 | } 39 | 40 | return new int[]{}; 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/TwoSum.scala: -------------------------------------------------------------------------------- 1 | package challengers 2 | 3 | object TwoSum extends App { 4 | 5 | def twoSum(nums: Array[Int], target: Int): Array[Int] = { 6 | 7 | def twoSum(inputMap: Map[Int, Int], index: Int): Array[Int] = { 8 | val valueCalculate = target - nums(index) 9 | if (inputMap.contains(valueCalculate)) Array(inputMap(valueCalculate), index) 10 | else twoSum(inputMap + (nums(index) -> index), index + 1) 11 | } 12 | 13 | twoSum(Map.empty[Int, Int], 0) 14 | 15 | } 16 | 17 | val anArray = Array(2, 7, 11, 15) 18 | print(twoSum(anArray, 9).toList) 19 | 20 | } 21 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/TwoSumSolution.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | 4 | namespace twosum 5 | { 6 | public class TwoSumSolution 7 | { 8 | static void Main(string[] args) 9 | { 10 | int[] arr = { 2, 7, 11, 15 }; 11 | 12 | int[] result = TwoSum(arr, 9); 13 | Console.WriteLine("[{0}]", string.Join(", ", result)); 14 | } 15 | 16 | static int[] TwoSum(int[] numbers, int target) 17 | { 18 | Hashtable seen = new Hashtable(); 19 | 20 | for (int i = 0; i < numbers.Length; i++) 21 | { 22 | int num = numbers[i]; 23 | int needed = target - num; 24 | 25 | if (!seen.ContainsKey(needed)) 26 | { 27 | seen.Add(num, i); 28 | } 29 | else 30 | { 31 | int[] result = { Convert.ToInt32(seen[needed]), i }; 32 | return result; 33 | } 34 | 35 | } 36 | 37 | return new int[] { }; 38 | } 39 | 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/tow-sum.cs: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum/ 2 | # -> Challenge: 3 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | 5 | # You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | # Example: 8 | 9 | # Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | # Because nums[0] + nums[1] = 2 + 7 = 9, 12 | # return [0, 1]. 13 | 14 | 15 | public class Solution { 16 | public int[] TwoSum(int[] nums, int target) { 17 | 18 | var dictNums = new Dictionary(); 19 | int rest = 0; 20 | 21 | for(int i = 0; i < nums.Length; i++) 22 | { 23 | rest = target-nums[i]; 24 | 25 | if (dictNums.ContainsKey(rest)) 26 | { 27 | return new[]{dictNums[rest],i}; 28 | } 29 | 30 | dictNums[nums[i]] = i; 31 | } 32 | 33 | return null; 34 | } 35 | } -------------------------------------------------------------------------------- /leetcode/1 - twosum/two-sum.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | final twoSum1 = TwoSum(numbers: [2, 7, 11, 15], target: 9); 3 | final twoSum2 = TwoSum(numbers: [3, 2, 4], target: 6); 4 | final twoSum3 = TwoSum(numbers: [3, 3], target: 6); 5 | print(twoSum1.solve()); 6 | print(twoSum2.solve()); 7 | print(twoSum3.solve()); 8 | } 9 | 10 | class TwoSum { 11 | final List numbers; 12 | final int target; 13 | 14 | TwoSum({ 15 | required this.numbers, 16 | required this.target, 17 | }); 18 | 19 | List solve() { 20 | Map cache = {}; 21 | for (var index = 0; index < numbers.length; index++) { 22 | final targetFound = target - numbers[index]; 23 | if (cache.containsKey(targetFound)) { 24 | return [cache[targetFound]!, index]; 25 | } 26 | cache[numbers[index]] = index; 27 | } 28 | return []; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/two-sum.go: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/two-sum/ 2 | // -> Challenge: 3 | // Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | 5 | // You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | // Example: 8 | 9 | // Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | // Because nums[0] + nums[1] = 2 + 7 = 9, 12 | // return [0, 1]. 13 | 14 | // -> Solution: 15 | 16 | package main 17 | 18 | func twoSumQuadradic(nums []int, target int) []int { 19 | // Time Complexity: O(n2) 20 | // Space Complexity: 21 | 22 | // Se movimentar pela lista, depois escolher um número 23 | for i := 0; i < len(nums)-1; i++ { 24 | // Combinar esse numero com todos os outros 25 | for j := i + 1; j < len(nums); j++ { 26 | 27 | // Não precisamos validar se o indice é o mesmo 28 | // pois o `j` sempre esta 1 número a frente de `i` 29 | 30 | // Testar se a soma dos dois números é igual ao objetivo 31 | if nums[i]+nums[j] == target { 32 | // Quando achar a combinação, retornar a posição dessses números 33 | return []int{i, j} 34 | } 35 | } 36 | } 37 | 38 | // Retornar array vazio caso nenhum das combinações 39 | // derem o resultado correto 40 | return []int{} 41 | } 42 | 43 | // -> Solution: 44 | 45 | func twoSum(nums []int, target int) []int { 46 | // Time Complexity: O(nlog) 47 | // Space Complexity: O(n) 48 | 49 | // Criando mapa 50 | seen := map[int]int{} 51 | 52 | for i, num := range nums { 53 | // Checar qual o par deste numero 54 | pair := target - num 55 | 56 | // Checa se este par do numero atual já foi visto 57 | if _, exists := seen[pair]; exists { 58 | // Já temos a resposta, retornar ambas posições 59 | return []int{seen[pair], i} 60 | } 61 | // Não precisamos do else, pois caso o valor acima for verdadeiro 62 | // a função já retornaria o resultado 63 | 64 | // No caso de não ter visto, guardar informação atual 65 | 66 | seen[num] = i 67 | } 68 | 69 | // Retornar array vazio caso nenhum das combinações 70 | // derem o resultado correto 71 | return []int{} 72 | } 73 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/twoSum.js: -------------------------------------------------------------------------------- 1 | function solution(nums, target) { 2 | const pairs = {}; 3 | for(let i = 0; i < nums.length; i++) { 4 | if (typeof pairs[target - nums[i]] !== 'undefined') { 5 | return [pairs[target - nums[i]], i]; 6 | } 7 | pairs[nums[i]] = i; 8 | } 9 | } -------------------------------------------------------------------------------- /leetcode/1 - twosum/twoSum.ts: -------------------------------------------------------------------------------- 1 | const solution = (nums: number[], target: number) : number[] => nums.reduce( 2 | (pairs, num, index) => nums.includes(target - num) ? [nums.indexOf(target - num), index] : pairs, 3 | [] 4 | ); -------------------------------------------------------------------------------- /leetcode/1 - twosum/two_sum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main(){ 4 | int nums[] = { 2, 7, 11, 15 }; 5 | int target = 9; 6 | int numsLength = sizeof(nums)/sizeof(nums[0]); 7 | 8 | for(int i = 0; i < numsLength; i++) { 9 | for(int j = i +1; j < numsLength; j++){ 10 | if((nums[i] + nums[j]) == target){ 11 | printf("[%d,%d]", i, j); 12 | return; 13 | } 14 | } 15 | } 16 | 17 | return; 18 | } -------------------------------------------------------------------------------- /leetcode/1 - twosum/two_sum.cpp: -------------------------------------------------------------------------------- 1 | // Time complexity: O(N) - linear (tamanho do vetor) 2 | 3 | // A estrutura de dados map pode ser implementada de duas formas, utilizando o conceito de árvore rubro-negra 4 | // ou Hash table. cada estrutura possui vatangens/desvantagens. No exercício em questão a implementação baseada 5 | // em Hash table faz muito mais sentido, visto que o custo de busca de um item em uma Hash table é constante 6 | // e em uma árvore rubro-negra é Log2(N), sendo N o número de elementos contidos no mapa. 7 | 8 | // em C++ temos as duas implementações, onde estrutura map utliza árvore rubro-negra como implementação 9 | // e a estrutura unordered_map utiliza o conceito de Hash table como implementação ;) 10 | 11 | class Solution { 12 | public: 13 | vector twoSum(vector& nums, int target) { 14 | unordered_map storage; 15 | for (int index = 0; index < nums.size(); index++) { 16 | int diff = (target - nums[index]); 17 | if (storage.find(diff) != storage.end()) { 18 | return {index, storage[diff]}; 19 | } 20 | storage[nums[index]] = index; 21 | } 22 | return {}; 23 | } 24 | }; -------------------------------------------------------------------------------- /leetcode/1 - twosum/two_sum.ex: -------------------------------------------------------------------------------- 1 | # Time complexity: O(n^2) - quadrático, N*N, sendo N o tamanho do vetor nums 2 | 3 | # Elixir não foi criado para resolver problemas de CPU-bound 4 | # ou seja, caso você precise resolver problemas onde exija muito da CPU, elixir definitivamente 5 | # não é a linguagem correta =(. Pode até existir um modo melhor de resolver esse problema utilizando elixir 6 | # porém comparado com outras linguagens como (C++, Rust, Golang ou até Python) a complexidade de implementação 7 | # fica extremamente alta. 8 | 9 | # Acredito que possa haver um modo de resolver o problema de outra maneira 10 | # Porém o meu conhecimento de elixir se limita apenas a essa solução XD 11 | 12 | defmodule Solution do 13 | def two_sum(nums, target) do 14 | nums 15 | |> Enum.with_index 16 | |> get_positions(target) 17 | end 18 | 19 | defp get_positions([{number, current_index} | tail], target) do 20 | case exists_sum?(tail, number, target) do 21 | nil -> get_positions(tail, target) 22 | new_index -> [current_index, new_index] 23 | end 24 | end 25 | 26 | defp exists_sum?([{new_value, index} | _tail], current, target) when current + new_value == target, do: index 27 | defp exists_sum?([_ | tail], current, target), do: exists_sum?(tail, current, target) 28 | defp exists_sum?(_, _, _), do: nil 29 | end 30 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/two_sum.php: -------------------------------------------------------------------------------- 1 | $num) { 9 | $pair = $target - $num; 10 | if (isset($seen[$pair])) { 11 | return [$seen[$pair], $pos]; 12 | } 13 | $seen[$num] = $pos; 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/two_sum.py: -------------------------------------------------------------------------------- 1 | # https://leetcode.com/problems/two-sum/ 2 | # -> Challenge: 3 | # Given an array of integers, return indices of the two numbers such that they add up to a specific target. 4 | 5 | # You may assume that each input would have exactly one solution, and you may not use the same element twice. 6 | 7 | # Example: 8 | 9 | # Given nums = [2, 7, 11, 15], target = 9, 10 | 11 | # Because nums[0] + nums[1] = 2 + 7 = 9, 12 | # return [0, 1]. 13 | 14 | # class QuadraticSolution: 15 | # def twoSum(self, nums: List[int], target: int) -> List[int]: 16 | # # Time Complexity: O(n2) 17 | # # Space Complexity: 18 | # # Se movimentar pela lista, depois de escolher um numero 19 | # for i, num1 in enumerate(nums): 20 | # # Combinar esse numero com todos os outros 21 | # for j, num2 in enumerate(nums): 22 | # if i != j: 23 | # # Testar se a soma dos dois e igual ao objetivo 24 | # if num1 + num2 == target: 25 | # # Quando achar essa combinacao, retornar a posicao desses numeros 26 | # return [i,j] 27 | # # Big O notation 28 | # -> Solution: 29 | class Solution: 30 | def twoSum(self, nums: List[int], target: int) -> List[int]: 31 | # Time Complexity: O(nlogn) 32 | # Space Complexity: O(n) 33 | # Criaria um mapa 34 | seen = {} 35 | # Comecar a movimentar pela lista 36 | for pos, num in enumerate(nums): 37 | # Checar qual e o par deste numero 38 | pair = target - num 39 | # Checa se este par do numero atual ja foi visto 40 | if pair in seen: 41 | # Ja temos a resposta, retornar ambas posicoes 42 | return [seen[pair], pos] 43 | # No caso de nao ter visto, guardar informacao do numero atual 44 | else: 45 | seen[num] = pos 46 | -------------------------------------------------------------------------------- /leetcode/1 - twosum/two_sum.rs: -------------------------------------------------------------------------------- 1 | // Time complexity: O(N) - linear (tamanho do vetor) 2 | 3 | // Em rust a estrutura HashMap é implementada utilizando o conceito de Hash Table 4 | // Logo temos uma complexidade de O(1), constante, para inserção e obtenção dos dados. 5 | 6 | // OBS: qualquer dúvida sobre a implementação é só mandar uma msg que eu 7 | // explico/ajudo sem problema algum ;) 8 | 9 | impl Solution { 10 | pub fn two_sum(nums: Vec, target: i32) -> Vec { 11 | let mut storage = std::collections::HashMap::new(); 12 | 13 | for (index, num) in nums.into_iter().enumerate(){ 14 | let diff = target - num; 15 | 16 | match storage.get(&diff){ 17 | Some(&value) => return vec![index as i32, value as i32], 18 | None => {storage.insert(num, index);}, 19 | } 20 | } 21 | return unreachable!() 22 | } 23 | } -------------------------------------------------------------------------------- /leetcode/20 - validparenthesis/README.MD: -------------------------------------------------------------------------------- 1 | # Challenge Description 2 | 3 | [20 - Valid Parentheses](https://leetcode.com/problems/valid-parentheses/) | Difficulty: Easy 4 | 5 | ## Description: 6 | --- 7 | Given a string s containing just the characters `'(', ')', '{', '}', '[' and ']'`, determine if the input string is valid. 8 | 9 | An input string is valid if: 10 | 11 | 1. Open brackets must be closed by the same type of brackets. 12 | 2. Open brackets must be closed in the correct order. 13 | 14 | Example 1: 15 | 16 | ``` 17 | Input: s = "()" 18 | Output: true 19 | ``` 20 | Example 2: 21 | 22 | ``` 23 | Input: s = "()[]{}" 24 | Output: true 25 | ``` 26 | Example 3: 27 | 28 | ``` 29 | Input: s = "(]" 30 | Output: false 31 | ``` 32 | Example 4: 33 | 34 | ``` 35 | Input: s = "([)]" 36 | Output: false 37 | ``` 38 | Example 5: 39 | 40 | ``` 41 | Input: s = "{[]}" 42 | Output: true 43 | ``` 44 | 45 | **Constraints:** 46 | 47 | - 1 <= s.length <= 104 48 | - s consists of parentheses only '()[]{}'. 49 | 50 | -------------------------------------------------------------------------------- /leetcode/20 - validparenthesis/valid-parenthesis.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func isValid(s string) bool { 6 | // Cria uma pilha para guardar os valores 7 | stack := []rune{} 8 | // Nós precisamos de uma lista de pares, qual símbolo fecha qual 9 | symbols := map[rune]rune{ 10 | ')': '(', 11 | ']': '[', 12 | '}': '{', 13 | } 14 | // Vamos passar por cada simbolo, verificando se ele tem um que fecha, na ordem correta 15 | for _, caracter := range s { 16 | switch caracter { 17 | case '(', '{', '[': 18 | // Se o caracter for um símbolo de abertura, adicione ele ao stack 19 | stack = append(stack, caracter) 20 | case ')', '}', ']': 21 | // Se o caracter for um símbolo de fechamento, checar dois cases: 22 | // 1 - Se o Stack está vazio significa que estamos tentando começar fechando um par, retorne falso 23 | // 2 - Se o último símbolo do stack não é o par deste caracter atual, retorne falso 24 | if len(stack) == 0 || stack[len(stack)-1] != symbols[caracter] { 25 | return false 26 | } 27 | // Se não caiu no if check acima, remova o último item do stack (o par deste item) 28 | stack = stack[:len(stack)-1] 29 | } 30 | } 31 | // Após o loop se o stack estiver vazio, fechamos todos os pares. Se houver algum item no stack nós não fechamos esses caracteres 32 | return len(stack) == 0 33 | } 34 | 35 | func main() { 36 | fmt.Println(isValid("()[]{}")) // true 37 | fmt.Println(isValid("([)]")) // false 38 | } 39 | --------------------------------------------------------------------------------