Searching for the length of the greatest substring comprised of distinct characters in JavaScript

Seeking a solution to the problem of finding the longest sub-string within a string that does not contain any repeating characters. I am facing an issue with my code when trying to handle the input "dvdf". Below is the code that I have written:

function lengthOfLongestSubstring(check) {
    var letters = check.split("");
    var max = 0;
    var result = [];
    for (var i = 0; i < letters.length; i++) {
        var start = i
        if (result.indexOf(letters[i]) === -1) {
            result.push(letters[i])
        } else {
            i = i - 1
            result = []
        }
        if (max === 0 || max < result.length) {
            max = result.length
        }
    }
    return max
}

Answer №1

For the input string "dvdf", this particular approach provides the correct output.

The algorithm involves adding characters to the current_string until a duplicate is encountered. Upon finding a duplicate, the current_string is trimmed from the point of duplication. The variable max keeps track of the maximum length that current_string has achieved at any given moment. This method appears logically sound and yields the expected results.

function lengthOfLongestSubstring(string) {
    var max = 0, current_string = "", i, char, pos;

    for (i = 0; i < string.length; i += 1) {
        char = string.charAt(i);
        pos = current_string.indexOf(char);
        if (pos !== -1) {
            // Trim "dv" to "v" upon encountering another "d"
            current_string = current_string.substr(pos + 1);
        }
        current_string += char;
        max = Math.max(max, current_string.length);
    }
    return max;
}

lengthOfLongestSubstring("dvdf"); // Length will be 3

In each iteration, the value of current_string progresses as follows: "", "d", "dv", "vd", "vdf".

Answer №2

Instead of using an array to store results, you can opt for a map that keeps track of the last index for each character encountered. This allows you to optimize the loop by jumping back to one after the last index of a repeated character and continuing the search from there. By doing so, you avoid simply restarting from the current position which may not work in certain scenarios like in the case of 'dvdf':

Here is the modified code incorporating the use of a map:

function lengthOfLongestSubstring(check) {
  var letters = check.split("");
  var max = 0;
  var result = new Map();
  var start = 0;
  
  for (var i = 0; i < letters.length; i++) {
    if (!result.has(letters[i])) {
      result.set(letters[i], i);
    } else {
      i = result.get(letters[i]);
      result.clear();
    }
    
    if (max < result.size) {
      max = result.size;
    }
  }
  return max;
}

// Example:
console.log(lengthOfLongestSubstring("dvdf")); // 3

Answer №3

In order to solve this problem, we can implement a solution using the concept of Sliding Window along with a HashMap.

const findLengthOfLongestSubstring = (str) => {
  if (!str.length || typeof str !== 'string') return 0;

  if (str.length === 1) return 1;
  
  let charMap = {};
  let longestSubstringLength = 0;
  let start = 0;
  
  for (let i = 0; i < str.length; i++) {
    if (charMap[str[i]] !== undefined && charMap[str[i]] >= start) {
      start = charMap[str[i]] + 1;
    }
    
    charMap[str[i]] = i;
    longestSubstringLength = Math.max(longestSubstringLength, (i - start + 1));
  }

  return longestSubstringLength;
}

Answer №4

After some brainstorming, I came up with a simpler approach:

function findLongestSubstr(input) {
    let start = 0;
    let maxLength = 0;
    let seenChars = new Set();

    for (let end = 0; end < input.length; end++) {
        while (seenChars.has(input[end])) {
            seenChars.delete(input[start]);
            start += 1;
        }
        seenChars.add(input[end]);
        maxLength = Math.max(maxLength, end - start + 1);
    }

    console.log(seenChars);
    return maxLength;
}

console.log(findLongestSubstr('abcaabcad')); //4

Answer №5

On the date of January 7th, 2021, this particular Leetcode problem was featured as the question of the day. Initially, my approach closely resembled the chosen solution. While the performance was acceptable, I decided to delve into the answer solution documentation out of curiosity. After studying examples exclusively in Java and Python, I opted to rewrite my code using the sliding window technique. This change yielded a slightly more efficient outcome - with an execution time of 144ms as opposed to the original 160ms, along with a reduced memory footprint of 42mb compared to the initial 44.9mb:

function lengthOfLongestSubstring(s: string): number {
    let stringLength = s.length;
    let maxLength = 0;
    const charMap = new Map();
    let pos = 0;

    for (let i = 0; i < stringLength; i++) {
        if (charMap.has(s[i])) {
            pos = Math.max(charMap.get(s[i]), pos);
        }

        maxLength = Math.max(maxLength, i - pos + 1);
        charMap.set(s[i], i + 1);
    }
    return maxLength;
}

