Code Monkey home page Code Monkey logo

interactive-coding-challenges's Introduction


interactive-coding-challenges

Binder

120+ continually updated, interactive, and test-driven coding challenges, with Anki flashcards.

Challenges focus on algorithms and data structures found in coding interviews.

Each challenge has one or more reference solutions that are:

  • Fully functional
  • Unit tested
  • Easy-to-understand

Challenges will soon provide on-demand incremental hints to help you arrive at the optimal solution.

Notebooks also detail:

  • Constraints
  • Test cases
  • Algorithms
  • Big-O time and space complexities

Also included are unit tested reference implementations of various data structures and algorithms.

Challenge Solutions



Anki Flashcards: Coding and Design


The provided Anki flashcard deck uses spaced repetition to help you retain key concepts.

Great for use while on-the-go.

Design Resource: The System Design Primer

Looking for resources to help you prep for the System Design and Object-Oriented Design interviews?


Check out the sister repo The System Design Primer, which contains additional Anki decks:

Notebook Structure

Each challenge has two notebooks, a challenge notebook with unit tests for you to solve and a solution notebook for reference.

Problem Statement

  • States the problem to solve.

Constraints

  • Describes any constraints or assumptions.

Test Cases

  • Describes the general and edge test cases that will be evaluated in the unit test.

Algorithm

  • [Challenge Notebook] Empty, refer to the solution notebook algorithm section if you need a hint.
  • [Solution Notebook] One or more algorithm solution discussions, with Big-O time and space complexities.

Hints

  • [Challenge Notebook] Provides on-demand incremental hints to help you arrive at the optimal solution. Coming soon!

Code (Challenge: Implement Me!)

  • [Challenge Notebook] Skeleton code for you to implement.
  • [Solution Notebook] One or more reference solutions.

Unit Test

  • [Challenge Notebook] Unit test for your code. Expected to fail until you solve the challenge.
  • [Solution Notebook] Unit test for the reference solution(s).

Index

Challenges Categories

Format: Challenge Category - Number of Challenges

Total number of challenges: 120

Reference Implementations: Data Structures

Unit tested, fully functional implementations of the following data structures:

Reference Implementations: Algorithms

Unit tested, fully functional implementations of the following algorithms:

Reference Implementations: TODO

Installing and Running Challenges

Misc

Challenges

Image Credits



Arrays and Strings

Binder

Challenge Static Notebook
Determine if a string contains unique characters ChallengeSolution
Determine if a string is a permutation of another ChallengeSolution
Determine if a string is a rotation of another ChallengeSolution
Compress a string ChallengeSolution
Reverse characters in a string ChallengeSolution
Given two strings, find the single different char ChallengeSolution
Find two indices that sum to a specific value ChallengeSolution
Implement a hash table ChallengeSolution
Implement fizz buzz ChallengeSolution
Find the first non-repeated character in a string ContributeContribute
Remove specified characters in a string ContributeContribute
Reverse words in a string ContributeContribute
Convert a string to an integer ContributeContribute
Convert an integer to a string ContributeContribute
Add a challenge ContributeContribute


Linked Lists

Binder

Challenge Static Notebook
Remove duplicates from a linked list ChallengeSolution
Find the kth to last element of a linked list ChallengeSolution
Delete a node in the middle of a linked list ChallengeSolution
Partition a linked list around a given value ChallengeSolution
Add two numbers whose digits are stored in a linked list ChallengeSolution
Find the start of a linked list loop ChallengeSolution
Determine if a linked list is a palindrome ChallengeSolution
Implement a linked list ChallengeSolution
Determine if a list is cyclic or acyclic ContributeContribute
Add a challenge ContributeContribute


Stacks and Queues

Binder

Challenge Static Notebook
Implement n stacks using a single array ChallengeSolution
Implement a stack that keeps track of its minimum element ChallengeSolution
Implement a set of stacks class that wraps a list of capacity-bounded stacks ChallengeSolution
Implement a queue using two stacks ChallengeSolution
Sort a stack using another stack as a buffer ChallengeSolution
Implement a stack ChallengeSolution
Implement a queue ChallengeSolution
Implement a priority queue backed by an array ChallengeSolution
Add a challenge ContributeContribute


Graphs and Trees

Binder

