--- id: 69cfca90e8a0a6d4d6871c54 title: "Challenge 270: Longest Common Substring" challengeType: 28 dashedName: challenge-270 --- # --description-- Given a string, return the longest substring that appears more than once. - The substrings can overlap. # --hints-- `getLongestSubstring("abracadabra")` should return `"abra"`. ```js assert.equal(getLongestSubstring("abracadabra"), "abra"); ``` `getLongestSubstring("hello world hello")` should return `"hello"`. ```js assert.equal(getLongestSubstring("hello world hello"), "hello"); ``` `getLongestSubstring("mississippi")` should return `"issi"`. ```js assert.equal(getLongestSubstring("mississippi"), "issi"); ``` `getLongestSubstring("ha ha ha ha ha ha ha")` should return `"ha ha ha ha ha ha"`. ```js assert.equal(getLongestSubstring("ha ha ha ha ha ha ha"), "ha ha ha ha ha ha"); ``` `getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over")` should return `"the quick brown fox jumped over"`. ```js assert.equal(getLongestSubstring("the quick brown fox jumped over the lazy dog that the quick brown fox jumped over"), "the quick brown fox jumped over"); ``` # --seed-- ## --seed-contents-- ```js function getLongestSubstring(str) { return str; } ``` # --solutions-- ```js function getLongestSubstring(str) { let longest = ''; for (let len = str.length - 1; len >= 1; len--) { for (let i = 0; i <= str.length - len; i++) { const sub = str.slice(i, i + len); if (str.indexOf(sub) !== str.lastIndexOf(sub)) { return sub; } } } return longest; } ```