console.log(lengthOfLongestSubstring("dvdf"));

Answer №6

Give this a try:

function findLongestNonRepeatingSubstring (inputString) {
  const charMap = new Map();
  let maxLength = 0;
  let leftIndex = 0;
  
  for (let rightIndex = 0; rightIndex < inputString.length; rightIndex++) {
    const currentChar = inputString[rightIndex];
    
    if (charMap.get(currentChar) >= leftIndex) {
      leftIndex = charMap.get(currentChar) + 1;
    } else {
      maxLength = Math.max(maxLength, rightIndex - leftIndex + 1);
    }
    
    charMap.set(currentChar, rightIndex);
  }
  
  return maxLength;
}

Answer №7

It is important to note that resetting the variable "i" to "i - 1" may not be the correct approach in this scenario. Another loop inside the for loop might be necessary. Consider the following example code snippet (please verify the index carefully).

function findLongestDistinctSubstring(input){
    var characters = input.split("");
    var maxLength = 0;
    
    for (var i = 0; i < characters.length; i++) {
        var uniqueChars = [];
        var j = i;
        
        for(;j < characters.length; j++) {
            if (uniqueChars.indexOf(characters[j]) === -1) {
                uniqueChars.push(characters[j]);
            } else {
                break;
            }        
        }
        
        if(j - i > maxLength) {
            maxLength = j - i;
        }
    }
    
    return maxLength;
}

Answer №8

A useful strategy to tackle this issue is by employing the sliding window pattern.

function findMaxLength(str) {
  let maxLength = 0;
  let maxSubstr = "";
  let seenChars = {};
  let startIndex = 0;
  let nextIndex = 0;

  while (nextIndex < str.length) {
    // Extract current character from string
    let character = str[nextIndex];

    // Check if character already exists in map
    if (seenChars[character]) {
      // Determine whether start index exceeds last index of current character
      startIndex = Math.max(startIndex, seenChars[character]);
    }

    // Compare lengths of new substring and previous substrings
    if (maxLength < nextIndex - startIndex + 1) {
      maxLength = nextIndex - startIndex + 1;
      // Capture slice of longer substring
      maxSubstr = str.slice(startIndex, nextIndex + 1);
    }
    // Update index of current character
    seenChars[character] = nextIndex + 1;
    // Move to the next character
    nextIndex++;
  }

  console.log(str, "->", maxSubstr, "->", maxLength);
  return maxLength;
}

findMaxLength("dvdfvev");
findMaxLength("hello");
findMaxLength("1212312344");

Answer №9

Discovering the Longest Unique Substring with Map Method

let inputString = "aaabcbdeaf";
let startingIndex = 0;
let charMap = new Map();
let maxSubStringLength = 0;
let longestSubstring = '';

for(nextCharIndex=0; nextCharIndex< inputString.length ; nextCharIndex++){
if(charMap.has(inputString[nextCharIndex])){
  charMap.set(inputString[nextCharIndex],charMap.get(inputString[nextCharIndex])+1);
  startingIndex = Math.max(startingIndex,charMap.get(inputString[nextCharIndex]));
}
if(maxSubStringLength < nextCharIndex-startingIndex+1){
  maxSubStringLength = nextCharIndex-startingIndex+1;
  longestSubstring = inputString.slice(startingIndex,nextCharIndex+1);
}
 charMap.set(inputString[nextCharIndex],nextCharIndex);
}
console.log(longestSubstring);

Answer №10

If you're looking for a solution, here is one way to approach it:

function findLongestSubstring(str) {
  const substrings = []
  const strLength = str.length
  const addSubstring = (value) => {
    if (value !== '') {
      if (substrings.length > 0) {
        if (substrings.indexOf(value) === -1) {
          substrings.push(value)
        }
      } else {
        substrings.push(value)
      }
    }
  }
  addSubstring(str)
  for (const [index, value] of str.split('').entries()) {
    let length = strLength
    let substringStr = str
    const indexOffset = str.indexOf(value)
    addSubstring(value)
    while (length > indexOffset) {
      addSubstring(substringStr.slice(index-1, length + 1))
      length = --length
    }
    substringStr = str.slice(index, strLength)
  }
  substrings.sort()
  return substrings.pop()
}

console.log(findLongestSubstring('banana'))
console.log(findLongestSubstring('fgjashore'))
console.log(findLongestSubstring('xyzabcd'))

Answer №11