Challenge Static Notebooks
Implement depth-first search (pre-, in-, post-order) on a tree ChallengeSolution
Implement breadth-first search on a tree ChallengeSolution
Determine the height of a tree ChallengeSolution
Create a binary search tree with minimal height from a sorted array ChallengeSolution
Create a linked list for each level of a binary tree ChallengeSolution
Check if a binary tree is balanced ChallengeSolution
Determine if a tree is a valid binary search tree ChallengeSolution
Find the in-order successor of a given node in a binary search tree ChallengeSolution
Find the second largest node in a binary search tree ChallengeSolution
Find the lowest common ancestor ChallengeSolution
Invert a binary tree ChallengeSolution
Implement a binary search tree ChallengeSolution
Implement a min heap ChallengeSolution
Implement a trie ChallengeSolution
Implement depth-first search on a graph ChallengeSolution
Implement breadth-first search on a graph ChallengeSolution
Determine if there is a path between two nodes in a graph ChallengeSolution
Implement a graph ChallengeSolution
Find a build order given a list of projects and dependencies. ChallengeSolution
Find the shortest path in a weighted graph. ChallengeSolution
Find the shortest path in an unweighted graph. ChallengeSolution
Add a challenge ContributeContribute


Sorting

Binder

Challenge Static Notebooks
Implement selection sort ChallengeSolution
Implement insertion sort ChallengeSolution
Implement quick sort ChallengeSolution
Implement merge sort ChallengeSolution
Implement radix sort ChallengeSolution
Sort an array of strings so all anagrams are next to each other ChallengeSolution
Find an item in a sorted, rotated array ChallengeSolution
Search a sorted matrix for an item ChallengeSolution
Find an int not in an input of n integers ChallengeSolution
Given sorted arrays A, B, merge B into A in sorted order ChallengeSolution
Implement a stable selection sort ContributeContribute
Make an unstable sort stable ContributeContribute
Implement an efficient, in-place version of quicksort ContributeContribute
Given two sorted arrays, merge one into the other in sorted order ContributeContribute
Find an element in a rotated and sorted array of integers ContributeContribute
Add a challenge ContributeContribute


Recursion and Dynamic Programming

Binder

Challenge Static Notebooks
Implement fibonacci recursively, dynamically, and iteratively ChallengeSolution
Maximize items placed in a knapsack ChallengeSolution
Maximize unbounded items placed in a knapsack ChallengeSolution
Find the longest common subsequence ChallengeSolution
Find the longest increasing subsequence ChallengeSolution
Minimize the cost of matrix multiplication ChallengeSolution
Maximize stock prices given k transactions ChallengeSolution
Find the minimum number of ways to represent n cents given an array of coins ChallengeSolution
Find the unique number of ways to represent n cents given an array of coins ChallengeSolution
Print all valid combinations of n-pairs of parentheses ChallengeSolution
Navigate a maze ChallengeSolution
Print all subsets of a set ChallengeSolution
Print all permutations of a string ChallengeSolution
Find the magic index in an array ChallengeSolution
Find the number of ways to run up n steps ChallengeSolution
Implement the Towers of Hanoi with 3 towers and N disks ChallengeSolution
Implement factorial recursively, dynamically, and iteratively ContributeContribute
Perform a binary search on a sorted array of integers ContributeContribute
Print all combinations of a string ContributeContribute
Implement a paint fill function ContributeContribute
Find all permutations to represent n cents, given 1, 5, 10, 25 cent coins ContributeContribute
Add a challenge ContributeContribute


Mathematics and Probability

Binder

Challenge Static Notebooks
Generate a list of primes ChallengeSolution
Find the digital root ChallengeSolution
Create a class supporting insert, max, min, mean, mode in O(1) ChallengeSolution
Determine if a number is a power of two ChallengeSolution
Add two numbers without the + or - sign ChallengeSolution
Subtract two numbers without the + or - sign ChallengeSolution
Check if a number is prime ContributeContribute
Determine if two lines on a Cartesian plane intersect ContributeContribute
Using only add, implement multiply, subtract, and divide for ints ContributeContribute
Find the kth number such that the only prime factors are 3, 5, and 7 ContributeContribute
Add a challenge ContributeContribute


Bit Manipulation

Binder

