I can't pass this coding challenge: Code Challenge: https://www.codewars.com/kata/550f22f4d758534c1100025a/train/javascript
because my code is TOO SLOW. I'm not sure which part of my code is causing the problem. That's why I need help to optimize it.
function dirReduc(arr){
if (arr.length === 0 || arr.length === 1) return [];
let lengthTracker = arr.length;
for (let i = 0; i < arr.length; i++) {
if (lengthTracker > arr.length) {
lengthTracker = arr.length;
i = 0;
}
switch(arr[i]) {
case "NORTH":
arr[i-1] === "SOUTH"? arr.splice(i-1,2) :
arr[i+1] === "SOUTH"? arr.splice(i,2) : null
break;
case "SOUTH":
arr[i-1] === "NORTH"? arr.splice(i-1,2) :
arr[i+1] === "NORTH"? arr.splice(i,2) : null
break;
case "EAST":
arr[i-1] === "WEST"? arr.splice(i-1,2) :
arr[i+1] === "WEST"? arr.splice(i,2) : null
break;
case "WEST":
arr[i-1] === "EAST"? arr.splice(i-1,2) :
arr[i+1] === "EAST"? arr.splice(i,2) : null
break;
}
i===arr.length-1? i=0:null
}
return arr;
}
Splicing can be expensive. We can form a recurrence that assumes the function has already correctly reduced the next part of the list:
function matches(a, b){
return (a == "NORTH" && b == "SOUTH") ||
(b == "NORTH" && a == "SOUTH") ||
(a == "EAST" && b == "WEST") ||
(b == "EAST" && a == "WEST");
}
function f(A, i=0){
if (i == A.length)
return [];
const rest = f(A, i + 1);
const [head,...tail] = rest;
if (head){
if (matches(A[i], head))
return tail;
else
return [A[i]].concat(rest);
}
return [A[i]];
}
I see several problems with this. First, as I mentioned in the comments, splicing long arrays is costly and makes your algorithm O(n^2). Simple and faster would be to use a read-point and a write-point to copy the elements into itself one cell at a time, just skipping over the annihilations and then use splice once at the end to trim the uncopied cells off the end of the array. This would make it O(n).
Secondly, your code is looking both forward and backward for matches which is both unnecessary and can be confusing. Finally, there's no need for a switch (...) as all of the branches do the same thing.
Here is how I would use your code to accomplish this, changing the things mentioned above and noted in the comments.
function dirReduc(arr){
if (arr.length === 0 || arr.length === 1) return [];
let lengthTracker = 0; // the write-point
for(let i = 0; i < arr.length; i++) { // i is the read-point
if(lengthTracker == 0) {
// if no output, copy readpoint to write-point and advance
arr[lengthTracker++] = arr[i];
} else {
// replaces switch()
if (((arr[lengthTracker-1] === "NORTH") && (arr[i] === "SOUTH"))
|| ((arr[lengthTracker-1] === "SOUTH") && (arr[i] === "NORTH"))
|| ((arr[lengthTracker-1] === "EAST") && (arr[i] === "WEST"))
|| ((arr[lengthTracker-1] === "WEST") && (arr[i] === "EAST"))) {
lengthTracker--; // annihilate by decrementing the writepoint
} else {
// copy readpoint to writepoint and advance
arr[lengthTracker++] = arr[i];
}
}
}
//trim the array to only include what was written
arr.splice(lengthTracker);
return arr;
}
Related
I was only allowed to use google document for writing.
Could you please tell me what I did wrong? The recruiter wont get back to me when I asked her why I failed
Task 1:
Implement function verify(text) which verifies whether parentheses within text are
correctly nested. You need to consider three kinds: (), [], <> and only these kinds.
My Answer:
const verify = (text) => {
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
}
};
return parenthesesStack.length ? 0 : 1;
}
Task 2:
Simplify the implementation below as much as you can.
Even better if you can also improve performance as part of the simplification!
FYI: This code is over 35 lines and over 300 tokens, but it can be written in
5 lines and in less than 60 tokens.
Function on the next page.
// ‘a’ and ‘b’ are single character strings
function func2(s, a, b) {
var match_empty=/^$/ ;
if (s.match(match_empty)) {
return -1;
}
var i=s.length-1;
var aIndex=-1;
var bIndex=-1;
while ((aIndex==-1) && (bIndex==-1) && (i>=0)) {
if (s.substring(i, i+1) == a)
aIndex=i;
if (s.substring(i, i+1) == b)
bIndex=i;
i--;
}
if (aIndex != -1) {
if (bIndex == -1)
return aIndex;
return Math.max(aIndex, bIndex);
} else {
if (bIndex != -1)
return bIndex;
return -1;
}
};
My Answer:
const funcSimplified = (s,a,b) => {
if(s.match(/^$/)) {
return -1;
} else {
return Math.max(s.indexOf(a),s.indexOf(b))
}
}
For starters, I'd be clear about exactly what the recruiter asked. Bold and bullet point it and be explicit.
Secondly, I would have failed you from your first 'for' statement.
See my notes:
// Bonus - add jsdoc description, example, expected variables for added intention.
const verify = (text) => {
// verify what? be specific.
const parenthesesStack = [];
for( let i = 0; i<text.length; i++ ) {
// this could have been a map method or reduce method depending on what you were getting out of it. Rarely is a for loop like this used now unless you need to break out of it for performance reasons.
const closingParentheses = parenthesesStack[parenthesesStack.length - 1]
// parenthesesStack.length - 1 === -1.
// parenthesesStack[-1] = undefined
if(text[i] === “(” || text[i] === “[” || text[i] === “<” ) {
parenthesisStack.push(text[i]);
// “ will break. Use "
// would have been more performant and maintainable to create a variable like this:
// const textOutput = text[i]
// if (textOutput === "(" || textOutput === "[" || textOutput === "<") {
parenthesisStack.push(textOutput)
} else if ((closingParentheses === “(” && text[i] === “)”) || (closingParentheses === “[” && text[i] === “]”) || (closingParentheses === “<” && text[i] === “>”) ) {
parenthesisStack.pop();
// There is nothing in parenthesisStack to pop
}
};
return parenthesesStack.length ? 0 : 1;
// Will always be 0.
}
Not exactly what the intention of your function or logic is doing, but It would fail based on what I can see.
Test it in a browser or use typescript playground. You can write javascript in there too.
Hard to tell without the recruiter feedback. But i can tell that you missundertood the second function.
func2("mystrs", 's', 'm') // returns 5
funcSimplified("mystrs", 's', 'm') // returns 3
You are returning Math.max(s.indexOf(a),s.indexOf(b)) instead of Math.max(s.lastIndexOf(a), s.lastIndexOf(b))
The original code start at i=len(str) - 1 and decrease up to 0. They are reading the string backward.
A possible implementation could have been
const lastOccurenceOf = (s,a,b) => {
// Check for falsyness (undefined, null, or empty string)
if (!s) return -1;
// ensure -1 value if search term is empty
const lastIndexOfA = a ? s.lastIndexOf(a) : -1
const lastIndexOfB = b ? s.lastIndexOf(b) : -1
return Math.max(lastIndexOfA, lastIndexOfB)
}
or a more concise example, which is arguably worse (because less readable)
const lastOccurenceOf = (s,a,b) => {
const safeStr = s || '';
return Math.max(safeStr.lastIndexOf(a || undefined), safeStr.lastIndexOf(b || undefined))
}
I'm using a || undefined to force a to be undefined if it is an empty string, because:
"canal".lastIndexOf("") = 5
"canal".lastIndexOf(undefined) = -1
original function would have returned -1 if case of an empty a or b
Also, have you ask if you were allowed to use ES6+ syntax ? You've been given a vanilla JS and you implemented the equivalent using ES6+. Some recruiters have vicious POV.
Function must return true for "()" sequence and false for "[)" sequence, so it does. But why this function doesn't return true for "||" sequence? Could you help, please?
I wrote this code, but nothing works :(
function check(s) {
const brackets = {
")": "(",
"]": "[",
"}": "{",
"|": "|",
};
const st = [];
for (let i = 0; i < s.length; i++) {
if (isClosedBracket(s[i])) {
if (brackets[s[i]].toString() !== st.pop()) {
return false;
}
} else {
st.push(s[i]);
}
}
return st.length === 0;
}
//if bracket is in this array, function returns true, so bracket is closing
function isClosedBracket(ch) {
return [")", "]", "}", "|"].indexOf(ch) > -1;
}
Well, since the pipe sequence "||" uses the same character for opening and closing, then when the first | (the opening one) will be encountered, the block of code for the closing bracket will be executed.
Your code works, but it will not operate correctly if the opening character is the same as the closing character. If you absolutely need this feature, then consider adding more checks in this particular situation.
However, the code will get much more complex since a singular | could also mean a closing bracket in an error sequence, so inputs like "(|)" will be a bit complicated to handle.
Thank you all! I solved this problem by adding another if/else block. Here is solution, if you need it =3
function check(str) {
let stack = [];
for (let i = 0; i < str.length; i++) {
if (
+str[i] === 1 ||
+str[i] === 3 ||
+str[i] === 5 ||
str[i] === "(" ||
str[i] === "[" ||
str[i] === "{"
) {
stack.push(str[i]);
} else if (
(+str[i] === 2 && stack.at(-1) === "1") ||
(+str[i] === 4 && stack.at(-1) === "3") ||
(+str[i] === 6 && stack.at(-1) === "5") ||
(str[i] === ")" && stack.at(-1) === "(") ||
(str[i] === "]" && stack.at(-1) === "[") ||
(str[i] === "}" && stack.at(-1) === "{")
) {
stack.pop();
} else if (str[i] !== stack.at(-1)) {
stack.push(str[i]);
} else {
stack.pop();
}
}
return !stack.length > 0;
}
Any ideas how to improve this code?
var isValid = function (s) {
let stack = [];
for (let i = 0; i < s.length; i++) {
let top = stack[stack.length - 1];
if (s[i] === "(" || s[i] === "{" || s[i] === "[") {
stack.push(s[i]);
} else if (s[i] === ")" && top === "(" && stack.length !== 0) {
stack.pop();
} else if (s[i] === "]" && top === "[" && stack.length !== 0) {
stack.pop();
} else if (s[i] === "}" && top === "{" && stack.length !== 0) {
stack.pop();
} else {
return false;
}
}
return stack.length === 0;
};
Function like this works (this is the problem https://leetcode.com/problems/valid-parentheses/)
However when i put variable "top" before the for loop ,the function doest do its job.
Can you please explain me what is the difference in this 2 cases?
Thank you!
I tried to put variable "top" before and in the for loop ,got different acting function.
Below is my code, it works for some strings but not for all.
Ex: "()()()()()((" expected is false, my code returns true.
function validParentheses(parens){
var stack = [];
parens.split('').map((cur, index) =>{
if(stack.length === 0 || stack[index-1] === cur) stack.push(cur);
else stack.pop();
});
return stack.length > 0 ? false : true;
}
stack[index - 1] will be valid so long as you push every iteration. In the case that you pop an element, the incrementing index will always be out of bounds.
Change it to stack.length - 1 to always get the last element, regardless of what is pushed or popped.
For every '(' there must be a exactly one ')'. So you need a counter to see that there is an exact match
function validParentheses(parens){
const chars = parens.split('');
const numChars = chars.length;
let ii;
let numOpenParens = 0;
for (ii = 0; ii < numChars; ii += 1) {
curChar = chars[ii];
numOpenParens += curChar == '(' ? 1 : -1;
// return false if there is one too many closed parens
if (numOpenParens < 0) {
return false;
}
}
// return true only if all parens have been closed
return numOpenParens === 0;
}
For case when stack's length is greater than 0:
if top of the stack is equal to current iterated parenthesis, push that to stack
else pop the stack
function validParentheses(parens) {
var stack = []
parens.split("").forEach((cur) => {
if (stack.length > 0) {
if (stack[stack.length - 1] === cur) {
stack.push(cur)
} else {
stack.pop()
}
} else {
stack.push(cur)
}
})
return stack.length > 0 ? false : true
}
console.log(validParentheses("()()()()()(("))
console.log(validParentheses("()()()()()()"))
console.log(validParentheses("((()))"))
console.log(validParentheses("((())))"))
in stack[index-1] === cur
you are comparing if the char isn't the same like the one stored in the stack, so )( opposite parens will be valid
you can try do something like this
function validParentheses(parens) {
if (parens % 2 == 1) return false;
for (let i = 0; i < parens.length; i++) {
const char = parens[i];
if (char == "(") {
if (parens[i + 1] == ")") {
i++;
} else {
return false
}
} else {
return false
}
}
return true;
}
You need to check the last added value as well, because an unresolves closing bracket should remain in he stack.
BTW, Array#forEach is the method of choice, because Array#map returns a new array, which is not used here.
function validParentheses(parens) {
var stack = [];
parens.split('').forEach((cur, index) => {
if (cur === ')' && stack[stack.length - 1] === '(') stack.pop();
else stack.push(cur);
});
return !stack.length;
}
console.log(validParentheses("(())()"));
console.log(validParentheses("()()()()()(("));
console.log(validParentheses("))(())"));
This probably has an easy solution, but I simply don't see it at the moment.
I have three if-clauses that ashould be activated based on the length of an array. The first two ones seem to work fine, but for some odd reason I can't activate the third one (arr.length === 3). Right before the if clauses I have tried an alert to test whether it gives the right length of the array and it does.
function calculateDistances() {
var arr = [];
arr.push(posM, posL, posR);
alert(arr[1])
for (var i = 0; i < arr.length; i++) {
if (!arr[i]) {
arr.splice(i,1)
}
}
alert(arr.length)
if (arr.length === 0 || 1) {
return true;
}
else if (arr.length === 2 ) {
var diameter = calculateDiameter(arr[0], arr[1])
if (diameter > minDistance) {
return false;
}
else {
return true;
}
}
else if (arr.length === 3) {
alert("hello")
var diameter1 = calculateDiameter(arr[0], arr[1]);
var diameter2 = calculateDiameter(arr[0], arr[2]);
var diameter3 = calculateDiameter(arr[1], arr[3]);
if (diameter1 && diameter2 && diameter3 < minDistance) {
return true
}
else{
return false
}
}
}
Nor can you activate the second.
There's a bug here: if (arr.length === 0 || 1) {
The 1 casts to true.
Perhaps you meant: if (arr.length === 0 || arr.length === 1) {
You need this:
if (arr.length === 0 || arr.length === 1) {
The way you put it, it is equal to
if ((arr.length === 0) || true) {
which is always true.
I think what you are looking for is below condition in the first if condition
if (arr.length === 0 || arr.length === 1) {
return true;
}
this checks whether the length of the array is 1 or it's 0. Your first if condition is always true as it has 1 which is true.
(arr.length === 0 || 1)
is always true.
You could usethis instead
if (arr.length <= 1)
{
return true;
}