Restore IP Addresses | LeetCode-93: Medium | JavaScript Implementation

Manan Kumar Gupta
2 min readFeb 5, 2022

We will be seeing the solution to the LeetCode problem 93 in JavaScript. I hope you will find it useful.

Problem Statement: A valid IP address consists of exactly four integers separated by single dots. Each integer is between 0 and 255 (inclusive) and cannot have leading zeros.

For example, “0.1.2.201” and “192.168.1.1” are valid IP addresses, but “0.011.255.245”, “192.168.1.312” and “192.168@1.1” are invalid IP addresses.
Given a string s containing only digits, return all possible valid IP addresses that can be formed by inserting dots into s. You are not allowed to reorder or remove any digits in s. You may return the valid IP addresses in any order.

Link to Problem: https://leetcode.com/problems/restore-ip-addresses/

Implementation:

var restoreIpAddresses = function (s) {
let result = [];
const util = (partitionCount, temp, i) => {
if (i == s.length || partitionCount == 4) {
if (i == s.length && partitionCount == 4) {
result.push(temp.substring(0, temp.length -1));
}
} else {
util(partitionCount + 1, temp + s[i] + ".", i + 1);
if ((i + 2) <= s.length) {
if(isValid(s[i] + s[i + 1])){
util(partitionCount + 1, temp + s[i] + s[i + 1]+ ".", i + 2);
}
}
if ((i + 3) <= s.length) {
if(isValid(s[i] + s[i + 1]+ s[i + 2])){
util(partitionCount + 1, temp + s[i] + s[i + 1]+ s[i + 2] + ".", i + 3);
}
}
}
};
const isValid = (str) => {
if (str[0] == 0) return false
if (parseInt(str) < 10 || parseInt(str) >255) {
return false;
} else {
return true;
}
};
util(0, "", 0);
return result;
};
console.log(restoreIpAddresses("25525511135"));

Thank you for reading hope this code is helpful to you.

--

--

Manan Kumar Gupta

I am Frontend Developer, exploring the power of Javascript. I have worked on Angular, ReactJS and React Native.