Discover the maximum length of a unique substring without relying on MAP(). Utilize simple slice() instead. This same technique can also be applied to find the longest unique string.

Just swap out "return max => return str"

const sampleString = "dvdf";;

var getLongestUniqueSubstring = function() {
if(sampleString.length == 1) return 1;
if(sampleString.length == 0) return 0;

let max = 0,i =  0, str = "";

while(i < sampleString.length){
    const index = str.indexOf(sampleString.charAt(i));
    if(index > -1) {
        // s = "fiterm".slice(1,4) => ite
        str = str.slice(index + 1, sampleString.length);
    }
    str += sampleString.charAt(i);
    max = Math.max(str.length, max);
    i++;
}
  return max;
};

Answer №12

Find the longest substring without repeating characters:

function findLongestUniqueSubstring(inputString) {
    if(inputString.length < 2) {
        return inputString.length;
    }
    
    let longestLength = 1;
    let currentSubstr = '';
    
    for(let i = 0; i < inputString.length; i++) {
        if(currentSubstr.includes(inputString.charAt(i))) {
           let firstIndex = currentSubstr.indexOf(inputString.charAt(i));
            currentSubstr = currentSubstr.substring(firstIndex + 1, currentSubstr.length);   

        }
          currentSubstr += inputString.charAt(i);
          longestLength = Math.max(currentSubstr.length, longestLength);
    }
     
    return longestLength;
};

Answer №13

Utilizing the reduce function for a concise solution.

const findUniqueSubstring = str => [...str].reduce((prev, current) => ( prev.includes(current) ? (prev += current, prev.substr(prev.indexOf(current)+1)) : prev += current),'');
console.log(findUniqueSubstring('abacdbef').length);

Answer №14

function findLongestUniqueSubstring(input: string): number {
  const charArray = input.split("");
  let longestLength = 0;
  const uniqueSet: Set<string> = new Set();
  
  for (let index = 0; index < charArray.length; index++) {
    uniqueSet.add(charArray[index]);
    let tryIndex = index + 1;
    
    while (charArray[tryIndex] && !uniqueSet.has(charArray[tryIndex])) {
      uniqueSet.add(charArray[tryIndex]);
      tryIndex++;
    }
    
    if (uniqueSet.size > longestLength) {
      longestLength = uniqueSet.size;
    }
    
    uniqueSet.clear();
  }

  return longestLength;
}

Answer №15

After thinking about it for a while, I decided to share my approach because I believe it offers an innovative way to solve this problem. Instead of using if/else blocks, I utilized the substring.indexOf() method to search for matching string characters in an array and remove indexes up to, and including, the match (+1). If no match is found, indexOf() returns -1 which, when added to +1, results in a .splice(0,0) operation that does nothing. The final Math check takes into consideration the addition of the last character in the loop to determine the higher outcome.

const findSubstring = input => {
let substring = [];
let maxLength = 0;
for (let i = 0; i < input.length; i++) {
    maxLength = Math.max(substring.length, maxLength);
    substring.splice(0, substring.indexOf(input[i]) + 1);
    substring.push(input[i]);
}
maxLength = Math.max(substring.length, maxLength);
return maxLength;
}

Answer №16

employs the concept of a sliding window

function findLongestDistinctSubstring(inputString) {
  var characters = inputString.split("");
  var substring = "";
  var result = [];
  var length = 0;
  let maxLength = 0;

  for (var index = 0; index < characters.length; index++) {
    const pos = result.indexOf(characters[index]);
    if (pos === -1) {
      result.push(characters[index]);
      length += 1;
    } else if (characters[index]) {
      result = result.splice(pos + 1);
      length = result.length + 1;
      result.push(characters[index]);
    }
    maxLength = length > maxLength ? length : maxLength;
  }
  return maxLength;
}

console.log(findLongestDistinctSubstring("example"));

Answer №17

Sliding Window Algorithm with O(n) Time Complexity

  • To implement this algorithm, you can utilize either a hash table or a Map data structure.
  1. Iterate through each character in the string.
  2. Maintain a dictionary to keep track of unique characters encountered.
  3. If a character already exists in the dictionary, update the count and reset the dictionary. Update the longest substring length accordingly.
  4. Restart from the index after the first occurrence of the repeated character.

var lengthOfLongestSubstring = function(s) {
    if(s.length<2) return s.length;
    let longest = 0;
    let count=0;
    let hash={}
    for (let i = 0; i < s.length; i++) {
       //If char exist in hash
        if(hash[s[i]]!=undefined){
            i=hash[s[i]];
            hash={}
            longest = Math.max(longest, count);
            count = 0;
        }else{
            hash[s[i]]=i
            count = count+1;
        }
        
    }
    return Math.max(longest, count);
};

