How can I efficiently locate identical sequences of cells in two or more arrays?

Unique Example 1

We can explore an interesting scenario by considering two arrays:

('m','o','o','n','s','t','a','r','d')
('s','t','a','r','d')

Let's search for matching sequences between the two arrays that are not part of longer matches. Here is what we found:

('s','t','a','r','d') = position 5 in array 1 and position 0 in array 2

Array 1: ('m','o','o','n','s','t','a','r','d')

Array 2: ('s','t','a','r','d')

Unique Example 2

('m','o','o','n','s','t','a','r','d')
('s','t','a','r','d')

In this case, we have shorter matching sequences:

('s','t','a','r','d') = position 5 in array 1 and position 0 in array 2

Array 1: ('m','o','o','n','s','t','a','r','d')

Array 2: ('s','t','a','r','d')

Overall Overview

Both examples showcase multiple matches, all contained within larger matches in at least one of the arrays.

If you're seeking efficient code (a balance of low memory consumption and high speed suitable for mobile devices), JavaScript implementations would be very beneficial!

Answer №1

My attempt at implementing a general LCS algorithm in JavaScript, with a time and space complexity of O(mn). By iterating row by row, we are able to optimize space usage by reusing only two rows and copying the second row to the first once it's processed.

var example1 = [['n','v','a','n','i','n','n','v','a','n'],
               ['a','n','n','n','v','a','n','v','n']],

    example2 = [['n','v','a','n','i','n','n','v','i','n'],
               ['a','n','i','n','v','i','n','v','n']];

function findLCS(arr){
  var M = new Array(arr[0].length),
      result = [];

  for (var i=0; i<arr[0].length; i++){
    M[i] = new Array(arr[1].length).fill(0);

    for (var j=0; j<arr[1].length; j++){
      if (arr[0][i] == arr[1][j]){
        M[i][j] = M[i-1] && M[j-1] ? 1 + M[i-1][j-1] : 1;
      }
      if ((i == arr[0].length - 1 || j == arr[1].length - 1) && M[i][j] > 2){
        result.push([i - M[i][j] + 1,j - M[i][j] + 1,M[i][j]]);
      } else if (i > 1 && j > 1 && M[i][j] < M[i-1][j-1] && M[i-1][j-1] > 2){
        result.push([i - M[i-1][j-1],j - M[i-1][j-1],M[i-1][j-1]]);
      }
    }
  }

  return result;
}

console.log(JSON.stringify(findLCS(example2))); // [[2,0,4],[6,3,4]]

Answer №2

If you have two arrays of lengths m and n, it seems that achieving better performance than O(mn) in general is highly unlikely. Consider arrays with alternating as but otherwise unique characters, such as:

[a, b, a, c, a, d, a, e, a, f, a, g]
[a, h, a, i, a, j, a, k, a, l, a, m]

The number of matches between these arrays is (m/2)*(n/2). To find all matches, the algorithm's complexity will likely be at least O(mn).

To achieve O(mn) time complexity, you can perform the following steps. Imagine sliding one array against the other like this:

[a, b, c, d, e]
            [f, g, h, i, j]

   [a, b, c, d, e]
            [f, g, h, i, j]

      [a, b, c, d, e]
            [f, g, h, i, j]

                  ...
                        [a, b, c, d, e]
            [f, g, h, i, j] 

There are m + n - 1 possible positions. At each position, you must iterate over pairs of aligned characters (usually no more than min(m, n)) to find the longest chains of matching characters. This results in a time complexity of

O((m + n) * min(m, n)) = O(mn)

This solution's drawback is that its time complexity depends mainly on the length of the arrays rather than their actual content. For instance, even if the arrays are identical, it still requires O(nm) time, although determining equality would only take O(n). As noted in another response, there exist smarter solutions that are significantly faster when dealing with fewer matching sequences.

Answer №3

Provided here is an optimal O(n+k) solution for comparing two strings A and B, with total length n and k maximal matching substrings:

  1. To begin, construct a generalised suffix tree using the strings A and B. This involves creating a standard suffix tree on the concatenated single string A$B#, where $ and # are unique characters absent from both A and B. Building this tree can be achieved in O(n) time employing algorithms like Ukkonen's.
  2. Subsequently, engage in a bottom-up depth-first search through the constructed tree while executing two tasks at each node:
    • Determine and record whether there are any leaf nodes corresponding to suffixes of A or B under the current node. (Try to figure out how to address this question specifically for a leaf node.)
    • If leaf nodes exist for both kinds of strings, and this condition does not hold true for any child nodes, identify and report the substring denoted by the current node as a potential match. If the same situation occurs for a child node as well, the substring represented by the parent node will be a subset of the child node's substring—emphasizing the need for maximum substrings only.

This method also extends smoothly to deal with scenarios involving multiple input strings greater than or equal to three: maintain and assess the set of input strings connected to leaves below the present node, triggering appropriate actions when this set reaches full capacity.

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

Help needed with using Regex to restrict the number of alphabetical characters allowed

