Open Side Menu Go to the Top
Register
Expected Interview Knowledge Expected Interview Knowledge

09-14-2016 , 11:26 PM
This is a slight twist on Interview Test Questions Problems, Solutions, Links, Discussion. In this thread, we pose questions that we would expect applicants to be able to answer if we were interviewing them. I'll start out with a simple one. In your chosen language, write a code snippet that determines if a string is a palindrome (case insensitive) Solution :

Spoiler:

Code:
function isPalindrome(string) {
    return string.split('').reverse().join('') == string
}


My chosen language is javascript.
Expected Interview Knowledge Quote
09-15-2016 , 02:21 AM
Ruby
Spoiler:
string == string.reverse
Expected Interview Knowledge Quote
09-17-2016 , 02:54 AM
Quote:
Originally Posted by Craggoo
This is a slight twist on Interview Test Questions Problems, Solutions, Links, Discussion. In this thread, we pose questions that we would expect applicants to be able to answer if we were interviewing them. I'll start out with a simple one. In your chosen language, write a code snippet that determines if a string is a palindrome (case insensitive) Solution :

Spoiler:

Code:
function isPalindrome(string) {
    return string.split('').reverse().join('') == string
}


My chosen language is javascript.
What is the runtime of this?

Spoiler:
n^3


Can you do better (can you solve this is n time, can you solve this in logN time)?
Expected Interview Knowledge Quote
09-17-2016 , 02:58 AM
Quote:
Originally Posted by daveT
What is the runtime of this?

Spoiler:
n^3


Can you do better (can you solve this is n time, can you solve this in logN time)?
I would expect for loops to be the fastest construct. I'll post a code snippet once I've sobered up. You have me curious @ runtime so Imma do some tests and see what the average run time is for the one liner solution vs the super dirty but more efficient version.
Expected Interview Knowledge Quote
09-17-2016 , 03:35 AM
Can't edit any longer but I feel that we can potentially break out of the for loop at any time with a check. What that means is that on a long string we can potentially break out of the for loop after checking just a single character and return false. So.... I feel that the difference between the one liner and the optimized version is entirely dependent on the length of the input string. A random 3 character string probably won't make any real difference but a random 20 character string would make a big difference for example.
Expected Interview Knowledge Quote
09-17-2016 , 04:10 AM
My optimized version for checking if two case sensitive strings are equal :

Spoiler:
Code:
function optimized(string) {

	var truthyString = '';

	for (var i=0; i<string.length;i++) {

		// we add some value to the truthy string. doesnt matter what value it is.
		// we break out of the iteration early if we do not find a match at the 
		// corresponding negative index in this optimized version

		if (string[string.length - i - 1] == string[i]) {
			truthyString += 'a'
		} else {
			break;
		}
	}

	// since we appended some dummy value we only care about length. If the lengths
	// are not the same they cannot possibly be equal. This version assumes case 
	// sensitive matching

	return truthyString.length == string.length;
}


The above version allows us to exit almost immediately in the case of a really long string like 'lkajdl;fjasdfjasdfkjsald;fjsadlkfjslakdjfskladjfl ;sdakjfsda;ljfsdlakjfsd;lakjfkl;dsjfl;ksdajfkl;asj dfajdsfkljsdafjskadf;jsadfklsadfjsadfM'.

We only check 'l' and 'M'. They are not equal so we return false right away instead of checking the other however many characters there are.
Expected Interview Knowledge Quote
09-17-2016 , 04:34 AM
with your new version, you don't have to...

Spoiler:
increment i all the way to string.length. You should be able to go to string.length / 2, which, assuming this is integer division, takes care of cases that you have an odd-length string (7 chars, for example).

you can then simply compare string[i - 1] == string[-i]. if finish, then you gotta a palindrome, else, you do not.

*caveat: don't know JS very well at all.



something in pseudo JS:

Spoiler:

Code:
function is_palindrome (str) {
    for (i = 0, i < str.length / 2; i++) {
       if (str[i - 1] != str[-i]) {
           return false
   }
   return true
}


of course, there is a recursive version, but I think you can figure that one out.

Last edited by daveT; 09-17-2016 at 04:40 AM. Reason: bug, I think...
Expected Interview Knowledge Quote
09-17-2016 , 05:27 AM
Quote:
Originally Posted by daveT
with your new version, you don't have to...

Spoiler:
increment i all the way to string.length. You should be able to go to string.length / 2, which, assuming this is integer division, takes care of cases that you have an odd-length string (7 chars, for example).

you can then simply compare string[i - 1] == string[-i]. if finish, then you gotta a palindrome, else, you do not.

*caveat: don't know JS very well at all.



something in pseudo JS:

Spoiler:

Code:
function is_palindrome (str) {
    for (i = 0, i < str.length / 2; i++) {
       if (str[i - 1] != str[-i]) {
           return false
   }
   return true
}


of course, there is a recursive version, but I think you can figure that one out.
We don't have to account for odd/even string lengths unless I'm mistaken. Imagine we have a string of length 3...

@ i = 0 we are comparing string[0] and string[2]
@ i = 1 (the middle index) we are comparing string[1] and string[1]

What about for a string of length 4?

@ i = 1 (the middle 2 indexes) we are comparing string[1] and string[2]

In the above scenario, imagine comparing a string of 'adda' to easily visualize a string of length 4 that should return true.

Your return true / return false has the same effect as my break/return truthyString.length == string.length but is a bit cleaner. It's been a while since I've used any for loops.

It's been my experience that most people are idiots. They barely progressed past for loops so testing them for a recursive version would be a fruitless endeavour. I'll post my recursive version tomorrow (or tonight if I don't pass out before then).

Actually @ return true/false inside for loop it doesn't. That was the the whole point of my break. Imagine a string of 'amba'. If i replaced if the if-else (break) with return true/false that would return true.

Last edited by Craggoo; 09-17-2016 at 05:39 AM.
Expected Interview Knowledge Quote
09-17-2016 , 07:41 AM
fine... this appears to work:

Spoiler:
Code:
function is_palindrome(str) {
    for (i = 1; i <= str.length / 2; i ++) {
         if (str[i - 1] != str.charAt(str.length - i)) {
               return false;
         }
     }
     return true 
}

// all evaluate to true:
is_palindrome("");
is_palindrome("a");
is_palindrome("abba");
is_palindrome("abcba");

// all evaluate to false:
is_palindrome("abca");
is_palindrome("abcab");


I'm truly surprised that JavaScript doesn't do str[-1].
Expected Interview Knowledge Quote
09-17-2016 , 09:31 AM
Quote:
Originally Posted by daveT
What is the runtime of this?

Spoiler:
n^3


Can you do better (can you solve this is n time, can you solve this in logN time)?
His algorithm is most definitely not O(n^3), it's already O(n)
Expected Interview Knowledge Quote
09-18-2016 , 01:29 AM
Quote:
Originally Posted by RustyBrooks
His algorithm is most definitely not O(n^3), it's already O(n)
you are right. Drinking and coding don't mix. sry
Expected Interview Knowledge Quote
09-18-2016 , 09:53 AM
Quote:
Originally Posted by RustyBrooks
His algorithm is most definitely not O(n^3), it's already O(n)
Right - from an asymptotic point of view, the issue is space complexity, not time, though it's also quite slow.
Expected Interview Knowledge Quote
09-18-2016 , 02:53 PM
Does javascript have iterators or generators or stuff like that? I have done a tiny bit of JS programmnig but I have no idea. That would probably be the most efficient way to do it.
Expected Interview Knowledge Quote
09-19-2016 , 01:17 PM
In c/c++ you can just use pointers to compare. Not sure if in javascript, splitting and reversing creates a copy, in which case the space complexity is O(n).

Time complexity is obviously Ω(n), you have to look at every element. Can't get any better than that.

Here's my palindrome in python. I'm a c/c++ guy so feel free to critique :def

Spoiler:
Code:
ispalindrome(s):
    l = 0
    r = len(s) - 1

    while l < r:
        if s[l] == s[r]:
            l = l + 1
            r = r - 1
        else:
            return False

    return True
Expected Interview Knowledge Quote
09-19-2016 , 02:00 PM
Efficiency wise yours is fine, but
Spoiler:

In python "reverse" makes an iterator and it works on strings so a simpler version would be
Code:
def ispalindrome2(s):
    return reversed(s) == s


Which has the same performance but is much simpler - really you don't even need a function for it. I made a quick script that tested both. They come out about the same, and both of them are capable, on my reasonably new linux machine, of processing about 5 million palindromes/s. I generated random strings from 10 to 1000 characters.
Expected Interview Knowledge Quote
09-19-2016 , 07:30 PM
Apparently javascript doesn't have a reverse function, so Cragoo is sort of stuck with his solution. With that said, I'd probably just pull the reverse part out into its own function.

I was looking around a bit and found this:

http://stackoverflow.com/questions/9...-in-javascript

It is quite an enlightening read. Looks like someone created a library that takes care of the strange stuff that happens.
Expected Interview Knowledge Quote
09-24-2016 , 12:28 AM
Quote:
Originally Posted by daveT
Apparently javascript doesn't have a reverse function, so Cragoo is sort of stuck with his solution. With that said, I'd probably just pull the reverse part out into its own function.

I was looking around a bit and found this:

http://stackoverflow.com/questions/9...-in-javascript

It is quite an enlightening read. Looks like someone created a library that takes care of the strange stuff that happens.
More specifically, there is not a string.reverse function but there is an array.reverse function. Seems like one of those 'wtf' moments.
Expected Interview Knowledge Quote
09-24-2016 , 12:37 AM
I feel like everyone is just trying to answer my original question "Is a string a palindrome?". Feel free to offer you own questions/solutions. My next question... given a string input, find the most commonly occurring word within that input. For this question, word is defined as a string with at least one whitespace character on both sides of a substring. Sample code :

Code:
function(inputString) {
    return mostCommonString
}
Expected Interview Knowledge Quote
09-24-2016 , 01:15 AM
This is what the recruiters at Google send to candidates prior to the phone screen interviews.

https://gist.githubusercontent.com/s...35/google-tips

Basically need to know everything :\

Also I spent a good hour and a half just doing this.. And I heard people asking this in interviews...
https://leetcode.com/problems/rotate-image/
Expected Interview Knowledge Quote
09-24-2016 , 01:35 AM
My solution to my latest question :

Spoiler:


Code:
  function mostCommonString(input) {

    var unique = []

    var strings = input.split(/\s+/)

    strings.forEach(function(element) {
      unique.indexOf(element.toLowerCase()) == -1 ? unique.push(element.toLowerCase()) : void 0;
    })

    var duplicates = unique.filter(function(element) {

      var hasDuplicates = strings.filter(function(ele) {
        return ele == element.toLowerCase()
      })

      return hasDuplicates.length > 1
    })
    
    return duplicates.length > 1 ? duplicates : duplicates.join('')
  }
Expected Interview Knowledge Quote
09-24-2016 , 01:37 AM
Per the 'in place' requirement, that is the easiest requirement. In JS, just modify this before you return this. Maybe its harder to do in other languages? The one question i would ask for the question is what assumption should I make? The 2d array is organised as [x][y] or [y][x]. With that in mind, it seems very straightforward with a bit of visualizing what you're working with imo.
Expected Interview Knowledge Quote
09-24-2016 , 02:10 AM
Quote:
Originally Posted by Craggoo
I feel like everyone is just trying to answer my original question "Is a string a palindrome?". Feel free to offer you own questions/solutions. My next question... given a string input, find the most commonly occurring word within that input. For this question, word is defined as a string with at least one whitespace character on both sides of a substring. Sample code :

Code:
function(inputString) {
    return mostCommonString
}
here's my solution, too lazy to write code, will do it in pseudocode :P
Spoiler:


time complexity: O(n)

Code:
function(inputString) {
     if inputString is empty:
          return nil or null
     dictionary = {}
     current_word = "";
    
     for (char c in inputString)
         if (c is a letter):
               add c to current_word
         else if current_word not empty:
             if current_word not in dictionary:
                 dictionary[current_word] = 1
             else
                 dictionary[current_word] += 1
                 current_word = ""

     if current_word not empty:
             if current_word not in dictionary:
                 dictionary[current_word] = 1
             else
                 dictionary[current_word] += 1
                 current_word = ""
      
      loop through dictionary and return key with highest value
}
Expected Interview Knowledge Quote
09-24-2016 , 11:22 AM
Quote:
Originally Posted by Craggoo
For this question, word is defined as a string with at least one whitespace character on both sides of a substring.
Not sure where you got this question but I think the wording is incorrect - this would exclude the first and last words unless you had space padding on both ends.
Expected Interview Knowledge Quote
09-24-2016 , 12:05 PM
Code:
public static String fun(String in) {
    return Pattern.compile("\\s+").splitAsStream(in)
            .collect(Collectors.groupingBy(Function.identity(),
                    Collectors.summingInt(s -> 1)))
            .entrySet().stream()
                .reduce(new AbstractMap.SimpleEntry<>("", 0), 
                    (a, b) -> a.getValue() > b.getValue() ? a : b)
            .getKey();
}

Last edited by bex989; 09-24-2016 at 12:12 PM.
Expected Interview Knowledge Quote
09-24-2016 , 01:18 PM
Quote:
Originally Posted by candybar
Not sure where you got this question but I think the wording is incorrect - this would exclude the first and last words unless you had space padding on both ends.
You're right my definition sucks. Will you get mad if i start using poor grammar too?
Expected Interview Knowledge Quote

      
m