Smaller elements in left using stack
function next_smaller_left(arr) { var v = []; var s = []; for(var i = 0; i < arr.length; i++) { if(s.length == 0) { v.push(-1); } else if(s.length > 0 && s[s.length - 1] < arr[i]) { v.push(s[s.length - 1]); } else if(s.length > 0 && s[s.length - 1] >= arr[i]) { while(s.length > 0 && s[s.length - 1] >= arr[i]) { s.pop(); } if(s.length == 0) { v.push(-1); } else { v.push(s[s.length - 1]); } } s.push(arr[i]); } return v; }