├── June2018.md ├── README.md ├── challenges ├── 100Doors.md ├── AnagramStrings.md ├── AnagramStrings │ ├── AnagramStrings.md │ └── solution │ │ ├── AnagramStrings-DirectAddressingSolution.rb │ │ ├── AnagramStrings-HashtableBasedSolution.rb │ │ └── AngramStrings-UsinSorting.rb ├── ArrayIntersection │ ├── ArrayIntersection.md │ └── solution │ │ ├── ArrayIntersection-BruteForceSolution.rb │ │ ├── ArrayIntersection-UsingHashTables.rb │ │ └── ArrayIntersection-UsingSorting.rb ├── August2019.md ├── DeleteNodeInLinkedList │ ├── Readme.md │ └── solution │ │ └── DeleteNode.java ├── DetectCycle │ ├── Readme.md │ └── solution │ │ └── DetectCycle.java ├── EncodeRepeating │ ├── readme.md │ └── solutions │ │ └── encode_repeating.rb ├── February-2020.md ├── MergeSortedList │ ├── Readme.md │ └── solution │ │ └── MergeLists.java ├── NRepeated │ └── NRepeated.md ├── October2018.md ├── October2019.md ├── PalindromeCheck │ ├── readme.md │ └── solutions │ │ └── palindrome_check.rb ├── PalindromeLinkedList │ ├── Readme.md │ └── solution │ │ └── PalindromeList.java ├── Recursion │ ├── BinarySearchTree │ │ └── Search │ │ │ ├── Readme.md │ │ │ └── solution │ │ │ └── BSTSearch.java │ ├── BinaryTree │ │ ├── AllUniqueTrees │ │ │ └── Readme.md │ │ └── Height │ │ │ ├── Readme.md │ │ │ └── solution │ │ │ └── BTHeight.java │ ├── ClimbinStairs │ │ ├── Readme.md │ │ └── solution │ │ │ └── climbingsteps.java │ ├── Fibonacci │ │ ├── Readme.md │ │ └── solution │ │ │ └── fibonacci.java │ ├── KthSymbolInGrammar │ │ ├── Readme.md │ │ └── solution │ │ │ └── kthSymbolInGrammar.java │ ├── LinkedLists │ │ ├── MergeSortedLists │ │ │ ├── Readme.md │ │ │ └── solution │ │ │ │ └── MergeLists.java │ │ ├── Readme.md │ │ ├── Reverse │ │ │ ├── Readme.md │ │ │ └── solution │ │ │ │ └── LinkedListReverse.java │ │ └── SwapNodesInPairs │ │ │ ├── Readme.md │ │ │ └── solution │ │ │ └── SwapNodesInPairs.java │ ├── NthRowOfPascalsTriangle │ │ ├── Readme.md │ │ └── solution │ │ │ └── PascalsTriangleRow.java │ ├── PowerFunction │ │ ├── Readme.md │ │ └── solution │ │ │ └── RaisedToThePower.java │ ├── Readme.md │ └── ReverseString │ │ ├── Readme.md │ │ └── solution │ │ └── StringReverseRecursive.java ├── RemoveNthFromEnd │ ├── Readme.md │ └── solution │ │ └── RemoveNth.java ├── RepeatedTwice │ └── RepeatedTwice.md ├── ReverseLinkedList │ ├── Readme.md │ └── solution │ │ └── ReverseLinkedList.java ├── ReverseSentence │ ├── readme.md │ └── solutions │ │ └── reverse_sentence.rb ├── ReverseWords │ ├── readme.md │ └── solution │ │ └── reverse_words.rb ├── September2019.md ├── StringReverse │ ├── readme.md │ └── solutions │ │ └── StringReverseInPlace.rb ├── TwoSum │ └── TwoSum.md ├── compareTwoStrings.md ├── evenFibonacci.md ├── multiples3and5.md └── segregateArray.md └── past events ├── april2018.md ├── february2018.md ├── january2018.md ├── may2018.md └── new /June2018.md: -------------------------------------------------------------------------------- 1 | # June 19 2018 Algorithms Event 2 | 3 | ## Problems 4 | ### [Repeatify](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/repeatify/repeatify.md) 5 | ### [Bitonic Point](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/bitonicPoint/bitonicPoint.md) 6 | ### [Prime Sum](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/primeSum/primeSum.md) 7 | ### [Segregate Even and Odd Numbers](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/segregateEvenOdd/segregateEvenOdd.md) 8 | ### [Rotate Matrix](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/rotateMatrix/rotateMatrix.md) 9 | 10 | Some Women Who Code Reminders! 11 | * Everyone is welcome at our events - we just ask that you follow the [Code of Conduct](https://www.womenwhocode.com/codeofconduct) and support our mission. 12 | * [Twitter!](https://twitter.com/wwcboston) 13 | * [Women Who Code Mailing List](https://www.womenwhocode.com/) + [Job Board](https://www.womenwhocode.com/jobs) 14 | * SUBMIT NEW PROBLEMS! WE NEED YOUR HELP! 15 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # WomenWhoCode Boston Algorithms 2 | On April 16th, 2020, we'll be meeting for [online event](https://www.meetup.com/Women-Who-Code-Boston/events/269823017/) and discuss [Recursion](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/Recursion/Readme.md) 3 | 4 | The [Algorithms & Interview Prep introduction slide deck](https://docs.google.com/presentation/d/10cpdukUw5i4Keeoptkcs6loTWFG5vGY-1baweEeDZgs/edit?usp=sharing) 5 | 6 | Don't wait for the next meet up! Join the Conversation at bit.ly/wwcode-boston-slack 7 | 8 | This repository contains resources related to the monthly algorithms meetup. Here you can find all of the problems and (ongoing) solutions for Algorithms events. 9 | 10 | ## Contribute your favorite problems to this repo! 11 | Head to algorithms/challenges and `create new file` using .md 12 | 13 | ## Get a head start with whiteboarding problems 14 | - [Mock interview practice on Pramp](https://www.pramp.com/#/) 15 | - [LeetCode](https://leetcode.com/) 16 | - [HackerRank](https://www.hackerrank.com/) 17 | - [RosettaCode](http://rosettacode.org/wiki/Rosetta_Code) 18 | - [CodeWars](http://www.codewars.com/) 19 | - [Project Euler](https://projecteuler.net/) 20 | - [Coderbyte](http://coderbyte.com/) 21 | 22 | 23 | ## Learning to code? Resources to get started! 24 | - [Codecademy](http://codecademy.com) 25 | - [Codeschool](http://codeschool.com) 26 | - [FreeCodeCamp](http://www.freecodecamp.com/) 27 | - [CodeNewbie](http://www.codenewbie.org/) 28 | - [Khan Academy](https://www.khanacademy.org/computing) 29 | -------------------------------------------------------------------------------- /challenges/100Doors.md: -------------------------------------------------------------------------------- 1 | You have 100 doors in a row that are all initially closed. You make 100 passes by the doors. The first time through, you visit every door and toggle the door (if the door is closed, you open it; if it is open, you close it). The second time you only visit every 2nd door (door #2, #4, #6, ...). The third time, every 3rd door (door #3, #6, #9, ...), etc, until you only visit the 100th door. 2 | 3 | What state are the doors in after the last pass? Which are open, which are closed? 4 | 5 | ## Source 6 | http://rosettacode.org/wiki/100_doors 7 | -------------------------------------------------------------------------------- /challenges/AnagramStrings.md: -------------------------------------------------------------------------------- 1 | # String Anagrams 2 | 3 | ## Exercise 4 | * Design and implement a method to check if the two input parameter strings are anagrams of each other. 5 | The method should return `true` if the two input parameters are anagrams of each other. Otherwise, return `false`. 6 | * Explain the time and space complexity of your solution 7 | * Can you think of more than one solution? 8 | 9 | * Anagrams: Two strings are anagrams if you can rearrange the characters in one string to create the other string. e.g. "iceman" and "cinema". 10 | -------------------------------------------------------------------------------- /challenges/AnagramStrings/AnagramStrings.md: -------------------------------------------------------------------------------- 1 | # String Anagrams 2 | 3 | ## Exercise 4 | * Design and implement a method to check if the two input parameter strings are anagrams of each other. 5 | The method should return `true` if the two input parameters are anagrams of each other. Otherwise, return `false`. 6 | * Explain the time and space complexity of your solution 7 | * Can you think of more than one solution? 8 | 9 | * Anagrams: Two strings are anagrams if you can rearrange the characters in one string to create the other string. e.g. "iceman" and "cinema". 10 | -------------------------------------------------------------------------------- /challenges/AnagramStrings/solution/AnagramStrings-DirectAddressingSolution.rb: -------------------------------------------------------------------------------- 1 | # Approach 2: assuming the character set is ASCII extended set 2 | # that would limit the characters 256 possible values 3 | # Time complexity: O(n), where n is the number of characters in one of the strings 4 | # back to back loops, each running n times 5 | # Space complexity: O(n), where n is the number of characters in one of the strings 6 | # hash table space in the worst case scenario 7 | def string_anagrams(str1, str2) 8 | return false if str1 == nil || str2 == nil 9 | return false if str1.length != str2.length 10 | 11 | ascii_options = Array.new(256) 12 | 256.times do |i| 13 | ascii_options[i] = 0 14 | end 15 | 16 | str1.length.times do |i| 17 | ascii_options[str1[i].ord] += 1 18 | end 19 | 20 | str2.length.times do |i| 21 | ascii_options[str2[i].ord] -= 1 22 | return false if ascii_options[str2[i].ord] < 0 23 | end 24 | 25 | return true 26 | end 27 | -------------------------------------------------------------------------------- /challenges/AnagramStrings/solution/AnagramStrings-HashtableBasedSolution.rb: -------------------------------------------------------------------------------- 1 | # Approach 3: using hash tables 2 | # Time complexity: O(n), where n is the number of characters in one of the strings 3 | # back to back loops, each running n times 4 | # Space complexity: O(n), where n is the number of characters in one of the strings 5 | # hash table space in the worst case scenario 6 | def string_anagrams(str1, str2) 7 | return false if str1 == nil || str2 == nil 8 | return false if str1.length != str2.length 9 | 10 | Hash char_count = Hash.new() 11 | str1.length.times do |i| 12 | if !char_count[str1[i]] 13 | char_count[str1[i]] = 1 14 | else 15 | char_count[str1[i]] += 1 16 | end 17 | end 18 | 19 | str2.length.times do |i| 20 | if !char_count[str2[i]] || char_count[str2[i]] == 0 21 | return false 22 | end 23 | char_count[str2[i]] -= 1 24 | end 25 | 26 | return true 27 | end 28 | -------------------------------------------------------------------------------- /challenges/AnagramStrings/solution/AngramStrings-UsinSorting.rb: -------------------------------------------------------------------------------- 1 | # sort the characters in a string in-place 2 | # uses merge sort 3 | def sort(str) 4 | temp = str.dup 5 | mergesort(str, temp, 0, str.length-1) # invoke recursive merge sort 6 | end 7 | 8 | def mergesort(str, temp, low, high) 9 | return if low >= high 10 | 11 | mid = (low + high) / 2 12 | mergesort(str, temp, low, mid) 13 | mergesort(str, temp, mid+1, high) 14 | merge(low, mid, high, str, temp) 15 | end 16 | 17 | def merge(low, mid, high, str, temp) 18 | h = low 19 | i = low 20 | j = mid + 1 21 | 22 | while h <= mid && j <= high 23 | if str[h] <= str[j] 24 | temp[i] = str[h] 25 | h += 1 26 | else 27 | temp[i] = str[j] 28 | j += 1 29 | end 30 | i += 1 31 | end 32 | 33 | if h > mid 34 | k = j 35 | while k <= high 36 | temp[i] = str[k] 37 | i += 1 38 | k += 1 39 | end 40 | else 41 | k = h 42 | while k <= mid 43 | temp[i] = str[k] 44 | i += 1 45 | k += 1 46 | end 47 | end 48 | 49 | k = low 50 | while k <= high 51 | str[k] = temp[k] 52 | k += 1 53 | end 54 | end 55 | 56 | 57 | # A method to check if the two input strings are anagrams of each other 58 | # Returns true if the two input strings are anagrams of each other. 59 | # Returns false otherwise. 60 | 61 | # Approach 1: Sort, then compare 62 | # Time complexity: O(n log n) where n is the number of characters in any one of the input string 63 | # Space complexity: O(n) where n is the number of characters in any one of the input string 64 | # merge sort uses an additional space of the same size as the input. 65 | def string_anagrams(str1, str2) 66 | return false if str1 == nil || str2 == nil 67 | return false if str1.length != str2.length 68 | 69 | # sort the two strings 70 | sort(str1) 71 | sort(str2) 72 | # O(n log n) time complexity, where n is the number of characters 73 | 74 | str1.length.times do |i| 75 | return false if str1[i] != str2[i] 76 | end # O(n) time complexity, where n is the number of characters 77 | 78 | return true 79 | end 80 | -------------------------------------------------------------------------------- /challenges/ArrayIntersection/ArrayIntersection.md: -------------------------------------------------------------------------------- 1 | # Array Intersection 2 | Determine the intersection of two sets of input integer arrays. 3 | 4 | ## Exercise 5 | * Design and implement a method that takes two integer arrays and returns their intersection. The two input arrays have non repeating elements. The array returned should not have repeating elements. 6 | * Share and explain the time and space complexities for your solution in the comments above the method. 7 | * If the complexity is defined in terms of *n* and *m*, explain what *n* and *m* stand for. 8 | * If you think of multiple approaches to solve the problem, implement the solution which minimizes space complexity. Explain the other approaches, and your decision in comments above the code. 9 | 10 | * For example, 11 | - intersection of [2, 3, 4] and [4, 5, 6] is [4] 12 | - intersection of [50, 43, 25, 72] and [25, 36, 43, 50, 80] is [50, 25, 43] 13 | - intersection of [9, 30, 42] and [56, 34, 90, 32] is [] 14 | 15 | -------------------------------------------------------------------------------- /challenges/ArrayIntersection/solution/ArrayIntersection-BruteForceSolution.rb: -------------------------------------------------------------------------------- 1 | # Approach 1: brute force 2 | # Creates a new array to return the intersection of the two input arrays 3 | # Brute force approach 4 | # Time complexity: O(m*n) where array1 has m elements and array2 has n elements 5 | # Space complexity: O(n) if n < m since common_elements array gets created and 6 | # returned and at the most all elements will match. 7 | def intersection(array1, array2) 8 | common_elements = [] 9 | return common_elements if array1 == nil || array2 == nil 10 | 11 | array1.each do |number1| 12 | array2.each do |number2| 13 | if number1 == number2 14 | common_elements << number1 15 | break 16 | end 17 | end 18 | end 19 | 20 | return common_elements 21 | end 22 | -------------------------------------------------------------------------------- /challenges/ArrayIntersection/solution/ArrayIntersection-UsingHashTables.rb: -------------------------------------------------------------------------------- 1 | # Approach 3: Using hash tables 2 | # Time complexity: O(n+m) where array1 has m elements and array2 has n elements 3 | # Space complexity: O(n) if n < m since common_elements array gets created, as well 4 | # at the most n elements will get added to the hash table. 5 | def intersection(array1, array2) 6 | return [] if array1 == nil || array2 == nil 7 | 8 | if array1.length < array2.length 9 | larger = array2 10 | smaller = array1 11 | else 12 | larger = array1 13 | smaller = array2 14 | end 15 | 16 | my_hash = Hash.new() 17 | smaller.each do |num| 18 | my_hash[num] = 1 19 | end # O(n) space and O(n) time 20 | 21 | common_elements = [] 22 | larger.each do |num_1| 23 | # runs m times 24 | if my_hash.include? num_1 25 | # takes O(1) time 26 | common_elements << num_1 27 | end 28 | end 29 | 30 | # overall: O(n+m) time 31 | # overall: O(n) space 32 | return common_elements 33 | end 34 | -------------------------------------------------------------------------------- /challenges/ArrayIntersection/solution/ArrayIntersection-UsingSorting.rb: -------------------------------------------------------------------------------- 1 | # Approach 2: Using sorting approach 2 | # Helper method needed for the sorting approach below to find intersection 3 | def binary_search(array, value_to_find) 4 | return false if array.length == 0 5 | low = 0 6 | high = array.length-1 7 | while low < high 8 | mid = (high+low)/2 9 | if array[mid] == value_to_find 10 | return true 11 | elsif array[mid] > value_to_find 12 | high = mid-1 13 | elsif array[mid] < value_to_find 14 | low = mid+1 15 | end 16 | end 17 | 18 | return true if array[low] == value_to_find 19 | 20 | return false 21 | end 22 | 23 | # Leveraging sorting approach 24 | # Time complexity: O(m log m) + O(n log m) where array1 has m elements and array2 has n elements 25 | # Space complexity: O(n) if n < m since common_elements array gets created and 26 | # returned and at the most all elements will match. 27 | # Note: this approach has better time complexity than approach 1 (brute force) 28 | def intersection(array1, array2) 29 | return [] if array1 == nil || array2 == nil 30 | if array1.length < array2.length 31 | array2.sort! # O(m log m) time 32 | larger = array2 33 | smaller = array1 34 | else 35 | array1.sort! # O(m log m) time 36 | larger = array1 37 | smaller = array2 38 | end 39 | common_elements = [] 40 | smaller.each do |number1| 41 | # runs n times 42 | if binary_search(larger, number1) 43 | # takes log m time 44 | common_elements << number1 45 | end 46 | end # overall: O(n log m) 47 | return common_elements 48 | end 49 | -------------------------------------------------------------------------------- /challenges/August2019.md: -------------------------------------------------------------------------------- 1 | # August 15, 2019 2 | Theme: **Hash tables** 3 | 4 | ## Slides on Hash Tables 5 | From the event, here's the [slide deck on Hash Tables](https://docs.google.com/presentation/d/1pFtUeKQZjqFUXNeCSn8O1Rhw-jRaA21XjouirVre_0k/edit?usp=sharing) 6 | 7 | ## Interview knowledge questions 8 | Explain the following: 9 | - What is **direct addressing**? 10 | - How is a hash table implemented? 11 | - What is the time complexity and space complexity of creating a hash table to solve a problem? 12 | - When would the time complexity of a hash table closer to **linear** instead of **constant**? 13 | - In what scenarios would you use a hash table to solve a problem? 14 | - What is a **collison** in the context of a hash table? Explain one design approach used to deal with collisions. 15 | - In *, e.g. Java or Ruby*, what is/are language provided implementations of choice? If there are more than one, what are the differences between them? *(e.g. HashMap vs. HashSet in Java)* 16 | 17 | ## Interview coding problems: 18 | - [Array Intersection](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/ArrayIntersection/ArrayIntersection.md) 19 | - [Two Sum](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/TwoSum/TwoSum.md) 20 | - [Repeated Twice](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/RepeatedTwice/RepeatedTwice.md) 21 | - [Anagram Strings](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/AnagramStrings/AnagramStrings.md) 22 | - [N Repeated](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/NRepeated/NRepeated.md) 23 | 24 | 25 | ## WomenWhoCode Reminders & Links: 26 | * We hope you read and follow the [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 27 | * Join the [Boston Mailing List](https://mailchi.mp/0405d78baf97/wwcodeboston) 28 | * Follow us on [Twitter](https://twitter.com/wwcbos) 29 | 30 | -------------------------------------------------------------------------------- /challenges/DeleteNodeInLinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | # Delete a node in a singly linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that deletes a node from a singly linked list except if it is the tail of the linked list. 5 | * You have access only to the pointer/reference to the node to be deleted. 6 | * The method does not return anything 7 | 8 | ## Solution 9 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/DeleteNodeInLinkedList/solution 10 | 11 | ### Contribute 12 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 13 | 14 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/553/ 15 | -------------------------------------------------------------------------------- /challenges/DeleteNodeInLinkedList/solution/DeleteNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | 10 | class Solution { 11 | public void deleteNode(ListNode node) { 12 | // do not assume input - reverify constraints 13 | // if node is null, then it is the end of the linked list 14 | // if node.next is null, then node is the tail of the linked list 15 | if (node == null || node.next == null) { 16 | return; 17 | } 18 | 19 | while (node.next != null) { 20 | node.val = node.next.val; 21 | if (node.next.next == null) { 22 | node.next = null; 23 | break; 24 | } 25 | node = node.next; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /challenges/DetectCycle/Readme.md: -------------------------------------------------------------------------------- 1 | # Cycle in a singly linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that checks if there is a cycle in a singly linked list. 5 | * If the linked list does not terminate with null, there is a cycle in the linked list. 6 | * Return true if there is a cycle, and false if there isn't. 7 | 8 | ## Solution 9 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/DetectCycle/solution 10 | 11 | ### Contribute 12 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 13 | 14 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/773/ 15 | -------------------------------------------------------------------------------- /challenges/DetectCycle/solution/DetectCycle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { 7 | * val = x; 8 | * next = null; 9 | * } 10 | * } 11 | */ 12 | public class Solution { 13 | public boolean hasCycle(ListNode head) { 14 | if (head == null || head.next == null) { 15 | return false; 16 | } 17 | 18 | ListNode slow = head; 19 | ListNode fast = head.next; 20 | 21 | while (fast != null && slow != fast) { 22 | slow = slow.next; 23 | fast = fast.next; 24 | if (fast == null) { 25 | return false; 26 | } 27 | fast = fast.next; 28 | } 29 | 30 | if (slow == fast) { 31 | return true; 32 | } 33 | return false; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /challenges/EncodeRepeating/readme.md: -------------------------------------------------------------------------------- 1 | # Encode Repeating 2 | 3 | ## Exercise 4 | * Design and implement a method that updates the string by replacing consecutive repeating characters with a number representing the frequency. The replacement is done only if the string length will get reduced by the process. In addition to `.length`, you may use `.slice!` to implement this method. 5 | - e.g "*aaabbbbbcccc*" will get replaced to "*a3b5c4*", since *a* is repeated 3 times, *b* is repeated 5 times and *c* is repeated 4 times 6 | - "*xxxyttttgeee*" will get replaced with "*x3yt4ge3*". *y* and *g* do not get replaced by *y1* and *g1* since that will increase the length of the string. 7 | - "*ddbbfffgjjjj*" will get replaced with "*ddbbf3gj4*". *dd* and *bb* do not get replaced since the length will remain the same with *d2* and *b2*. *g* does not get replaced with *g1* since that will increase the length. 8 | * Share and explain the time and space complexities for your solution in the comments above the method. 9 | * If you define the complexities in terms of *n*, be sure to explain what *n* stands for. 10 | 11 | Further reading: Read further on [Run-length encoding (RLE)](https://en.wikipedia.org/wiki/Run-length_encoding), the simple form of loss-less data compression that this assignment is based on. 12 | -------------------------------------------------------------------------------- /challenges/EncodeRepeating/solutions/encode_repeating.rb: -------------------------------------------------------------------------------- 1 | # A method that updates the string by replacing consecutive repeating characters 2 | # with a number representing the frequency. The replacement is done only if the 3 | # string length will get reduced by the process. 4 | # Time complexity: O(n) where n is the number of characters in my_string 5 | # - O(2n) to examine if consecutive character, update character count and update characters if needed 6 | # - O(n-2) worst case to delete unneeded characters 7 | # Overall, O(n) time. 8 | # Space complexity: O(1) auxiliary storage used for indexing and keeping track of 9 | # current character remains constant as my_string size changes. 10 | def encode_repeating(my_string) 11 | # return if nil or empty 12 | return if (my_string == nil || my_string.length == 0) 13 | 14 | entering_index = 0 # this is where characters will get replaced 15 | examining_index = 0 # this is where the current character is getting examined and counted 16 | length = my_string.length 17 | while examining_index < length # all n characters will be examined 18 | temp = my_string[examining_index] # current character 19 | count = 1 # current character count 20 | while my_string[examining_index+1] == temp && examining_index < length 21 | examining_index += 1 # increment index 22 | count += 1 # increment current character count 23 | end 24 | # update at entering_index on seeing the subsequent character changing 25 | if count > 2 # enter the current character followed by it's count 26 | my_string[entering_index] = my_string[examining_index] 27 | entering_index += 1 28 | my_string[entering_index] = count.to_s 29 | entering_index += 1 30 | elsif count == 2 # enter the current character twice 31 | count.times do 32 | my_string[entering_index] = my_string[examining_index] 33 | entering_index += 1 34 | end 35 | else # count == 1, enter the current character once 36 | my_string[entering_index] = my_string[examining_index] 37 | entering_index += 1 38 | end 39 | examining_index += 1 # move to next character 40 | end 41 | 42 | # delete trailing characters in the string. 43 | count = length - entering_index 44 | count.times do # worst case: delete n-2 number of characters 45 | my_string.slice! entering_index # trim the string 46 | end 47 | return 48 | end 49 | -------------------------------------------------------------------------------- /challenges/February-2020.md: -------------------------------------------------------------------------------- 1 | # February 20, 2020 2 | Theme: **Linked Lists** 3 | 4 | ## Slides on "Linked List - quick revision" 5 | From the event, here's the [slide deck on a quick revision of linked list data structure](https://drive.google.com/file/d/1bEGgxFTixxhuEIvqfNrdpqxKhNGctKL-/view?usp=sharing) 6 | 7 | ## Interview knowledge questions 8 | These questions seek to judge your understanding of CS Fundamentals and of the primary programming language of your choice. 9 | 10 | Explain the following: 11 | - Compare an array and linked list data structure. When would you use one over the other? 12 | - What is the difference between a **pointer** and a **reference**? 13 | - What is a **memory Access Violation** or **AV**? 14 | - What is a **memory leak**? What's the harm with memory leaks? 15 | - Does *, e.g. Java or Ruby*, provide an implementation of LinkedList as part of the common library? 16 | - Does *, e.g. Java or Ruby*, have a garbage collector? How does the garbage collector work? 17 | 18 | ## Interview coding problems: 19 | Given a singly linked list 20 | - [Delete a node in the linked list (except if it is the tail). Return the head to the modified linked list.](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/DeleteNodeInLinkedList) 21 | - [Delete nth node from the end of a linked list. Return the head to the modified linked list](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/RemoveNthFromEnd) 22 | - [Reverse the linked list. Return the head to the modified linked list.](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/ReverseLinkedList) 23 | - [Merge two sorted lists. Return the head to the linked list.](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/MergeSortedList) 24 | - [Check if the linked list has values that form a palindrome. Return true if it does, no if it doesn't.](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/PalindromeLinkedList) 25 | - [Detect if the linked list has a cycle. Return true if it does, no if it doesn't.](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/DetectCycle) 26 | 27 | Given a singly linked list with integer values constrained to 1, 2 and 3. Sort the linked list so that all the nodes with value 1 come before the nodes with the value 2 and all nodes with the value 3 are in the end of the linked list. Return the head of the modified linked list. 28 | 29 | Given a singly linked list, detect if the linked list has a cycle and return the node at which the cycle begins. If there is no cycle, return null. 30 | 31 | Given a singly linked list, reverse every k set of nodes in the list. e.g. if the linked list was: 32 | (head)1 -> 4 -> 2 -> 3 -> 6 -> 9 -> 0 -> 5(tail) -> null 33 | and k= 3, then the linked list should get modified to: 34 | (head)2 -> 4 -> 1 -> 9 -> 6 -> 3 -> 5 -> 0(tail) -> null 35 | 36 | ## Additional Resources: 37 | - [Linked List by Vaidehi Joshi](https://medium.com/basecs/whats-a-linked-list-anyway-part-1-d8b7e6508b9d) 38 | 39 | ## WomenWhoCode Reminders & Links: 40 | * We hope you read and follow the [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 41 | * Don't wait until our next meetup! Join the Conversation at slack.wwcboston.org 42 | * Join the [Boston Mailing List](https://mailchi.mp/0405d78baf97/wwcodeboston) 43 | * Follow us on [Twitter](https://twitter.com/wwcbos) 44 | -------------------------------------------------------------------------------- /challenges/MergeSortedList/Readme.md: -------------------------------------------------------------------------------- 1 | # Merge two sorted linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that merges two sorted linked list based on the integer value in the nodes. 5 | * Both lists are made up of the same node definition. 6 | * Return the head of the merged linked list. 7 | 8 | ## Solution 9 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/MergeSortedList/solution 10 | 11 | ### Contribute 12 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 13 | 14 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/771/ 15 | -------------------------------------------------------------------------------- /challenges/MergeSortedList/solution/MergeLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 | if (l1 == null) { 12 | return l2; 13 | } else if (l2 == null) { 14 | return l1; 15 | } 16 | 17 | ListNode head = null; 18 | ListNode current = null; 19 | while (l1 != null && l2 != null) { 20 | if (l1.val <= l2.val) { 21 | if (current == null) { 22 | head = l1; 23 | current = head; 24 | } else { 25 | current.next = l1; 26 | current = current.next; 27 | } 28 | l1 = l1.next; 29 | } else { 30 | if (current == null) { 31 | head = l2; 32 | current = head; 33 | } else { 34 | current.next = l2; 35 | current = current.next; 36 | } 37 | l2 = l2.next; 38 | } 39 | } 40 | 41 | ListNode temp = null; 42 | if (l2 != null) { 43 | current.next = l2; 44 | } else if (l1 != null) { 45 | current.next = l1; 46 | } else { 47 | current.next = null; 48 | } 49 | 50 | return head; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /challenges/NRepeated/NRepeated.md: -------------------------------------------------------------------------------- 1 | ## N repeated 2 | An array of size 2N with N+1 distinct elements and one element repeated N times. 3 | 4 | ### Exercise 5 | A method takes an array of size 2N. There are N+1 unique elements and exactly one element is repeated N times. Design the algorithm for the method to return the element that is repeated N times. 6 | 7 | - What is the time and space complexity of your solution? 8 | - Can you think of a solution that optimizes for memory or space? 9 | - Can you think of a solution that optimizes for time? 10 | 11 | 12 | Example 1: 13 | Input: [1,2,3,3] 14 | Output: 3 15 | 16 | Example 2: 17 | Input: [2,1,2,5,3,2] 18 | Output: 2 19 | 20 | Example 3: 21 | Input: [5,1,5,2,5,3,5,4] 22 | Output: 5 23 | 24 | 25 | Note: 26 | 4 <= A.length <= 10000 27 | 0 <= A[i] < 10000 28 | A.length is even 29 | 30 | ### Source, trying out and for solutions 31 | https://leetcode.com/problems/n-repeated-element-in-size-2n-array/ 32 | -------------------------------------------------------------------------------- /challenges/October2018.md: -------------------------------------------------------------------------------- 1 | # October 17 2018 2 | ### [Letter Capitalize](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/letterCapitalize/letterCapitalize.md) 3 | ### [Binary Search](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/binarySearch/binarySearch.md) 4 | ### [Self-Describing Numbers ](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/selfDescribingNumbers/selfDescribingNumbers.md) 5 | ### [Anagram Detection](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/anagramDetection/anagramDetection.md) 6 | ### [Longest Range](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/longestRange/longestRange.md) 7 | 8 | WomenWhoCode Reminders & Links: 9 | * We hope you read and follow the [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 10 | * Join the [Boston Mailing List](https://mailchi.mp/0405d78baf97/wwcodeboston) 11 | * Follow us on [Twitter](https://twitter.com/wwcbos) 12 | -------------------------------------------------------------------------------- /challenges/October2019.md: -------------------------------------------------------------------------------- 1 | # October 10, 2019 2 | Theme: **Linked Lists** 3 | 4 | ## Slides on "Linked List - quick revision" 5 | From the event, here's the [slide deck on a quick revision of linked list data structure](https://drive.google.com/file/d/1bEGgxFTixxhuEIvqfNrdpqxKhNGctKL-/view?usp=sharing) 6 | 7 | ## Interview knowledge questions 8 | These questions seek to judge your understanding of CS Fundamentals and of the primary programming language of your choice. 9 | 10 | Explain the following: 11 | - Compare an array and linked list data structure. When would you use one over the other? 12 | - What is the difference between a **pointer** and a **reference**? 13 | - What is a **memory Access Violation** or **AV**? 14 | - What is a **memory leak**? What's the harm with memory leaks? 15 | - Does *, e.g. Java or Ruby*, provide an implementation of LinkedList as part of the common library? 16 | - Does *, e.g. Java or Ruby*, have a garbage collector? How does the garbage collector work? 17 | 18 | ## Interview coding problems: 19 | https://www.geeksforgeeks.org/top-20-linked-list-interview-question/ 20 | 21 | ## Additional Resources: 22 | - [Linked List by Vaidehi Joshi](https://medium.com/basecs/whats-a-linked-list-anyway-part-1-d8b7e6508b9d) 23 | 24 | ## WomenWhoCode Reminders & Links: 25 | * We hope you read and follow the [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 26 | * Don't wait until our next meetup! Join the Conversation at slack.wwcboston.org 27 | * Join the [Boston Mailing List](https://mailchi.mp/0405d78baf97/wwcodeboston) 28 | * Follow us on [Twitter](https://twitter.com/wwcbos) 29 | -------------------------------------------------------------------------------- /challenges/PalindromeCheck/readme.md: -------------------------------------------------------------------------------- 1 | # Palindrome Check 2 | 3 | ## Exercise 4 | * Design and implement a method that checks if the input string is a palindrome. The method should return true, if the input string is a palindrome and return false, if it is not a palindrome. 5 | * Do not alter the input string. 6 | * Find a solution that optimizes the space complexity as much as possible. In other words, check if your algorithm can avoid duplicating the original string. 7 | * Share and explain the time and space complexities for your solution in the comments above the method. 8 | * If you describe the complexity in terms of *n*, be sure to explain what *n* stands for. 9 | * Palindrome is a word, phrase or sentence that reads the same backwards as it does forwards. e.g. "madam" 10 | * For this exercise purposes, white spaces are ignored while checking for a palindrome string. 11 | 12 | Notes: 13 | - You may retrieve a character at a given index, or update a character at a given index using any available approach. 14 | -------------------------------------------------------------------------------- /challenges/PalindromeCheck/solutions/palindrome_check.rb: -------------------------------------------------------------------------------- 1 | # A method to check if the input string is a palindrome. 2 | # Return true if the string is a palindrome. Return false otherwise. 3 | # Time complexity: O(n) where n is the length of my_phrase. 4 | # Each character in the string which is a white space will be examined once. 5 | # (nested inner loop). 6 | # Each character in the string which is not a white space will be examined twice. 7 | # (first to compare with white space, 8 | # next to compare with another non-white space character for equality.) 9 | # Space complexity: O(1) - auxiliary storage (i and j to hold index values) 10 | # takes constant space as input size changes. 11 | def palindrome_check(my_phrase) 12 | # return false if nil - not a string 13 | return false if my_phrase == nil 14 | 15 | # return true if empty - reads the same forwards and backwards 16 | return true if my_phrase.length == 0 17 | 18 | i = 0 # index of the first character in my_phrase 19 | j = my_phrase.length - 1 # index of the last character in my_phrase 20 | while i < j 21 | # account for ignoring white spaces 22 | while i < j && my_phrase[i] == ' ' 23 | i += 1 24 | end 25 | while i < j && my_phrase[j] == ' ' 26 | j -= 1 27 | end 28 | 29 | if i >= j # check if there is more characters after accounting for white spaces 30 | break # accounted for all characters in my_phrase 31 | end 32 | 33 | if my_phrase[i] != my_phrase[j] # palindrome check 34 | return false 35 | end 36 | i += 1 37 | j -= 1 38 | end 39 | 40 | return true # assumes that a string with one character is a palindrome. 41 | end 42 | -------------------------------------------------------------------------------- /challenges/PalindromeLinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | # Palindrome Linked List 2 | 3 | ## Exercise 4 | * Design and implement a method that checks if the integer values in a singly linked list form a Palindrome 5 | 6 | ## Solution 7 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/PalindromeLinkedList/solution 8 | 9 | ### Contribute 10 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 11 | 12 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/772/ 13 | -------------------------------------------------------------------------------- /challenges/PalindromeLinkedList/solution/PalindromeList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public boolean isPalindrome(ListNode head) { 11 | if (head == null || head.next == null) { 12 | return true; 13 | } 14 | 15 | // find the middle 16 | ListNode fast = head; 17 | ListNode slow = head; 18 | while (fast.next != null) { 19 | fast = fast.next; 20 | if (fast.next == null) { 21 | break; 22 | } 23 | fast = fast.next; 24 | slow = slow.next; 25 | } 26 | 27 | // reverse the second half 28 | ListNode mid = slow; 29 | ListNode previous = slow; 30 | ListNode current = slow.next; 31 | while (current != null) { 32 | ListNode temp = current.next; 33 | current.next = previous; 34 | previous = current; 35 | current = temp; 36 | } 37 | ListNode last = previous; 38 | 39 | // verify palindrome 40 | boolean pal = true; 41 | current = head; 42 | ListNode reverse = last; 43 | while (reverse != current && reverse != mid) { 44 | if (reverse.val != current.val) { 45 | pal = false; 46 | break; 47 | } 48 | reverse = reverse.next; 49 | current = current.next; 50 | } 51 | 52 | // re-reverse the second half 53 | previous = null; 54 | current = last; 55 | while (current != slow) { 56 | ListNode temp = current.next; 57 | current.next = previous; 58 | previous = current; 59 | current = temp; 60 | } 61 | 62 | return pal; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /challenges/Recursion/BinarySearchTree/Search/Readme.md: -------------------------------------------------------------------------------- 1 | # Search in a Binary Search Tree 2 | 3 | ## Exercise 4 | * Given a Binary Seach Tree's root node and a given value, return the node in the binary search tree which contains the same value as the given value. Return `null` if the given value is not found in the BST. 5 | 6 | ## Solution 7 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/BinarySeachTree/Search/solution 8 | 9 | ### Contribute 10 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 11 | 12 | The above problem is borrowed from: https://leetcode.com/explore/featured/card/recursion-i/251/scenario-i-recurrence-relation/3233/ 13 | -------------------------------------------------------------------------------- /challenges/Recursion/BinarySearchTree/Search/solution/BSTSearch.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public TreeNode searchBST(TreeNode root, int val) { 12 | if (root == null) { 13 | return null; // base case for not found 14 | } 15 | 16 | if (root.val == val) { 17 | return root; // base case for found 18 | } 19 | 20 | if (root.val > val) { 21 | return searchBST(root.left, val); // recursive call - value is less than value at root 22 | } 23 | 24 | return searchBST(root.right, val); // recursive call - value is greater than value at root 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /challenges/Recursion/BinaryTree/AllUniqueTrees/Readme.md: -------------------------------------------------------------------------------- 1 | # All unique trees with n values 2 | 3 | ## Exercise 4 | * Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n. 5 | * e.g. given 2 6 | ``` 7 | 2 1 1 2 8 | / / \ \ 9 | 1 2 2 1 10 | ``` 11 | 12 | ``` 13 | ``` 14 | 15 | 19 | 20 | ### Contribute 21 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 22 | 23 | The above problem is borrowed from: https://leetcode.com/problems/fibonacci-number/ 24 | -------------------------------------------------------------------------------- /challenges/Recursion/BinaryTree/Height/Readme.md: -------------------------------------------------------------------------------- 1 | # Binary Tree - height or depth (maximum) 2 | 3 | ## Exercise 4 | * Given a binary tree, author a method that recursively computes the maximum depth of the Binary Tree 5 | 6 | ## Solution 7 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/BinaryTree/Height/solution 8 | 9 | ### Contribute 10 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 11 | 12 | The above problem is borrowed from: https://leetcode.com/problems/maximum-depth-of-binary-tree/ 13 | 14 | -------------------------------------------------------------------------------- /challenges/Recursion/BinaryTree/Height/solution/BTHeight.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for a binary tree node. 3 | * public class TreeNode { 4 | * int val; 5 | * TreeNode left; 6 | * TreeNode right; 7 | * TreeNode(int x) { val = x; } 8 | * } 9 | */ 10 | class Solution { 11 | public int maxDepth(TreeNode root) { 12 | if (root == null) { 13 | return 0; // base case 14 | } 15 | 16 | int leftHeight = maxDepth(root.left); // recursive case 17 | int rightHeight = maxDepth(root.right); // recursive case 18 | if (leftHeight > rightHeight) { 19 | return leftHeight + 1; 20 | } else { 21 | return rightHeight + 1; 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /challenges/Recursion/ClimbinStairs/Readme.md: -------------------------------------------------------------------------------- 1 | # climbing stairs - distinct way 2 | 3 | ## Exercise 4 | * You are climbing a stair case. It takes n steps to reach to the top. 5 | * Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? 6 | * Note: Given n will be a positive integer. 7 | * e.g. 8 | ``` 9 | Input: 3 10 | Output: 3 11 | Explanation: There are three ways to climb to the top. 12 | 1. 1 step + 1 step + 1 step 13 | 2. 1 step + 2 steps 14 | 3. 2 steps + 1 step 15 | ``` 16 | 17 | ## Solution 18 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/ClimbStairs/solution 19 | 20 | ### Contribute 21 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 22 | 23 | The above problem is borrowed from: https://leetcode.com/problems/climbing-stairs/ 24 | 25 | -------------------------------------------------------------------------------- /challenges/Recursion/ClimbinStairs/solution/climbingsteps.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | // using memoization - cache 3 | HashMap cache = new HashMap(); 4 | 5 | public int climbStairs(int n) { 6 | // check in cache 7 | if (cache.containsKey(n)) { 8 | return cache.get(n); 9 | } 10 | 11 | int result; 12 | if (n <= 2) { 13 | result = n; // base case 14 | } else { 15 | result = climbStairs(n-1) + climbStairs(n-2); // recursive case 16 | } 17 | 18 | cache.put(n, result); // save in cache before return 19 | return result; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /challenges/Recursion/Fibonacci/Readme.md: -------------------------------------------------------------------------------- 1 | # nth number in Fibonacci series 2 | 3 | ## Exercise 4 | * Design and author a recursive solution to return the nth number in the Fibonacco series. 5 | * Assume that the 0th number is 0, 1st number is 1, and the nth number greater than 1 is defined as: 6 | nth Fibonacci number = (n-1)th Fibonacci number + (n-2)th Fibonacci number 7 | 8 | ## Solution 9 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/Fibonacci/solution 10 | 11 | ### Contribute 12 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 13 | 14 | The above problem is borrowed from: https://leetcode.com/problems/fibonacci-number/ 15 | 16 | -------------------------------------------------------------------------------- /challenges/Recursion/Fibonacci/solution/fibonacci.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | HashMap cache = new HashMap(); 3 | 4 | public int fib(int N) { 5 | // using memoization, check cache first 6 | if (cache.containsKey(N)) { 7 | return cache.get(N); 8 | } 9 | 10 | // not in cache 11 | int result; 12 | if (N <= 1) { 13 | result = N; // base case 14 | } else { 15 | result = fib(N-1) + fib(N-2); // recurrence case 16 | } 17 | 18 | // save in cache 19 | cache.put(N, result); 20 | return result; 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /challenges/Recursion/KthSymbolInGrammar/Readme.md: -------------------------------------------------------------------------------- 1 | # kth symbol in grammar 2 | 3 | ## Exercise 4 | * Design and author a method that returns the kth symbol in the nth row per the following rules 5 | * On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. 6 | * Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). 7 | * Note: N will be an integer in the range [1, 30]. 8 | * Note: K will be an integer in the range [1, 2^(N-1)]. 9 | ``` 10 | row 1: 0 11 | row 2: 01 12 | row 3: 0110 13 | row 4: 01101001 14 | ``` 15 | * e.g. N=4, K=5 should return 1 16 | 17 | ## Solution 18 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/KthSymbolInGrammar/solution 19 | 20 | ### Contribute 21 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 22 | 23 | The above problem is borrowed from: https://leetcode.com/problems/k-th-symbol-in-grammar/ 24 | 25 | -------------------------------------------------------------------------------- /challenges/Recursion/KthSymbolInGrammar/solution/kthSymbolInGrammar.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public int kthGrammar(int N, int K) { 3 | if (K == 1) { 4 | return 0; 5 | } 6 | 7 | if (K % 2 == 0) { 8 | return 1- kthGrammar(N-1, K/2); 9 | } 10 | 11 | return kthGrammar(N-1, (K+1)/2); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/MergeSortedLists/Readme.md: -------------------------------------------------------------------------------- 1 | # Merge two sorted linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that merges two sorted linked list based on the integer value in the nodes. 5 | * Both lists are made up of the same node definition. 6 | * Return the head of the merged linked list. 7 | 8 | ## Solution 9 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/LinkedLists/MergeSortedLists/solution 10 | 11 | ### Contribute 12 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 13 | 14 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/771/ 15 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/MergeSortedLists/solution/MergeLists.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode mergeTwoLists(ListNode l1, ListNode l2) { 11 | if (l1 == null) { 12 | return l2; 13 | } else if (l2 == null) { 14 | return l1; 15 | } 16 | 17 | ListNode head = null; 18 | ListNode current = null; 19 | while (l1 != null && l2 != null) { 20 | if (l1.val <= l2.val) { 21 | if (current == null) { 22 | head = l1; 23 | current = head; 24 | } else { 25 | current.next = l1; 26 | current = current.next; 27 | } 28 | l1 = l1.next; 29 | } else { 30 | if (current == null) { 31 | head = l2; 32 | current = head; 33 | } else { 34 | current.next = l2; 35 | current = current.next; 36 | } 37 | l2 = l2.next; 38 | } 39 | } 40 | 41 | ListNode temp = null; 42 | if (l2 != null) { 43 | current.next = l2; 44 | } else if (l1 != null) { 45 | current.next = l1; 46 | } else { 47 | current.next = null; 48 | } 49 | 50 | return head; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/Readme.md: -------------------------------------------------------------------------------- 1 | A lot of problems involving Linked Lists can be solved but iteratively as well as Recursively. 2 | 3 | If you are still new to Linked Lists, you may benefit from revising the basics and first attempting the solutions iteratively. 4 | The iterative approaches for some common Linked List callenges may be found on https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 5 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/Reverse/Readme.md: -------------------------------------------------------------------------------- 1 | # Reverse a singly linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that reverses a singly linked list using recursive approach. 5 | 6 | ## Solution 7 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/LinkedLists/Reverse/solution 8 | 9 | ### Contribute 10 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 11 | 12 | The above problem is borrowed from: https://leetcode.com/explore/featured/card/recursion-i/251/scenario-i-recurrence-relation/2378/ 13 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/Reverse/solution/LinkedListReverse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode reverseList(ListNode head) { 11 | // recursive approach 12 | 13 | // base case 14 | if (head == null || head.next == null) { 15 | return head; 16 | } 17 | 18 | // recursive call - reverse everything after head 19 | ListNode newHead = reverseList(head.next); 20 | // add head to the end 21 | head.next.next = head; 22 | // ensure the linked list ends after head which is now added to the end 23 | head.next = null; 24 | // return the new head 25 | return newHead; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/SwapNodesInPairs/Readme.md: -------------------------------------------------------------------------------- 1 | # Swap Alternate Pairs 2 | 3 | ## Exercise 4 | * Design and implement a method that swaps alternate nodes in a singly linked list. 5 | e.g. If the input is 6 | `1->2->3->4 ` 7 | then after the method is executed, the linked list should become 8 | `2->1->4->3` 9 | 10 | ## Solution 11 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/LinkedLists/SwapNodesInPairs/solution 12 | 13 | ### Contribute 14 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 15 | 16 | The above problem is borrowed from: https://leetcode.com/explore/featured/card/recursion-i/250/principle-of-recursion/1681/ 17 | -------------------------------------------------------------------------------- /challenges/Recursion/LinkedLists/SwapNodesInPairs/solution/SwapNodesInPairs.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | 10 | class Solution { 11 | public ListNode swapPairs(ListNode head) { 12 | if (head == null || head.next == null) { 13 | // base case 14 | return head; // if only one node (not a pair), or no nodes, then return 15 | } 16 | 17 | // recursive case 18 | ListNode returnNode = head.next; // the second node needs to be returned 19 | ListNode temp = returnNode.next; // recursively call the method on this node 20 | returnNode.next = head; // do the current pair swap 21 | head.next = swapPairs(temp); // recursive case 22 | return returnNode; // this is not a tail recursion 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /challenges/Recursion/NthRowOfPascalsTriangle/Readme.md: -------------------------------------------------------------------------------- 1 | # nth row of Pascal's Triangle 2 | 3 | ## Exercise 4 | * Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. 5 | * Note that the row index starts from 0. e.g. k = 2 should return `[1, 2, 1]` 6 | * Pascal's triangle: 7 | ``` 8 | 1 9 | 1 1 10 | 1 2 1 11 | 1 3 3 1 12 | 1 4 6 4 1 13 | 1 5 10 10 5 1 14 | ``` 15 | 16 | ## Solution 17 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/NthRowOfPascalsTriangle/solution 18 | 19 | ### Contribute 20 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 21 | 22 | The above problem is borrowed from: https://leetcode.com/problems/pascals-triangle-ii/ 23 | 24 | -------------------------------------------------------------------------------- /challenges/Recursion/NthRowOfPascalsTriangle/solution/PascalsTriangleRow.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public List getRow(int rowIndex) { 3 | if (rowIndex < 0) { 4 | return null; 5 | } 6 | 7 | List newRow = new ArrayList(); 8 | newRow.add(1); 9 | if (rowIndex == 0) { 10 | return newRow; 11 | } 12 | 13 | return getRow(newRow, 0, rowIndex); 14 | } 15 | 16 | private List getRow(List currentRow, int currentIndex, int rowIndex) { 17 | List newRow = new ArrayList(); 18 | newRow.add(1); 19 | 20 | 21 | for (int i = 0; i < currentRow.size()-1; i++) { 22 | newRow.add(currentRow.get(i) + currentRow.get(i+1)); 23 | } 24 | 25 | newRow.add(1); 26 | 27 | if (currentIndex+1 == rowIndex) { 28 | // base case 29 | return newRow; 30 | } 31 | 32 | return getRow(newRow, currentIndex+1, rowIndex); // recursive case 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /challenges/Recursion/PowerFunction/Readme.md: -------------------------------------------------------------------------------- 1 | # Binary Tree - height or depth (maximum) 2 | 3 | ## Exercise 4 | * Implement pow(x, n), which calculates x raised to the power n (i.e. x^n). 5 | * Note: -100.0 < x < 100.0 6 | * Note: n is a 32-bit signed integer, within the range [−231, 231 − 1] 7 | 8 | ## Solution 9 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/PowerFunction/solution 10 | 11 | ### Contribute 12 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 13 | 14 | The above problem is borrowed from: https://leetcode.com/problems/powx-n/ 15 | 16 | -------------------------------------------------------------------------------- /challenges/Recursion/PowerFunction/solution/RaisedToThePower.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public double myPow(double x, int n) { 3 | if (n == 0) { 4 | return 1; // base case 5 | } 6 | 7 | if (n == 1) { 8 | return x; // base case 9 | } 10 | 11 | if (n == -1) { 12 | return 1/x; 13 | } 14 | 15 | // memoization 16 | double computedValue = myPow(x, n/2); 17 | 18 | if (n % 2 == 0) { // power is divisible by 2 19 | return computedValue * computedValue; 20 | } 21 | 22 | if (n > 0) { // power is positive 23 | return x * computedValue * computedValue; 24 | } 25 | 26 | // power is negative, so invert x 27 | return 1/x * computedValue * computedValue; 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /challenges/Recursion/Readme.md: -------------------------------------------------------------------------------- 1 | A lot of the problems that can be solved recursively can also be solved iteratively. Here's the slide deck we used on April 2nd, 2020 to revise some basics building up to Recursion: [Recursion Revision](https://docs.google.com/presentation/d/1QxR9pX8UZpJQTiKsfwJxNwFSQ653mqfkZxgWuMkiA1o/edit?usp=sharing) 2 | 3 | If you're still new to recursion, we recommend these links from GeeksForGeeks.org to internalize the working of recursive methods before designing methods: 4 | * [Set 1: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion/) 5 | * [Set 2: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion-set-2/) 6 | * [Set 3: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion-set-3/) 7 | * [Set 4: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion-set-4/) 8 | * [Set 5: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion-set-5/) 9 | * [Set 6: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion-set-6/) 10 | * [Set 7: Practice question for Recursion](http://www.geeksforgeeks.org/practice-questions-for-recursion-set-7/) 11 | 12 | 13 | In the set of problems listed in this section, please attempt to solve the problems **recursively**. 14 | 1. Design and implement a method that reverses a string. The input string is given as an array of characters char[]. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. e.g. if the input is ['a', 'b', 'c'] then the method should change the input array to ['c', 'b', 'a']. For more details, see [Recursive - String Reverse](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/ReverseString) 15 | 16 | 2. Design and author a recursive solution to return the nth number in the Fibonacco series. Assume that the 0th number is 0, 1st number is 1, and the nth number greater than 1 is defined as: nth Fibonacci number = (n-1)th Fibonacci number + (n-2)th Fibonacci number. For more details, see [Recursive - Fibonacci](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/Fibonacci) 17 | 18 | 3. 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? Design a function that takes as input the count of steps, n and returns the distinct number of ways the steps can be climbed. Note: Given n will be a positive integer. For more details see [Climbing stairs - distinct ways](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/ClimbinStairs) 19 | 20 | 4. Design and author a method that returns the kth symbol in the nth row per the following rules. On the first row, we write a 0. Now in every subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and each occurrence of 1 with 10. Given row N and index K, return the K-th indexed symbol in row N. (The values of K are 1-indexed.) (1 indexed). N will be an integer in the range [1, 30]. K will be an integer in the range [1, 2^(N-1)]. For more details see [Kth symbol in grammar](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/KthSymbolInGrammar) 21 | 22 | 5. Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle. Note that the row index starts from 0. e.g. k = 2 should return [1, 2, 1] 23 | Pascal's triangle: 24 | ``` 25 | 1 26 | 1 1 27 | 1 2 1 28 | 1 3 3 1 29 | 1 4 6 4 1 30 | 1 5 10 10 5 1 31 | ``` 32 | For more details see [nth row of Pascal's Triangle](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/NthRowOfPascalsTriangle) 33 | 34 | 6. Design and implement a method that merges two sorted linked list based on the integer value in the nodes. Return the head of the merged linked list. For more details see [Linked List: merge two sorted linked list](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/LinkedLists/MergeSortedLists) 35 | 36 | 7. Design and implement a method that reverses a singly linked list using recursive approach. For more details see [Linked List: reverse](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/LinkedLists/Reverse) 37 | 38 | 8. Design and implement a method that swaps alternate nodes in a singly linked list. e.g. If the input is `1->2->3->4` then after the method is executed, the linked list should become `2->1->4->3`. For more details see [Linked List: swap alernate pairs](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/LinkedLists/SwapNodesInPairs) 39 | 40 | 9. Given a binary tree, author a method that recursively computes the maximum depth of the Binary Tree. For more details, see [Binary Tree - max depth](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/BinaryTree/Height) 41 | 42 | 10. Given a Binary Seach Tree's root node and a given value, return the node in the binary search tree which contains the same value as the given value. Return null if the given value is not found in the BST. For more details, see [Binary Search Tree - Search](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/BinarySearchTree/Search) 43 | 44 | The above problems have been borrowed from and can be practiced on: [LeetCode: Principles of Recursion](https://leetcode.com/explore/featured/card/recursion-i/250/principle-of-recursion/) 45 | -------------------------------------------------------------------------------- /challenges/Recursion/ReverseString/Readme.md: -------------------------------------------------------------------------------- 1 | # String Reverse Recursive 2 | 3 | ## Exercise 4 | * Design and implement a method that reverses a string. The input string is given as an array of characters char[]. 5 | * Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. 6 | 7 | ## Solution 8 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/Recursion/ReverseString/solution 9 | 10 | ### Contribute 11 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 12 | 13 | The above problem is borrowed from: https://leetcode.com/explore/featured/card/recursion-i/250/principle-of-recursion/1440/ 14 | 15 | -------------------------------------------------------------------------------- /challenges/Recursion/ReverseString/solution/StringReverseRecursive.java: -------------------------------------------------------------------------------- 1 | class Solution { 2 | public void reverseString(char[] s) { 3 | if (s == null) { 4 | return; // check input 5 | } 6 | 7 | recursiveHelper(s.length, 0, s); // call a recursive helper method 8 | return; 9 | } 10 | 11 | private void recursiveHelper(int sLength, int currentIndex, char[] s) { 12 | int swapIndex = sLength - currentIndex - 1; 13 | if (currentIndex >= swapIndex) { 14 | // base case 15 | return; 16 | } 17 | 18 | // swap the element at currentIndex 19 | char temp = s[currentIndex]; 20 | s[currentIndex] = s[swapIndex]; 21 | s[swapIndex] = temp; 22 | 23 | // recursive call 24 | recursiveHelper(sLength, currentIndex+1, s); 25 | return; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /challenges/RemoveNthFromEnd/Readme.md: -------------------------------------------------------------------------------- 1 | # Remove nth node from a singly linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that removed the nth node from the end of the linked list. 5 | * The method should return the head of the modified linked list. 6 | 7 | ## Solution 8 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/RemoveNthFromEnd/solution 9 | 10 | ### Contribute 11 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 12 | 13 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/603/ 14 | -------------------------------------------------------------------------------- /challenges/RemoveNthFromEnd/solution/RemoveNth.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | class Solution { 10 | public ListNode removeNthFromEnd(ListNode head, int n) { 11 | if (head == null) { 12 | return head; // empty linked list provided 13 | } 14 | 15 | ListNode forward = head; 16 | while (forward != null && n > 1) { 17 | forward = forward.next; 18 | n--; 19 | } 20 | 21 | if (forward == null) { 22 | return head; // less nodes in linked list then n 23 | } 24 | 25 | if (forward.next == null) { 26 | // delete the head node 27 | return head.next; 28 | } 29 | 30 | ListNode backward = head; 31 | while (forward.next.next != null) { 32 | backward = backward.next; 33 | forward = forward.next; 34 | } 35 | backward.next = backward.next.next; 36 | return head; 37 | 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /challenges/RepeatedTwice/RepeatedTwice.md: -------------------------------------------------------------------------------- 1 | # Reated Twice 2 | Determine the element repeated twice in an unsorted array. 3 | 4 | ## Exercise 5 | * An unsorted array has all unique elements except one. Design an algorithm/method to find the repeating element. 6 | * Share and explain the time and space complexities for your solution in the comments above the method. 7 | * If you think of multiple approaches to solve the problem, implement the solution which minimizes space complexity. Explain the other approaches, and your decision in comments above the code. 8 | 9 | * For example, 10 | - [35, 42, 7, 10, -18, 42, 63] should return 42. 11 | - [8, 3, 2, 1, 1, 9, 4] should return 1. 12 | - [9, 9] should return 9. 13 | 14 | -------------------------------------------------------------------------------- /challenges/ReverseLinkedList/Readme.md: -------------------------------------------------------------------------------- 1 | # Reverse a singly linked list 2 | 3 | ## Exercise 4 | * Design and implement a method that reverses the nodes in a singly linked list. 5 | * Return the head of the modified linked list 6 | 7 | ## Solution 8 | https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/ReverseLinkedList/solution 9 | 10 | ### Contribute 11 | Add your own interview questions, or solutions to existing problem: https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges 12 | 13 | The above problem is borrowed from: https://leetcode.com/explore/interview/card/top-interview-questions-easy/93/linked-list/560/ 14 | -------------------------------------------------------------------------------- /challenges/ReverseLinkedList/solution/ReverseLinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Definition for singly-linked list. 3 | * public class ListNode { 4 | * int val; 5 | * ListNode next; 6 | * ListNode(int x) { val = x; } 7 | * } 8 | */ 9 | 10 | class Solution { 11 | public ListNode reverseList(ListNode head) { 12 | ListNode previous = null; 13 | ListNode current = head; 14 | while (current != null) { 15 | ListNode temp = current.next; 16 | current.next = previous; 17 | previous = current; 18 | current = temp; 19 | } 20 | head = previous; 21 | 22 | return head; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /challenges/ReverseSentence/readme.md: -------------------------------------------------------------------------------- 1 | # Reverse Sentence 2 | 3 | ## Exercise 4 | * Design and implement a method to reverse the words in a sentence *in place*. The string of words to be reversed in passed in as the input parameter to the method. 5 | * Your algorithm should strive to optimize the space complexity as much as possible. 6 | * For example, if the method is called with input parameter of "Yoda   is    awesome", then the method should update the input string object to have the value "awesome    is   Yoda". 7 | * Note that the count of white spaces between words is preserved. 8 | * Share and explain the time and space complexities for your solution in the comments above the method. 9 | * If the complexity is shared in terms of *n*, your explanation must explain what *n* stands for. 10 | 11 | **Notes**: 12 | * Do not use language provided functionality for `.reverse` and `.reverse!`. 13 | * You may use `.length` method provided in the language's standard libraries. 14 | * If you choose to code in a language in which Strings are not mutable, return a new string with each word in the input string reversed. 15 | 16 | -------------------------------------------------------------------------------- /challenges/ReverseSentence/solutions/reverse_sentence.rb: -------------------------------------------------------------------------------- 1 | # Helper method for partial string reversal 2 | # Reverses the character from start_index to end_index 3 | def partial_reverse(my_string, start_index, end_index) 4 | i = start_index 5 | j = end_index 6 | while i < j 7 | temp = my_string[i] # swap using temporary variable 8 | my_string[i] = my_string[j] 9 | my_string[j] = temp 10 | i += 1 11 | j -= 1 12 | end 13 | return 14 | end 15 | 16 | # Helper method: A method to reverse each word in a sentence, in place. 17 | # Time complexity: O(n) where n is the length of my_words 18 | # - Each character in my_words gets scanned once to find the beginning and end of 19 | # a word. For this, the characters are compared to the white space, and character 20 | # count is tracked. This takes O(n) time. 21 | # - Once the beginning and end for a word is deduced, partial_reverse is called. 22 | # partial_reverse reverses each word and takes O(k) time if there are k characters 23 | # in the word. At the most n characters will get reversed. So, this takes O(n) time. 24 | # - Overall, each character gets visited twice, taking O(2n) time or O(n) time. 25 | # Space complexity: O(1) - the auxiliary storage size does not increase as the 26 | # input length increases. 27 | def reverse_words(my_words) 28 | # return if nil or empty 29 | return if (my_words == nil || my_words.length == 0) 30 | 31 | i = 0 32 | length = my_words.length 33 | while i < length # until end of input 34 | while my_words[i] == ' ' && i < length # accounting for preceeding spaces 35 | i += 1 36 | end 37 | start_index = i # start of word identified 38 | 39 | while my_words[i] != ' ' && i < length # looking for end of word 40 | i += 1 41 | end 42 | end_index = i - 1 # word ends before the white space or at length-1 43 | 44 | partial_reverse(my_words, start_index, end_index) # reverse the word 45 | end 46 | return 47 | end 48 | 49 | # A method to reverse the words in a sentence, in place. 50 | # Time complexity: O(n) where n is the number of characters in my_sentence 51 | # - O(n) time to reverse all characters in the sentence. ("Let's go" becomes "og s'teL") 52 | # - O(2n) time to reverse words in the sentence. ("og s'teL" becomes "go Let's") 53 | # - Overall, O(3n) or simplified to O(n) 54 | # Space complexity: O(1) - auxiliary storage used does not depend on input 55 | def reverse_sentence(my_sentence) 56 | # return if nil or empty 57 | return if (my_sentence == nil || my_sentence.length == 0) 58 | start_index = 0 59 | end_index = my_sentence.length - 1 60 | # reverse all characters in my_sentence 61 | partial_reverse(my_sentence, start_index, end_index) 62 | 63 | # reverse each word in my_sentence 64 | reverse_words(my_sentence) 65 | end 66 | -------------------------------------------------------------------------------- /challenges/ReverseWords/readme.md: -------------------------------------------------------------------------------- 1 | # Reverse words 2 | 3 | ## Exercise 4 | * Design and implement a method to reverse each word in a sentence in place. The sentence to reverse is passed in as the input parameter to the function. Design your algorithm to optimize the space complexity to be as minimal as possible. 5 | * For example, if the method is called with input parameter of "I can be an   engineer", the method should update the input string object to have the value "I nac eb na   reenigne". 6 | * Note that the count of white spaces between words is preserved. 7 | * Share and explain the time and space complexities for your solution in the comment above the method. 8 | * If the complexity is described in terms of *n*, your explanation must share what *n* stands for. 9 | 10 | **Notes**: 11 | * Do not use language provided functionality for `.reverse` and `.reverse!`. 12 | * You may use `.length` method provided in the language's standard libraries. 13 | * If you choose to code in a language in which Strings are not mutable, return a new string with each word in the input string reversed. 14 | -------------------------------------------------------------------------------- /challenges/ReverseWords/solution/reverse_words.rb: -------------------------------------------------------------------------------- 1 | # Helper method to reverse a word. 2 | # Characters between start_index to end_index (both 3 | # inclusive) form a word. 4 | # Reverses the characters from start_index to end_index. 5 | def partial_reverse(my_string, start_index, end_index) 6 | i = start_index 7 | j = end_index 8 | while i < j 9 | temp = my_string[i] # swap using temporary variable 10 | my_string[i] = my_string[j] 11 | my_string[j] = temp 12 | i += 1 13 | j -= 1 14 | end 15 | return 16 | end 17 | 18 | # A method to reverse each word in a sentence, in place. 19 | # Time complexity: O(n), where n is the length of the input string, my_words 20 | # - Each character in my_words gets scanned once to find the beginning and end of 21 | # a word. To deduce the beginning and end of a word, the characters are compared 22 | # to the white space, and character count is tracked. This takes O(n) time. 23 | # - Once the beginning and end for a word is deduced, partial_reverse is called. 24 | # partial_reverse reverses each word and takes O(k) time if there are k characters 25 | # in the word. At the most n characters will get reversed. So, this takes O(n) time. 26 | # - Overall, each character gets visited twice, taking O(2n) time or O(n) time. 27 | # Space complexity: O(1) - the auxiliary storage size does not increase as the 28 | # input length increases. 29 | def reverse_words(my_words) 30 | return if (my_words == nil || my_words.length == 0) 31 | 32 | i = 0 33 | length = my_words.length 34 | while i < length # until end of input 35 | while my_words[i] == ' ' && i < length # accounting for preceeding spaces 36 | i += 1 37 | end 38 | start_index = i # start of word identified 39 | 40 | while my_words[i] != ' ' && i < length # looking for end of word 41 | i += 1 42 | end 43 | end_index = i - 1 # word ends before the white space or at length-1 44 | 45 | partial_reverse(my_words, start_index, end_index) # reverse the word 46 | end 47 | 48 | return 49 | # since the string manipulation is done in-place, 50 | # there's no need to return the string 51 | end 52 | -------------------------------------------------------------------------------- /challenges/September2019.md: -------------------------------------------------------------------------------- 1 | # September 12, 2019 2 | Theme: **String manipulation** 3 | 4 | ## Slides on "A quick revision of Computer Memory" 5 | From the event, here's the [slide deck on a quick revision of computer memory](https://drive.google.com/open?id=16_OoNkO9w0Eiw-ReOf7cc5YSAd4yBlPR) 6 | 7 | ## Interview knowledge questions 8 | These questions seek to judge your understanding of CS Fundamentals and of the primary programming language of your choice. 9 | 10 | Explain the following: 11 | - What is the difference between a **pointer** and a **reference**? 12 | - What is a **memory Access Violation** or **AV**? 13 | - What is a **memory leak**? What's the harm with memory leaks? 14 | - In *, e.g. Java or Ruby*, are Strings mutable? 15 | - Does *, e.g. Java or Ruby*, have a garbage collector? How does the garbage collector work? 16 | 17 | ## Interview coding problems: 18 | - [Reverse a string](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/StringReverse) 19 | - [Reverse each word in the string](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/ReverseWords) 20 | - [Reverse a sentence](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/ReverseSentence) 21 | - [Palindrome check](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/PalindromeCheck) 22 | - [Anagram Strings](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/AnagramStrings/AnagramStrings.md) 23 | - [Encode a string](https://github.com/WomenWhoCodeBoston/algorithms/tree/master/challenges/EncodeRepeating) 24 | 25 | ## Additional Resources: 26 | - [Bits, Bytes, Building with Memory by Vaidehi Joshi](https://medium.com/basecs/bits-bytes-building-with-binary-13cb4289aafa) 27 | - [Video on Memory in Computer Systems by Prof Abelardo Pardo](https://www.youtube.com/watch?v=F0Ri2TpRBBg) 28 | 29 | ## WomenWhoCode Reminders & Links: 30 | * We hope you read and follow the [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 31 | * Don't wait until our next meetup! Join the Conversation at slack.wwcboston.org 32 | * Join the [Boston Mailing List](https://mailchi.mp/0405d78baf97/wwcodeboston) 33 | * Follow us on [Twitter](https://twitter.com/wwcbos) 34 | -------------------------------------------------------------------------------- /challenges/StringReverse/readme.md: -------------------------------------------------------------------------------- 1 | # String Reverse 2 | 3 | ## Exercise 4 | * Design and implement a method to reverse a string *in place*. The method takes the string to be reversed as input parameter. 5 | * Above the method, elaborate the comment to share the time and space complexity of your method. 6 | * Your solution should optimize the space complexity as much as possible. In other words, do not use any more space than needed. 7 | * If you explain the complexity in terms of *n*, be sure to explain what *n* stands for. 8 | * For example, if the method is called with input parameter of "*Lovelace*", the method should update the input string object to have the value "*ecalevoL*". 9 | 10 | **Notes**: 11 | * Do not use language provided functionality for `.reverse` and `.reverse!`. 12 | * You may use `.length` method provided in the language's standard libraries. 13 | * If you choose to code in a language in which Strings are not mutable, return a new string with each word in the input string reversed. 14 | 15 | -------------------------------------------------------------------------------- /challenges/StringReverse/solutions/StringReverseInPlace.rb: -------------------------------------------------------------------------------- 1 | # A method to reverse a string in place. 2 | # Time complexity: O(n) where n is the length of the string. 3 | # The while loop will run n/2 times. 4 | # Space complexity: O(1) i and j are auxiliary storages used. 5 | # Auxiliary storage takes constant space as input string size changes. 6 | def string_reverse(my_string) 7 | # return if nil or empty 8 | return if my_string == nil || my_string.length == 0 9 | 10 | i = 0 # initialized to index of first character 11 | j = my_string.length - 1 # initialized to index of the last character 12 | while i < j 13 | temp = my_string[i] # swap using temporary variable 14 | my_string[i] = my_string[j] 15 | my_string[j] = temp 16 | i += 1 17 | j -= 1 18 | end 19 | return # reversal is done in place and hence no new object is returned 20 | end 21 | -------------------------------------------------------------------------------- /challenges/TwoSum/TwoSum.md: -------------------------------------------------------------------------------- 1 | ### Two Sum 2 | 3 | Design a method that takes an array of positive integers and returns the indices of the two distinct values in the array that sum up to a specific target value. 4 | 5 | **Notes**: 6 | - You may assume that each input would have exactly one solution. 7 | - Can you think of at least two solutions/algorithms to solve the problem: one that is space efficient and another that is time efficient? 8 | 9 | **Example**: 10 | If the inputs to the method are: array: [2, 7, 11, 15], target = 9, then the method should return [0, 1] because array[0] and array[1] i.e. 2 and 7 sum up to the target value of 9. 11 | 12 | **Add on challenge**: Extend your solution so that it returns **all pairs** of indices that solve the problem. 13 | 14 | **Source, practice & compare solutions at**: https://leetcode.com/problems/two-sum/ 15 | -------------------------------------------------------------------------------- /challenges/compareTwoStrings.md: -------------------------------------------------------------------------------- 1 | ## Compare two strings represented as linked lists 2 | 3 | The following problem is taken from [geeksforgeeks.org](http://www.geeksforgeeks.org/compare-two-strings-represented-as-linked-lists/). NB: the link contains solution. We recommend you to try this yourself first. 4 | 5 | Given two linked lists, represented as linked lists (every character is a node in linked lists), write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are same, 1 if first linked list is lexicographically greater, and -1 if second string is lexicographically greater. 6 | 7 | Lexicographic order means that the words are arranged in a similar fashion as they are presumed to appear in a dictionary. For example, the word 'cat' will appear before the word 'dog' in a dictionary, so a < b, b < e, d > a, etc. 8 | 9 | Examples: 10 | 11 | Input: 12 | list1 = g->e->e->k->s 13 | list2 = g->e->e->k->s 14 | Output: 0 15 | 16 | Input: 17 | list1 = g->e->e->k->s->a 18 | list2 = g->e->e->k->s 19 | Output: 1 20 | 21 | Input: 22 | list1 = g->e->e->k->s->a 23 | list2 = g->e->e->k->s->b 24 | Output: -1 25 | 26 | submitted by https://github.com/ayunav 27 | -------------------------------------------------------------------------------- /challenges/evenFibonacci.md: -------------------------------------------------------------------------------- 1 | ## Even Fibonacci numbers 2 | 3 | Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 4 | 5 | 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... 6 | 7 | By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. 8 | 9 | ## Source 10 | [Project Euler](https://projecteuler.net/problem=2) 11 | -------------------------------------------------------------------------------- /challenges/multiples3and5.md: -------------------------------------------------------------------------------- 1 | If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. 2 | 3 | Find the sum of all the multiples of 3 or 5 below 1000. 4 | 5 | ## Source 6 | [Project Euler](https://projecteuler.net/problem=1) 7 | -------------------------------------------------------------------------------- /challenges/segregateArray.md: -------------------------------------------------------------------------------- 1 | ## Segregate 0s and 1s in an array 2 | You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Traverse array only once. 3 | 4 | Input array = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] 5 | Output array = [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] 6 | 7 | ## Source 8 | NB: the link contains solution. We recommend you to try this first :) 9 | [Geeks for Geeks](https://www.geeksforgeeks.org/segregate-0s-and-1s-in-an-array-by-traversing-array-once/) 10 | -------------------------------------------------------------------------------- /past events/april2018.md: -------------------------------------------------------------------------------- 1 | # April 10 2018 Algorithms - hosted by Pivotal Labs 2 | 3 | ### [Range](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/range/range.md) 4 | ### [Reverse Sublist](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/reverseSublist/reverseSublist.md) 5 | ### [Rock Paper Scissors](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/rockPaperScissors/rockPaperScissors.md) 6 | ### [Roman Numerals](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/roman-numerals/roman-numerals.md) 7 | ### [Selection Sort](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/selectionSort/selectionSort.md) 8 | 9 | 10 | Random reminders 11 | - We're a supportive group with a [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 12 | - Did you like this event? Volunteer for future events with WomenWhoCode Boston! It's easy and we're pretty nice. Talk to a volunteer or lead at any WWCode event you attend. 13 | - Follow us on [Twitter](https://twitter.com/wwcboston) 14 | -------------------------------------------------------------------------------- /past events/february2018.md: -------------------------------------------------------------------------------- 1 | # February 13 2018 Algorithms Meetup! 2 | 3 | ### [TR (translate/transliterate)](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/tr/tr.md) 4 | ### [The Sieve of Eratosthenes](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/sieveOfEratosthenes/sieveOfEratosthenes.md) 5 | ### [latticePaths](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/latticePaths/latticePaths.md) 6 | ### [Anagram Detection](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/anagramDetection/anagramDetection.md) 7 | ### [SumPairs](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/sumPairs/sumPairs.md) 8 | 9 | -------------------------------------------------------------------------------- /past events/january2018.md: -------------------------------------------------------------------------------- 1 | # January 9 2018 Algorithms Meetup 2 | 3 | This first batch of problems comes from our dear friends at WomenWhoCode NYC. 4 | 5 | ### [Investment](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/investment/investment.md) 6 | ### [Insertion Sort](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/insertionSort/insertionSort.md) 7 | ### [Hamming Distance](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/hammingDistance/hammingDistance.md) 8 | ### [kth To Last Element](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/kthToLastElement/kthToLastElement.md) 9 | ### [Largest Palindromic Number](https://github.com/WomenWhoCodeNYC/Algorithms/blob/master/challenges/largestPalindromicNumber/largest_palindromic_number.md) 10 | -------------------------------------------------------------------------------- /past events/may2018.md: -------------------------------------------------------------------------------- 1 | # May 8 2018 Algorithms event 2 | 3 | ## Problems 4 | ### [100Doors](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/100Doors.md) 5 | ### [Multiples of 3 and 5](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/multiples3and5.md) 6 | ### [Even Fibonacci Numbers](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/evenFibonacci.md) 7 | ### [Segregate 0s and 1s in an Array](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/segregateArray.md) 8 | ### [Compare two strings represented as linked lists](https://github.com/WomenWhoCodeBoston/algorithms/blob/master/challenges/compareTwoStrings.md) 9 | 10 | ## Reminders 11 | - We're a supportive group with a [Code of Conduct](https://www.womenwhocode.com/codeofconduct) 12 | - Did you like this event? Volunteer for future events with WomenWhoCode Boston! Talk to a volunteer or lead at any WWCode event you attend. 13 | - Follow us on [Twitter](https://twitter.com/wwcboston) 14 | -------------------------------------------------------------------------------- /past events/new: -------------------------------------------------------------------------------- 1 | 2 | --------------------------------------------------------------------------------