CtCI-6th-Edition-JavaScript-ES2015 icon indicating copy to clipboard operation
CtCI-6th-Edition-JavaScript-ES2015 copied to clipboard

bug in chapter 1 question 1 solution 2

Open noorgrewal opened this issue 7 years ago • 2 comments

Hello,

I hope you are doing well.

I noticed a bug in the solution code for ch1-q1-solution2, specifically the function hasUniqueCharactersSort(). We cannot sort a string directly in Javascript - we have to convert the string to an array and then perform the sorting operation on it.

I have fixed the bug. Also, I have attached 2 screenshots below that show the reproduced bug and that the fix works.

Thank you for providing these solutions. Overall, they are very helpful : )

Best, Noor

Before the fix: screen shot 2018-02-24 at 6 24 20 pm

After the fix: screen shot 2018-02-24 at 6 43 48 pm

noorgrewal avatar Feb 24 '18 23:02 noorgrewal

It did split in the ch1-q1.spec.js:

[
      'abcdefghi',
      'jklpoiuqwerzxcvmnsadf',
      '1234567890',
      'AaBbCcDdeFg1234567890(*&^%$#@!)'
    ].forEach(arg => {

      it(`returns true for unique string: '${arg}'`, function() {
        expect(func(arg.split(''))).to.be.true;
      });

    });

In fact in this repository, many test code ([ch\d-q\d].spec.js) involving string manipulation split the primitive string into an array of string, then pass it as argument into function (in [ch\d-q\d].js): func(arg.split('')). String in JavaScript is immutable, but Array is on the contrary. It's interesting and we need to be careful to discuss the space complexity of the method. Here, if we assume the input is already in 'array form', then we could say that the space complexity is O(1), but if the question indeed give us 'inputString' as our start point, in my opinion, for usage of sort(), split() takes inevitable O(n) for new array. Another similar situation is in ch1-q3.js:

    url[j] = '0';
    url[--j] = '2';
    url[--j] = '%';

This kind of assignment operation is only available to array, if we assume the input is already an array, the space complexity could be O(1), but if the input we have is a primitive string, I think it should be O(n) because of splitting.

Carr1005 avatar Mar 04 '18 08:03 Carr1005