Code Monkey home page Code Monkey logo

ctci's Introduction

ctci

Solutions for "Cracking the Coding Interview v5"

Adding equivalent solutions in Objective-C Adding my own solutions

ctci's People

Contributors

adam-singer avatar aimeehu avatar anujku avatar caferyil avatar charnugagoo avatar davidorchard avatar dawsbot avatar dineshappavoo avatar edshadi avatar fcwheat avatar filannim avatar gaylemcd avatar kristianjaeger avatar mikeolteanu avatar nawaidshamim avatar nawazlj avatar ndavon avatar nkher avatar ouyanguf avatar prakashn27 avatar remstos avatar s16h avatar santhoshvai avatar sarathjoseph avatar shogunsea avatar smartkiwi avatar stujo avatar waltherg avatar yoavfrancis avatar yrbahn 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

ctci's Issues

Question 2_4 in python is completely wrong

It doesn't even work.
As an example:

python2 Question2_4.py
LinkedList [ 27->32->24->15->50->17->19->22->2->30 ] , x=15
LinkedList [ 2->27->32->24->15->50->17->19->22->30 ]

CSharp: Null Exception in Partition4 method of Chapter 2 Question 4 when input linked list doesn't contain pivot value

The O(n) time and O(1) space solution for Chapter 2 Question 4 crashes when the input list doesn't contain the pivot value (dangerous assumption).

My solution to this failure is in the PartitionInPlace method below:

https://github.com/alibad/PlayGround/blob/master/Cracking/Chapter%202/Problem_2_4.cs

Let me know if you like my solution and I can add it as a Partition4 to the existing file in this repo.

Thanks

for the CC150 4.9 java version, there is an write

The way at here and in the book can't find the path from leaf to leaf, or any path accrosses two PATH(from root to leaf), you can use your existing example, findSum(root, 9) and you will found the what I mean, your way outputs nothing, but there should be two paths where sum=9.

BTW, your book is awesome!

Python code for Q1.6

The original Q asks for a solution to do the rotation in place but the current solution obviously created a new matrix to do that. Please consider the following code, which rotates the picture (image) matrix in place:

def rotate_pic(pic):
    N = len(pic)
    for r in range(int(N/2)):
        for c in range(r, N-r-1):  
            p1 = pic[r][c]
            p2 = pic[c][N-r-1]
            p3 = pic[N-r-1][N-c-1]
            p4 = pic[N-c-1][r]
            pic[c][N-r-1] = p1
            pic[N-r-1][N-c-1] = p2
            pic[N-c-1][r] = p3
            pic[r][c] = p4

Question1_1 in java,the book's code is different from the code on github

int the book,the code is:
if (str.length() > 26) {
return false;
}
it's contains only the lowercase a to z characters.

but on github,the code is:

if (str.length() > 128) {
return false;
}

it's contains all ASCII.

public static boolean isUniqueChars(String str) {
if (str.length() > 128) {
return false;
}
int checker = 0;
for (int i = 0; i < str.length(); i++) {
int val = str.charAt(i) - 'a';
System.out.println(val);
if ((checker & (1 << val)) > 0) return false;
checker |= (1 << val);
}
return true;
}

4.1 could be optimised

We could add simple checks to avoid unnecessary traversal in case of unbalanced tree.
For example if a node has no elements in its right subtree, it makes no sense to traverse its left subtree for levels higher than 1. So if we reach 2nd level in the left subtree, we already know that the tree is unbalanced.
Also after processing left subtree we have its height and we could limit the maximum depth of traversal for the right subtree to this value.

4.9 question wording is confusing

The question states that
"The path does not need to start or end at the root or a leaf but must in a straight line down"

So is left-left-right a valid path ? I would think it is a not a straight path when drawn on a binary tree.
I am not sure what could be a good way to describe it without using the phrase "straight line" but this phrase is surely confusing. At least the solution should contain a diagram which clears this ambiguity.

update readme.md file

Project Title

One Paragraph of project description goes here

Table of contents

 Adding the list of contents it will easy of user.

Getting Started

These instructions will get you a copy of the project up and run on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.

Running the tests

Explain how to run the automated tests for this system

Break down into end to end tests

Explain what these tests test and why

Give an example

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Acknowledgments

  • Hat tip to anyone who's code was used
  • Inspiration
  • etc

And also you can add contribute.md file which is written in markdown language.

Contributing to the project

Please take a moment to review this document in order to make the contribution
process easy and effective for everyone involved.

Following these guidelines helps to communicate that you respect the time of
the developers managing and developing this open source project. In return,
they should reciprocate that respect in addressing your issue, assessing
changes, and helping you finalize your pull requests.

As for everything else in the project, the contributions to this project are governed by our team.

Bug reports

A bug is a demonstrable problem that is caused by the code in the repository.
Good bug reports are extremely helpful - thank you!

Guidelines for bug reports:

  1. Use the GitHub issue search — check if the issue has already been
    reported.

  2. Check if the issue has been fixed — try to reproduce it using the
    latest master or next branch in the repository.

  3. Isolate the problem — ideally, create a reduced test case.