Challenge Static Notebooks
Implement common bit manipulation operations ChallengeSolution
Determine number of bits to flip to convert a into b ChallengeSolution
Draw a line on a screen ChallengeSolution
Flip a bit to maximize the longest sequence of 1s ChallengeSolution
Get the next largest and next smallest numbers ChallengeSolution
Merge two binary numbers ChallengeSolution
Swap odd and even bits in an integer ChallengeSolution
Print the binary representation of a number between 0 and 1 ChallengeSolution
Determine the number of 1s in the binary representation of a given integer ContributeContribute
Add a challenge ContributeContribute


Online Judges

Binder

Challenge Static Notebooks
Find the longest substring with at most k distinct chars ChallengeSolution
Find the highest product of three numbers ChallengeSolution
Maximize stocks profit from 1 buy and 1 sell ChallengeSolution
Move all zeroes in a list to the end ChallengeSolution
Find the products of every other int ChallengeSolution
Given a list of entries and exits, find the busiest period ChallengeSolution
Determine an island's perimeter ChallengeSolution
Format license keys ChallengeSolution
Find the longest absolute file path ChallengeSolution
Merge tuple ranges ChallengeSolution
Assign cookies ChallengeSolution
Determine if you can win in Nim ChallengeSolution
Check if a magazine could have been used to create a ransom note ChallengeSolution
Find the number of times a sentence can fit on a screen ChallengeSolution
Utopian tree ChallengeSolution
Maximizing xor ChallengeSolution
Add a challenge ContributeContribute

Repo Structure

interactive-coding-challenges        # Repo
├─ arrays_strings                    # Category of challenges
│  ├─ rotation                       # Challenge folder
│  │  ├─ rotation_challenge.ipynb    # Challenge notebook
│  │  ├─ rotation_solution.ipynb     # Solution notebook
│  │  ├─ test_rotation.py            # Unit test*
│  ├─ compress
│  │  ├─ compress_challenge.ipynb
│  │  ├─ compress_solution.ipynb
│  │  ├─ test_compress.py
│  ├─ ...
├─ linked_lists
│  ├─ palindrome
│  │  └─ ...
│  ├─ ...
├─ ...

*The notebooks (.ipynb) read/write the associated unit test (.py) file.

Notebook Installation

Zero Install

Binder

This README contains links to Binder , which hosts dynamic notebooks of the repo's contents online with no installation needed.

Jupyter Notebook

Run:

pip install jupyter

For detailed instructions, scripts, and tools to more optimally set up your development environment, check out the dev-setup repo.

For more details on notebook installation, follow the directions here.

More information on IPython/Jupyter Notebooks can be found here.

Running Challenges

Notebooks

Challenges are provided in the form of IPython/Jupyter Notebooks and have been tested with Python 2.7 and Python 3.x.

If you need to install IPython/Jupyter Notebook, see the Notebook Installation section.

  • This README contains links to nbviewer, which hosts static notebooks of the repo's contents
  • To interact with or to modify elements within the dynamic notebooks, refer to the instructions below

Run the notebook of challenges:

$ git clone https://github.com/donnemartin/interactive-coding-challenges.git
$ cd interactive-coding-challenges
$ jupyter notebook

This will launch your web browser with the list of challenge categories:

  • Navigate to the Challenge Notebook you wish to solve
  • Run the cells within the challenge notebook (Cell->Run All)
    • This will result in an expected unit test error
  • Solve the challenge and verify it passes the unit test
  • Check out the accompanying Solution Notebook for further discussion

To debug your solution with pdb, refer to the following ticket.

Note: If your solution is different from those listed in the Solution Notebook, consider submitting a pull request so others can benefit from your work. Review the Contributing Guidelines for details.

Future Development

Challenges, solutions, and unit tests are presented in the form of IPython/Jupyter Notebooks.

  • Notebooks currently contain mostly Python solutions (tested on both Python 2.7 and Python 3.x), but can be extended to include 40+ supported languages
  • Repo will be continually updated with new solutions and challenges
  • Contributions are welcome!

Contributing

Contributions are welcome!

Review the Contributing Guidelines for details on how to:

  • Submit issues
  • Add solutions to existing challenges
  • Add new challenges

Credits

Resources

Images

Contact Info

Feel free to contact me to discuss any issues, questions, or comments.

My contact info can be found on my GitHub page.

License