console.log(lengthOfLongestSubstring("abcabcbb"))
console.log(lengthOfLongestSubstring("au"))

Answer №18

Give this a try:

function checkLongestSubstring(str) {
    let longest = "";
    for (let i = 0; i < str.length; i++) {
        if (longest.includes(str[i])) {
            return longest.length
        } else {
            longest += str[i];
        }
    }
    return longest.length;
}

console.log(checkLongestSubstring("abcabcbb"));
console.log(checkLongestSubstring("bbbbb"));
console.log(checkLongestSubstring("abcdef"));
console.log(checkLongestSubstring(""));

Answer №19

// ZXKJKKLPPXTVBVSQW -> JKLP

const findLongestUniqueSubstring = (str) => {
  let uniqueString = str;
  const pattern = /(\w+)\1+/g;
  const matches = [...str.matchAll(pattern)].map((p) => p[1]);
  if (matches.length > 0) {
    uniqueString = uniqueString.replace(pattern, '_');
    let strArray = uniqueString.split('_');
    let longestUniqueSubstr = strArray.reduce((a, b) =>
      a.length > b.length ? a : b
    );
    for (let i = 0; i < matches.length; i++) {
      let long1 = `${matches[i]}${longestUniqueSubstr}`;
      let long2 = `${longestUniqueSubstr}${matches[i]}`;
      if (str.indexOf(long1) > -1) {
        return long1;
      } else if (str.indexOf(long2) > -1) {
        return long2;
      }
    }
    return '';
  }
  return '';
};
const runTestCases = (func, result) =>
  func == result ? 'test passed' : `test failed. expected results : ${result}`;

console.log(findLongestUniqueSubstring('ZXKKIOQPGTAYNSCF'));

console.log(
  runTestCases(
    findLongestUniqueSubstring('ABXFGHIKCDDDEFGHI'),
    'ABXFGHIKCD'
  )
);
console.log(
  runTestCases(findLongestUniqueSubstring('AJAGOPPQE'), 'AGOPPQE')
);

Answer №20

the issue arises with the input string "pwwkew"

function checkLengthOfLongestSubstring(input) {
    let result = "";
    for (let i = 0; i < input.length; i++) {
        if (result.includes(input[i])) {
            return result.length
        } else {
            result += input[i];
        }
    }
    return result.length;
}

console.log(checkLengthOfLongestSubstring("abcabcbb"));
console.log(checkLengthOfLongestSubstring("bbbbb"));
console.log(checkLengthOfLongestSubstring("abcdef"));
console.log(checkLengthOfLongestSubstring(""));

Answer №21

Finding the Longest Substring Without Repeating Characters - using our own logic

// defining an input string
let strInput = "pwwkew";

// initialize result with the first character of input string
let result = strInput[0];
let isRepeated;

// function to check if a character exists in the result substring
let doesCharExistInResult = (result, strInput) => {
    for(let index = result.length-1; index >= 0; index--){
        if(result[index] == strInput){
            return true;
        }
    }
}

let findLongestSubstringWithoutRepeats = (strInput) => {
    for(let pos = 1; pos < strInput.length; pos++){
        if(result[0] != strInput[pos]){
            if(result.length == 1){
                result += strInput[pos]
            }
            else {
                isRepeated = doesCharExistInResult(result, strInput[pos]);
                if(isRepeated != true) {
                    result += strInput[pos]

                }
            }
        }
    }
    return result;
};

console.log(findLongestSubstringWithoutRepeats(strInput));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting problem with the Node and Mongoose update function

I am looking to update a document that has already been queried: The method of saving in memory seems to be working well: project.likers.push(profile.id); project.set({ likes: project.likes + 1 }) await project.save(); However, I came across a blog p ...

Retrieve JSON data within a service and provide it to a component

I am currently facing an issue with loading data from a JSON file into my component using a service. The data is successfully loaded in the service, as confirmed by the console log; however, when trying to access the data in the component, it does not disp ...

Is it possible to smoothly transition to the next step in PLAYWRIGHT testing if a button click is not an option?

My question is whether it's possible to attempt a click action on a button, and if the button is not present on the page, have the test skip that action without getting stuck or throwing an error, and continue to the next one. To provide more context, ...

Exploring the integration of Styled-components in NextJs13 for server-side rendering