A good bug report shouldn't leave others needing to chase you up for more
information. Please try to be as detailed as possible in your report. What is
your environment? What steps will reproduce the issue? What OS experiences the
problem? What would you expect to be the outcome? All these details will help
people to fix any potential bugs.

Any other information you want to share that is relevant to the issue being
reported. This might include the lines of code that you have identified as
causing the bug, and potential solutions (and your opinions on their
merits).

Feature requests

Feature requests are welcome. But take a moment to find out whether your idea
fits with the scope and aims of the project. It's up to you to make a strong
case to convince the project's developers of the merits of this feature. Please
provide as much detail and context as possible.

Pull requests

Good pull requests - patches, improvements, new features - are a fantastic
help. They should remain focused in scope and avoid containing unrelated
commits.

Please ask first before embarking on any significant pull request (e.g.
implementing features, refactoring code), otherwise you risk spending a lot of
time working on something that the project's developers might not want to merge
into the project.

For new Contributors

If you never created a pull request before, welcome: tada: : smile: Here is a great tutorial
on how to send one :)

  1. Fork the project, clone your fork,
    and configure the remotes:

    # Clone your fork of the repo into the current directory
    git clone https://github.com/<your-username>/<repo-name>
    # Navigate to the newly cloned directory
    cd <repo-name>
    # Assign the original repo to a remote called "upstream"
    git remote add upstream https://github.com/this projecthq/<repo-name>
  2. If you cloned a while ago, get the latest changes from upstream:

    git checkout master
    git pull upstream master
  3. Create a new topic branch (off the main project development branch) to
    contain your feature, change, or fix:

    git checkout -b <topic-branch-name>
  4. Make sure to update, or add to the tests when appropriate. Patches and
    features will not be accepted without tests. Run npm test to check that all
    tests pass after you've made changes. Look for a Testing section in the
    project’s README for more information.

  5. If you added or changed a feature, make sure to document it accordingly in
    the README.md file.

  6. Push your topic branch up to your fork:

    git push origin <topic-branch-name>
  7. Open a Pull Request
    with a clear title and description.

For Members of the this project Contributors Team

  1. Clone the repo and create a branch

    git clone https://github.com/this projecthq/<repo-name>
    cd <repo-name>
    git checkout -b <topic-branch-name>
  2. Make sure to update, or add to the tests when appropriate. Patches and
    features will not be accepted without tests. Run npm test to check that all tests
    pass after you've made changes. Look for a Testing section in
    the project’s README for more information.

  3. If you added or changed a feature, make sure to document it accordingly in
    the README.md file.

  4. Push your topic branch up to our repo

    git push origin <topic-branch-name>
  5. Open a Pull Request using your branch with a clear title and description.

Optionally, you can help us with these things. But don’t worry if they are too
complicated, we can help you out and teach you as we go :)

  1. Update your branch to the latest changes in the upstream master branch. You
    can do that locally with

    git pull --rebase upstream master

    Afterward, force push your changes to your remote feature branch.

  2. Once a pull request is good to go, you can tidy up your commit messages using
    Git's interactive rebase.
    Please follow our commit message conventions shown below, as they are used by
    semantic-release to automatically
    determine the new version and release to npm. In a nutshell:

Issues

Issue open :
It is not just fun.If there is really the bug or issue or suggestion the create an issue or make a pull request.

4.9 C++ implementation print the path in the reversed order

In the function print the code used to print the path is wrong. In the question, it says path must go in a straight line down, but the implementation print the path straight line up.
for(int j=i; j <= level; j++) cout<<path[j]<<" "; cout<<'\n';

C: quicksort fails to sort

I was trying to understand why my implementation of quicksort was not working, and figured I'd look at this repo for some insights.

The array input that I am testing is:

int nbr[8] = {3, 1, 2, 0, 8, 9, 11, -1};

If I print the elements after sorting, I see:

nbr failed
-1 1 2 0 3 8 9 11 
nbr_small passed
nbr_null passed

0 is at index 4, instead of index 2.

Following is main with my modifications:

int main(void){
  int nbr[8] = {3, 1, 2, 0, 8, 9, 11, -1};
  int nbr_small[2] = {100, 2};
  int *nbr_null = NULL;

  quicksort(nbr, 8);
  quicksort(nbr_small, 2);
  quicksort(nbr_null, 10);

  if(is_sorted(nbr, 8))
    printf("nbr passed\n");
  else
    printf("nbr failed\n");
  for (int i = 0; i < 8; i++) {
	  printf("%d ", nbr[i]);
  }
  printf("\n");

  if(is_sorted(nbr_small, 2))
    printf("nbr_small passed\n");
  else
    printf("nbr_small failed\n");

  if(nbr_null == NULL)
    printf("nbr_null passed\n");
  else
    printf("nbr_null failed\n");

  return EXIT_SUCCESS;
}

Quick diff:

int main(void){						      |	int main(){
  int nbr[8] = {3, 1, 2, 0, 8, 9, 11, -1};		      |	  int i;
							      >	  int nbr[5] = {10, 1, 0, 5, 2};
  quicksort(nbr, 8);					      |	  quicksort(nbr, 5);
  if(is_sorted(nbr, 8))					      |	  if(is_sorted(nbr, 5))
  for (int i = 0; i < 8; i++) {				      <
	  printf("%d ", nbr[i]);			      <
  }							      <
  printf("\n");						      <

Trinocular operator returns boolean type

Is this a good practice to use a trinocular operator when the result itself is boolean as below:

boolean isAncestor = rx.node != null || ry.node != null ? true : false;

or we can just write

boolean isAncestor = rx.node != null || ry.node != null;

Problem4_7

Question2_7

I might be wrong, but your method isPalindromeRecurse can be simplified like this:

public static Wrapper isPalindromeRecursive(Node<Integer> node, int length) {
    if (length == 0) {
        return new Wrapper(node, true);
    } else if (length == 1) {
        return new Wrapper(node.next, true);
    }

    Wrapper result = isPalindromeRecursive(n.next, length - 2);
    result.palindrome = result.palindrome && node.data == result.node.data;
    result.node = node.next;
    return result;
}

The case when length == 2 will be covered by length == 0 if we return current node instead of null.
The return logic is also easier without conditionals.
Correct me, please, if there are flaws in my solution.

4.8 Java

The question said both trees are very large. Does it mean we should not use a recursive way of doing this?

Compilation in eclipse

Earlier when it was in svn i was able to import and run the full project.
I do not know how to import frim github and then run it properly
can you please any walkthrough or tutorial on how to do this ?

BitInteger problem

Hi,

For the chapter 5, problem 7, in the solution, altough the last index stores the least significant k(the least significant is at INTEGER_SIZE - 1 th index), toInt() function seems to convert value reversely: INTEGER_SIZE - 1 th index becomes the most significant bit as the result of toInt() function.

Thanks,
İrem Özbek

Question8_4: If failed, clear filled spots

private boolean parkStartingAtSpot(int spotNumber, Vehicle vehicle) {

If one or more spots fail, it seems to still decrease the number of available spots, and also doesn't free the spots that succeeded. This should be an "all-or-nothing" kind of transaction. Potentially, if a level fails to park the vehicle, the following level should try, which then starts by clearing the spots on the given vehicle. To make sure we are clearing the correct number of vehicles vs. decreasing the correct number of available spots, a workaround would be to decrease the available spots by the actual number of spots that were filled rather than the vehicle's number of spots needed.

NullPointerException in problem 3.3

When you try to pop, directly after creation, you will get Null Pointer Exception in int v = last.pop(), since the list of stacks is empty.

public int pop() {
    Stack last = getLastStack();
    int v = last.pop();
    if (last.size == 0) {
        stacks.remove(stacks.size() - 1);
    }
    return v;
}

Question1_1 in java

Hey,the code of this maybe wrong:

public static boolean isUniqueChars(String str) {
    if (str.length() > 128) {
        return false;
    }
    int checker = 0;
    for (int i = 0; i < str.length(); i++) {
        int val = str.charAt(i) - 'a';
        System.out.println(val);
        if ((checker & (1 << val)) > 0) return false;
        checker |= (1 << val);
    }
    return true;
}

when i try these :
String[] words = {"0p","1q","2r","3s","4t","5u","6v","7w","8x","9y"};
the result is false.
image

Gitter?

Hi @gaylemcd! It might be a good idea to open a gitter for this repository. Gitter is just a public chat room you can create for free on repositories. (Think Slack)

https://gitter.im

Bug in 8.10 Java solution

In the Java solution for 8.10, if there is a collision in the bucket where the new element is to be placed, the current code uses collided.remove(c) where collided is the LinkedList object and c is the node in the bucket's list. But calling remove(...) on the LinkedList object itself, and not the iterator, will remove the element by starting at the beginning of the list and traversing until it finds the element. This has 2 problems 1) If the item removed is the second to last element in the list, the loop will never visit the last element (In my opinion the LinkedList iterator should actually throw a ConcurrentModificiationException here, but the check is in next(), and not hasNext() ). 2) This eliminates the benefit of using a LinkedList. The for loop should explicitly use the List's iterator, and then the remove should be done using the remove method of the iterator. This will take O(1) time instead of O(n), where n is the number of items in the bucket.

Char Range up To 128

Is it good to check length of char to 128 if one can use like:
int i=234;
String word="s";
char c=(char)234
word+ss;
isUniqueChars(word)

If someone try this so should be check for that as well

Can we add scala solution

As a scala fan, I hope I'm able to enjoy writing scala solutions to the whole CTCI solution sets.

Java generics

In Chapter 10 and Question 10_3 , and few more questions have the same warning issued by IDE that the declarations doesn't have Generics. Nowadays even a naive Java programmer writes his code with Generics, which has the following advantages.
http://docs.oracle.com/javase/tutorial/java/generics/why.html

Are these very trivial ? If yes, the issue can be closed.

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.