I am providing code and resources in this repository to you under an open source license. Because this is my personal repository, the license you receive to my code and resources is from me and not my employer (Facebook).

Copyright 2015 Donne Martin

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

interactive-coding-challenges's People

Contributors

ammarnajjar avatar datavistics avatar delirious-lettuce avatar donnemartin avatar goalong avatar hanzhizheng avatar hashhar avatar jaysonfrancis avatar johnrieth avatar jstnlef avatar justinmusgrove avatar kagemusha avatar kevin-george avatar kishanbagaria avatar laharah avatar mag6367 avatar rafadaguiar avatar rajatppn avatar rockybutler avatar rrajasek95 avatar ryan-mcbride avatar superxiao avatar tahir24434 avatar tayre avatar varunu28 avatar wchargin avatar wdonahoe avatar yangshun avatar yask123 avatar z123 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

interactive-coding-challenges's Issues

SQL questions

Are there any plans for SQL or numpy df questions (or any sort of query)?
In software engineering interviews for data infra or science teams, I've been asked these.

I would like to start contributing some common ones I've faced if this repository aligns with these type of questions as well.

Bug in trie solution?

in the delete method of graphs_trees/trie/trie_solution.ipynb:

while parent is not None:
# As we are propagating the delete up the
# parents, if this node has children, stop
# here to prevent orphaning its children.
# Or
# if this node is a terminating node that is
# not the terminating node of the input word,
# stop to prevent removing the associated word.
if node.children or node.terminates:
return
del parent.children[node.key]
node = parent
parent = parent.parent

When you traverse from child to parent, the parent will always at least contain one child. Thus the parent.children[node.key] will never be deleted.

Arrays_Strings compress challenge tests inconsistent

In the chellenge compress there are tests:

assert_equal(func(None), None)
        assert_equal(func(''), '')
        assert_equal(func('AABBCC'), 'AABBCC')
        assert_equal(func('AAABCCDDDDE'), 'A3BC2D4E')
        assert_equal(func('BAAACCDDDD'), 'BA3C2D4')
        assert_equal(func('AAABAACCDDDD'), 'A3BA2C2D4')

The question states compress only if saves space but while a test is not changing the 2 consecutive letters as seen:

assert_equal(func('AABBCC'), 'AABBCC')

While the other exemples such as this one:

assert_equal(func('AAABCCDDDDE'), 'A3BC2D4E')

compresses it.

If this is not intended and if I'm not terribly wrong 😄 then some of the tests must be changed.