Struggling with configuring RegEx's. Seeking guidance to create a RegEx with the following criteria: Only allow numbers (0-9) Allow a period (.), negative sign (-), plus sign (+), dollar sign ($), and comma (,) Do not permit any alphabetic characte ...

Leverage Jquery within the div element to manipulate the data retrieved from a post ajax request

On my one.jsp page, I have the following post code: $.post("<%=request.getContextPath()%>/two.jsp", { vaedre: fullDate} ,function(result){ $("#theresult").append(result); }); This code generates the followi ...

How can I retrieve a file from the www-directory using PhoneGap?

Despite trying various solutions to access a file in the www folder, none seem to work for me. I am testing the application on iOS with the iOS simulator. The specific file I want to access is test.txt located in the www folder. Here is my current appr ...

Is it possible to execute "green arrow" unit tests directly with Mocha in IntelliJ IDEA, even when Karma and Mocha are both installed?

My unit tests are set up using Karma and Mocha. The reason I use Karma is because some of the functionality being tested requires a web browser, even if it's just a fake headless one. However, most of my code can be run in either a browser or Node.js. ...

Inverting array - excluding the initial digit

One challenge I've encountered is with a programming exercise. The task requires inputting numbers and displaying them in reverse order. However, there seems to be an issue where the last entered number is not displayed. #include <iostream> #in ...

Create a layout with two rows of two buttons in HTML aligned to the right side while maintaining the left side's

I am currently working on designing a menu for my webpage that includes four buttons. My goal is to have two buttons displayed at the top of the page and two buttons displayed at the bottom. To achieve this, I have written the following CSS code: .navButt ...

Update google maps markers and infoBubbles dynamically with ajax

I am currently using asp mvc in conjunction with jquery and the google maps api to showcase and update various locations on a map. Main Objective: Utilize markers to mark multiple locations Display brief information about these locations using info ...

Challenges with implementing speech recognition within a React component's state

I've encountered an issue with the React library react-speech-recognition. When trying to modify the newContent state within useEffect, it ends up printing as undefined. Additionally, I'm facing a similar problem when attempting to update the sta ...

Uniform Image Sizes in Bootstrap Carousel (With One Exception)

I am encountering a JavaScript exception related to image size. I am trying to set a fixed size for the images in my carousel, allowing them to auto adjust or resize without concern for distortion or pixelation. I have experimented with max-width and widt ...

Collaborative JavaScript repository within the Websphere Liberty platform

Is it possible to utilize a JavaScript library (such as Dojo, JQuery, or other custom developed libraries) as shared libraries within a Websphere Liberty server? For instance, I am interested in storing the .js files in either C:\wlp\usr\sh ...

`Node.js encountering issues with undefined JSON Array values`

I am facing an issue while trying to extract an array of strings from a JSON file. Although I am able to successfully load the JSON array, I am encountering difficulties in accessing the actual data within it. The structure of my JSON file is as follows: ...

encountered net::ERR_EMPTY_RESPONSE while attempting to locate a CSS file within an AngularJS directive

Every time my webpage attempts to access the css file from a directive, I encounter a net::ERR_EMPTY_RESPONSE. I have implemented door3's on-demand css feature, which allows for lazy loading of css files only when necessary. This feature works flawle ...

Flask is failing to display AJAX data

Looking to embark on a Flask project involving sending an AJAX request. In the Flask code, I want to assign a variable to handle the request and display it on the page using a Jinja variable. Flask from flask import Flask,render_template,request app = Fla ...

Enhancing Efficiency and Optimization with jQuery

Recently delving into the world of jQuery, I have been on the lookout for ways to enhance the speed and performance of my code. If anyone has any tips or valuable resources that could aid me in this endeavor, I would greatly appreciate it. Thank you, Bev ...

Determine if the input text field contains any text and store it in a variable using jQuery

I'm working on a form that includes radiobuttons and textfields. To keep track of the number of checked radiobuttons, I use this code: var $answeredRadiobuttons = $questions.find("input:radio:checked").length; But how do I store the number of textf ...

Custom positioning of Mui Snackbar in V5

I've been attempting to position a Snackbar in the top right corner with some customization for the top property, but I'm struggling to get it to display correctly. Here's what I've tried: import React from "react"; import { ...

Utilizing jQuery grep() to sort through a JSON array

Despite my attempts to find a suitable example on this platform, I am still struggling to adapt them to my specific needs. Essentially, all I require is to filter some JSON results using the grep() function. Here is the JSON data that I am working with: ...

Populate a select list in real time with dynamically generated options

I'm facing a challenge at the moment; I am using JavaScript to dynamically generate select boxes, however, I require Ajax to populate them with options. At the moment, my code is returning undefined and I am unsure of how to proceed. While my PHP succ ...

What's the best way to manage endless routing options in express.js?

After reviewing the topic of handling routes in Express.js on Stack Overflow, I came across the following example : var express = require("express"); var app = express(); app.get("/", function(request, response) { response.send(&quo ...

Tips for effectively exchanging information among angular services

Currently, I am in the process of refactoring a complex and extensive form that primarily operates within a controller. To streamline the process, I have started segregating related functions into separate modules or services. However, I am grappling with ...