- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Placing integers at correct index in JavaScript
Problem
We are required to write a JavaScript function that takes in a string, str, which consists of only ‘[‘ or ‘]’.
Our function is supposed to add the minimum number of square brackets ( '[' or ']', and in any positions ) so that the resulting bracket combination string is valid. And lastly, we should return the smallest number of brackets added.
For example, if the input to the function is
Input
const str = '[]]';
Output
const output = 1;
Output Explanation
Because, if we add ‘[‘ to the starting, the string will be balanced.
Example
const findAdditions = (str = '') => { let left = 0 let right = 0 for (let i = 0; i < str.length; i++) { if (str[i] === '[') { left += 1 } else if (str[i] === ']') { if (left > 0) { left -= 1 } else { right += 1 } } } return left + right; }; console.log(findAdditions(str));
Output
1
Advertisements