I would kindly offer my help to change them and open a PR if you would kindly point which ones need change (again if I'm correct)

compress_challenge test case wrong?

In compress_challenge, the problem is specified as:

Problem: Compress a string such that 'AAABCCDDDD' becomes 'A3BC2D4'. Only compress the string if it saves space.

However, the last three test cases test for:

assert_equal(func('AAABCCDDDDE'), 'A3BC2D4E')
assert_equal(func('BAAACCDDDD'), 'BA3C2D4')
assert_equal(func('AAABAACCDDDD'), 'A3BA2C2D4')

shouldn't they be:

assert_equal(func('AAABCCDDDDE'), 'A3BCCD4E')
assert_equal(func('BAAACCDDDD'), 'BA3CCD4')
assert_equal(func('AAABAACCDDDD'), 'A3BAACCD4')

since compressing 2 repeated characters doesn't save space?

"Implement n stacks using a single array" solution uses 2 arrays

Why not include the stack pointer at the top of each stack so you can do this with a single num_stacks * (stack_size + 1) array?

Also, it is not clear why abs_index is part of the interface (as that is not part of the stack interface). Its purpose should be made clear in the challenge notebook.

Add incremental hints for each challenge notebook

Hints could be provided to help users incrementally arrive at the desired solution. Users could %load these hints into the Challenge Notebook when needed.

Hints

Run the following cell(s) for a hint:

%load hint1.txt
%load hint2.txt

Running the cell(s) would would load the contents of the accompanying hint file:

# %load hint1.txt
Consider a brute force solution that scans each 
element and compares it with every other element.
# %load hint2.txt
The brute force solution has a time complexity of O(n^2).  
A hash map lookup could help make this linear.

How to debug?

Thank you for your awesome challenges.

I am new to python, I know there is print and pdb.set_trace().

  1. Could you tell me where is the printed message?
  2. And how to make pdb.set_trace() work?

Solution to the Longest Common Subsequence needs corrections

The current solution could be spooked with 2 inputs : "ABCDFE" and "FOOBCDBCDE". The logic will create a map that will still end up having the last letter E in sequence.

According to Wikipedia , they are filling in 0 instead of taking the max (left, above) for characters that aren't matched.

Bug in bst_validate solution

The solution for bst_validate won't work if the tree has a node with the value of -sys.maxsize.

A suggested tweak would be to use None instead of sys.maxsize and -sys.maxsize.

 class BstValidate(Bst):

    def validate(self):
        if self.root is None:
            raise TypeError('No root node')
        return self._validate(self.root)

    def _validate(self, node, minimum=None, maximum=None):
        if node is None:
            return True

        if not ((minimum is None or node.data>minimum) and (maximum is None or node.data<=maximum)):
            return False

        if not self._validate(node.left, minimum, node.data):
            return False

        if not self._validate(node.right, node.data, maximum):
            return False
        
        return True

I would be happy to prepare a PR if this makes sense to you.

Bug in Compress a string notebook?

The compress_string notebook as the following test cases:

  • None -> None
  • '' -> ''
  • 'AABBCC' -> 'AABBCC'
  • 'AAABCCDDDD' -> 'A3B1C2D4'

Shouldn't the third test case result be A2B2C2?
If not then the description of this challenge needs some more details on how this result is consistent with the last test result.

Longest Common Subsequence algorithm wrong?

Longest Common Subsequence algorithm solution doesn't work on.

Here is the test case from Tushar Roy's video on Longest Common Subsequence (https://www.youtube.com/watch?v=NnD96abizww).

class TestLongestCommonSubseq(object):
    def test_another(self):
        str_comp = StringCompare()
        str0 = 'ABCDAF'
        str1 = 'ACBCF'
        expected = 'ABCF'
        assert_equal(str_comp.longest_common_subseq(str0, str1), expected)

The solution says

     13                 if i == 0 or j == 0:
     14                     T[i][j] = 0
---> 15                 elif str0[j - 1] != str1[i - 1]:
     16                     T[i][j] = max(T[i][j - 1],
     17                                   T[i - 1][j])

IndexError: string index out of range

Installation issues with virtualenvwrapper on Debian and Ubuntu

When I do:

pip install -r requirements.txt

and install ipython[notebook]

I have this problem when I open a terminal in ubuntu and Debian.

Traceback (most recent call last):
File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main
"main", fname, loader, pkg_name)
File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
exec code in run_globals
File "/usr/local/lib/python2.7/dist-packages/virtualenvwrapper/hook_loader.py", line 16, in
from stevedore import ExtensionManager
File "/usr/local/lib/python2.7/dist-packages/stevedore/init.py", line 11, in
from .extension import ExtensionManager
File "/usr/local/lib/python2.7/dist-packages/stevedore/extension.py", line 17, in
import pkg_resources
File "/usr/local/lib/python2.7/dist-packages/pkg_resources/init.py", line 72, in
import packaging.requirements
File "/usr/local/lib/python2.7/dist-packages/packaging/requirements.py", line 59, in
MARKER_EXPR = originalTextFor(MARKER_EXPR())("marker")
TypeError: call() takes exactly 2 arguments (1 given)
virtualenvwrapper.sh: There was a problem running the initialization hooks.

If Python could not import the module virtualenvwrapper.hook_loader,
check that virtualenvwrapper has been installed for
VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is
set properly.

This error happen twice in a Deban virtual machine and in an Ubuntu

requirements.txt?

It may be worth including a requirements.txt to this repository so that it's easy to install all the necessary dependancies in a virtualenv.

Python3.6: Error when installing packages with pip install -r requirements.txt

I'm using python3.6 and when I ran pip install -r requirements.txt to install all required packages the notebook did not work properly. When opening a notebook from the project I got this error:
/usr/bin/python: no module named ipykernel_launcher

Upon googling this issue I found the advice to reinstall this packages so I ran:

pip3 uninstall ipykernel_launcher
pip3 install ipykernel_launcher

This fixed that import issue, but when I proceeded to open a notebook I got this error:
ImportError: cannot import name 'generator_to_async_generator'

This did not have an easy fix on the internet, so I basically uninstalled all installed packages by running:

pip3 uninstall -r requirements.txt
and proceeded to install jupyter notebook with pip by running:

pip3 install jupyter

This seems to have fixed the issue, all notebooks I have tried so far have worked without issue. But I feel this should be added in the README or did I do something wrong?

Bug in add_reverse_solution

Input:

Input 1: 6->5->4
Input 2: 9->8->7->9->9

Expected:

Result: 5->4->2->0->0->1

Actual:

Result: 5->4->2->0->1

bst_valid_challenge's one test case is wrong

hi, I noticed that test case below is not a valid binary search tree, it might be valid if we delete the node 6, but in your challenge notebook marked it as valid. I'm not sure I should delete the node 6 and send a pr or just submit an issue, so I just submit an issue.
Valid:

      5
    /   \
   5     8
  / \   /
 4   6 7

longest common substring solution is for non-contiguous strings

https://en.wikipedia.org/wiki/Longest_common_substring_problem

according to wikipedia, because the substring is contiguous, we should end up with something like:
(I don't know python, sorry)

// preamble omitted
  let mut res = 0;
  for i in 0..a.len()+1 {
    for j in 0..b.len()+1 {
      if i == 0 || j == 0 { dist[i][j] = 0; }
      else if a[i - 1] == b[j - 1] {
        dist[i][j] = 1 + dist[i - 1][j - 1];
        res = std::cmp::max(res, dist[i][j]);
      }
      else {
        dist[i][j] = 0;
      }
    }
  }

Other solutions I've found also do something similar: http://www.geeksforgeeks.org/longest-common-substring/

However, the longest common substring implemented here does:

# preamble omitted
        for i in range(num_rows):
            for j in range(num_cols):
                if i == 0 or j == 0:
                    T[i][j] = 0
                elif str0[j - 1] != str1[i - 1]:
                    T[i][j] = max(T[i][j - 1],
                                  T[i - 1][j])
                else:
                    T[i][j] = T[i - 1][j - 1] + 1

despite stating:

Is a substring a contiguous block of chars?
Yes

It looks as though the solution is modelling the recurrence relation for subsequence not substring. Have a look at the geeksforgeeks solution for subsequence:

http://www.geeksforgeeks.org/dynamic-programming-set-4-longest-common-subsequence/

It's very similar to this repo's implementation of 'substring'

Media files missing from Coding anki deck

If you run Tools -> Check Media in Anki, the following files are reported as missing:

dijkstra.gif
selection_sort.gif
eratosthenes.gif
quicksort_wikipedia.gif
merge_sort.gif
insertion_sort.gif

sort_stack pseudocode and test cases text is incorrect

I think there are some mistakes in sort_stack's pseudocode and test cases description.

The test cases section says:

  • Empty stack -> None

But it should be returning an empty stack, not None.

Under the algorithm section, it says

" * While buffer is not empty or buffer top is > than temp\n",

but the code says

while not buff.is_empty() and temp < buff.peek():

so that should be an and, not an or.

It also says

"* Our buffer will hold elements in reverse sorted order, smallest at the top\n",

but the buffer stores elements in sorted order, largest at the top. Otherwise, how could we return buffer as our answer when the output should have the largest element at the top?

I also suggest changing

"* Store the current top element in a temp variable\n",

to

" * Pop the current top element of stack into a temp variable\n",

This clarifies that the top element is not just copied to a temp variable, but rather popped off into the temp variable. Also this happens within the outer while loop, not before.

Here's the code version of the solution for reference:

class MyStackSimplified(Stack):

    def sort(self):
        buff = MyStack()
        while not self.is_empty():
            temp = self.pop()
            while not buff.is_empty() and temp < buff.peek():
                self.push(buff.pop())
            buff.push(temp)
        return buff

I've submitted pull request #263 for this issue.

Add two numbers without the + or - sign [Bug]

The bitwise add 2 integers solution will hit infinite loop for negative integers. The carry will keep increasing if the bit length is not bounded.
Proposed solution:

	def sum_two(self,a,b):
                #max bit length, change to 32 for 32bit
		max_positive = 2 ** 64
		min_negative = -2 ** 64

		while b != 0:
			if b == max_positive:
				return a ^ min_negative
			a,b = a ^ b,(a&b)<<1
		return a

Bug - fibonacci

in ./recursion_dynamic/fibonacci/fibonacci_challenge.ipynb


### currently

Test Cases
n = 0 -> 0
n = 1 -> 0
n > 1 -> 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...

should be

Test Cases
n = 0 -> 0
n = 1 -> 1
n > 1 -> 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...

Linked_List_Challenge get length method- another solution?

I'm not sure this is necessarily an issue: The current solution of linked_list_challenge.ipynb uses an iterative approach to getting the length of a linked list, resulting in an O(n) time complexity for that method. Another solution could be to have an instance variable, updating this variable whenever we insert_to_front(), append(), or delete() and return this variable whenever we call the length method (thus O(1)) . I'm not a python expert, so I don't know how "Pythonic" this solution is, but I got it working in my notebook and can submit a PR if this is appropriate

Two sum unit test too strict

    def test_two_sum(self):
        solution = Solution()
        assert_raises(TypeError, solution.two_sum, None, None)
        assert_raises(ValueError, solution.two_sum, [], 0)
        target = 7
        nums = [1, 3, 2, -7, 5]
        expected = [2, 4]
        assert_equal(solution.two_sum(nums, target), expected)
        print('Success: test_two_sum')

[4, 2] should also be a valid answer. Unittest has an assertItemsEqual method, I'm not sure if nose has that too. I'm happy to write a PR for this, it's trivial to fix.

Issue on anagram check in java and python

You are using sum of prime numbers logic for checking anagrams which might result in inconsistent results like for example aa and b are my inputs which are not anagram to each other . In your case of addition the result will come as both are anagrams to each other.

Hence please fix the logic to product than using sum.

For your reference —-
https://forum.cosmoquest.org/showthread.php?167873-Using-Prime-Numbers-to-Check-if-Two-Words-are-Anagrams
https://hastebin.com/adazekoyet.swift
https://stackoverflow.com/questions/13215789/comparing-anagrams-using-prime-numbers

Remove reference to deleted node

In the stack challenge (stacks_queues/stack/stack_challenge), more specifically in the pop() method, shouldn't we be removing references from the node we want to pop? Only updating the top reference doesn't remove the reference the old top (popped item) has to the new top.

Append method of linkedlist implementation has a bug

https://github.com/donnemartin/interactive-coding-challenges/blob/master/linked_lists/linked_list/linked_list_solution.ipynb

When self.head == None, the node returned is not the node assigned to self.head. self.head should be assigned node.

I just found that the delete method also has a bug. When self.head.data == data, self.head is set to None and that deletes the whole linkedlist and not just the head... self.head should be set to self.head.next in that case.

Issue with Pythonic Solution for reverse_string

The following solution does not work:

class ReverseStringAlt(object):

    def reverse_string_alt(string):
        if string:
            return string[::-1]
        return string

    def reverse_string_alt2(string):
        if string:
            return ''.join(reversed(string))
        return string

Small phrasing fix

In /stacks_queues/sort_stack/sort_stack_solution.ipynb there's a small phrasing issue on the line:
"While buffer is empty or buffer top is > than temp\n".

It should be "While buffer is not empty or buffer top is > than temp\n" as implied in the code below:

class MyStack(Stack):

    def sort(self):
        buff = MyStack()
        while not self.is_empty():
            temp = self.pop()
            while not buff.is_empty() and buff.peek() > temp:
                self.push(buff.pop())
            buff.push(temp)
        return buff

IPython Notebook install instructions need a tweak

The wording makes it sound like installing the notebook dependencies is an optional step. The command is actually needed to run the notebooks.

Before

Or if you want to also get the dependencies for the IPython Notebook:

pip install "ipython[notebook]"

After

Install the dependencies for the IPython Notebook:

pip install "ipython[notebook]"

Add number prefix to directory names of categories/challenges to indicate order

When you start the IPython/Jupyter notebook at the top-level of the repo, as suggested by the readme, it presents the directory listing and it is not clear where to start and which directories contain challenges and which do not (e.g. the templates directory).

If you go into a challenge category directory, again, it is not clear in which (suggested) order the challenges (if any) should be tackled.

I suggest naming the category and challenge directories with a two-digit number prefix, so that they are ordered like in the readme. Example:

Categories:

01_arrays_strings
02_linked_lists
....

Challenges:

01_unique_chars
02_permutation
...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.