ERROR MESSAGE: The server encountered an error. The specific error message is: TypeError: createContext only works in Client Components. To resolve this issue, add the "use client" directive at the top of the file. More information can be found here i ...

What is the best method for combining ajax and php to perform a redirect?

I'm facing an issue with redirecting users from the login page to their profile page. I'm using ajax to validate the form, but upon successful login, the profile page is displayed on top of the index page. How can I ensure that the redirection ha ...

Choosing a line object with the mouse in Three.js

How can I select a line object in threeJS? I attempted to use raycaster for this purpose. http://jsfiddle.net/nelsonlbtn/z43hjqm9/43/ Upon running the test, I encountered the following error: three.min.js:598 Uncaught TypeError: d.distanceTo is not a f ...

Quirky rendering problem in AngularJS

My issue involves creating blocks using data from a JSON file, which includes a background-image path for a div. Here is an example snippet: [ .. { .. .. "smallimg": "../assets/images/dummy/dummy-intro-1.jpg", .. ] On my page, I hav ...

Discover the dynamic method for determining the value of a nested array based on a specific condition

Currently, I am delving into the world of nested arrays and attempting to locate a specific value within the array based on a condition. The data returned by the API is structured in the following format: data= { "ch_Id": "1234", "title": "Title" ...

Querying MongoDB to locate books by the same author or those that are categorized in at least one similar category

Looking to discover books by the same author or with at least one matching category. This is how my Book Schema looks: const bookSchema = new Schema( { title: { type: String, required: true }, author:{ ...

Robotic Arm in Motion

GOAL: The aim of the code below is to create a robotic arm that consists of three layers (upper, lower, and middle), all connected to the base. There are four sliders provided to independently move each part except for the base which moves the entire arm. ...

Hover-over functionality not functioning properly on select images

My website, located at , is fully functional. When you visit the homepage, you will see some words that turn black when you hover over them. I recently switched this site, which was originally created in Dreamweaver, to Umbraco, a .net based CMS. My site ...

The Dropdown Menu is displaying correctly in Chrome, but is being obscured by an image in Safari

While the Nav dropdown menu functions correctly in Chrome, an issue arises in Safari where the image covers the rest of the menu. This discrepancy between browsers is puzzling. Why does this problem only occur in Safari when it displays properly in Chrome? ...

Deleting elements from arrayA that do not exist in arrayB using JavaScript

Seeking guidance on a small project of mine. For example, I have these two arrays: chosenItems = ['apple', 'banana', 'cherry', 'date', 'kiwi'] availableFruits = ['apple', 'cherry', &ap ...

What steps should be taken to resolve the error message "EROFS: read-only file system, attempting to open '/var/task/db.json'?"

const jsonServer = require('json-server') const cors = require('cors') const path = require('path') const server = jsonServer.create() const router = jsonServer.router(path.join(__dirname, 'db.json')) const middlewa ...

Determine the width of a dynamically generated div element in JavaScript using the createElement method

Currently, I am utilizing the JavaScript function createElement to generate a new div element and then assigning its innerHTML. Following that action, I am attempting to determine the necessary width required to display the div with all of its content. var ...

Troubleshooting: The issue with json_encode in Ajax calls

I am facing an issue with my ajax call and the json response. The console is indicating that my php file is not returning a json format, but I am unable to pinpoint the exact reason behind it. Below is my ajax function: function showEspece(espece, categori ...

Is anyone else experiencing issues with the Express middleware that checks for IDs? Looking for suggestions on how to fix

Currently working on a project with Node js utilizing Express and MongoDb for the backend. In this project, USERS have the ability to post COMMENTS, so I have created a middleware to access the DELETE route and check if the USER ID matches the ID of the in ...

Choose the following span tag that comes after a specific HTML element using Jquery

I am attempting to locate the following span element with the class name slider-value after a specific HTML element has been selected. I have tried several solutions, but none of them seem to be working. While I could target it by utilizing the id, I pref ...

Execute a middleware prior to running the Nest Js ServeStaticModule command

Is there a way to execute middleware before Nest JS serves my React application through the ServeStatic Module? I've attempted using both a Nest middleware and Global middleware, but they only seem to work for static routes such as '/'. mai ...

AWS: Grant access to designated clients for users

My AWS Cognito setup includes: AWS Cognito User Pool: UserPool_1 The User Pool contains 3 users: Mike, Sarah, John I have configured 3 App Clients under this user pool: WebClient_1 WebClient_2 WebClient_3 I need Mike to be able to access: WebClient_ ...