From d2eb2a92a2b227ffa83b75208a3387262947a101 Mon Sep 17 00:00:00 2001 From: aadil42 <77232799+aadil42@users.noreply.github.com> Date: Mon, 23 Dec 2024 16:36:58 +0530 Subject: [PATCH] Create 1849-splitting-a-string-into-descending-consecutive-values.js Solved splitting-a-string-into-descending-consecutive-values with recursion. --- ...ring-into-descending-consecutive-values.js | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 javascript/1849-splitting-a-string-into-descending-consecutive-values.js diff --git a/javascript/1849-splitting-a-string-into-descending-consecutive-values.js b/javascript/1849-splitting-a-string-into-descending-consecutive-values.js new file mode 100644 index 000000000..8c2a3850e --- /dev/null +++ b/javascript/1849-splitting-a-string-into-descending-consecutive-values.js @@ -0,0 +1,29 @@ +/** + * BackTracking | DFS + * Time O(n^2) | Space O(n) + * https://leetcode.com/problems/splitting-a-string-into-descending-consecutive-values/ + * @param {string} s + * @return {boolean} + */ +var splitString = function(s) { + + const dfs = (start, pre) => { + if (start === s.length) return true; + for (let i = start; i < s.length; i++) { + const subStr = s.slice(start, i+1); + if ((+pre) - (+subStr) === 1) { + if( dfs(i+1, subStr)) return true; + } + } + + return false; + } + + for (let i = 0; i < s.length; i++) { + const subStr = s.slice(0, i+1); + if (i+1 === s.length) continue; // this means we took the entire string without spliting atleast once. + if (dfs(i+1, subStr)) return true; + } + + return false; +};