HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Finding the given word from jumbled letters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thewordjumbledfindingfromgivenletters

Problem

I have tried to write JavaScript code to check whether I can form a word from the given string (jumbled):

function findWord(word, jumbledLetters, isSameLength) {
if(isSameLength && word.length !== jumbledLetters.length)
return false;

var uniquePosition = {};
for(var i = 0; i< word.length; i++)
for(var j=0; j< jumbledLetters.length; j++){
  if(word[i] === jumbledLetters[j] && j !== uniquePosition[j]) {
    uniquePosition[j] = j;
    break;
  }
}
return Object.keys(uniquePosition).length === (word.length);
}


I could do this with string permutation with minor changes, but I tried something like the above one. Could you please suggest refactoring to be done for the above code?

Solution

Your code is hard to read, please use correct indentation and brackets.

For example your for loop:

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


confused me at the start! Code shouldn't be confusing! Use brackets ;)

I believe the code will work (hypothetically), perhaps add some comments to make it a bit more clearer.

However your solution has a complexity of \$O(n²)\$, I would suggest to improve it.

A simple possible solution is to sort both strings alphabetically and run over them linear, this way you don't need to check if they are both of equal length, there is no need for 2 nested loops and it will run in linear time (sorting not included).

Example:

word: 'potato'
jumbled: 'otpato'

sorted word: 'aooptt'
sorted jumbled: 'aooptt'


run with one for loop over it and check if both match.

Goodluck!

Code Snippets

for(var i = 0; i< word.length; i++)
word: 'potato'
jumbled: 'otpato'

sorted word: 'aooptt'
sorted jumbled: 'aooptt'

Context

StackExchange Code Review Q#74981, answer score: 5

Revisions (0)

No revisions yet.