Tips for incorporating an algorithm to identify whether a number contains 2 consecutive digits

Looking to create a function that can determine if a number contains consecutive digits:

For example:

  • If the input is 11, it will return true
  • If the input is 21, it will return false
  • If the input is 323, it should return false because even though there are repeated numbers, they are not consecutive

Currently, I am converting the number into an array and iterating through it one by one to check for consecutive digits. However, this approach has a time complexity of O(n). If anyone has alternative solutions with better efficiency, please share.

Thank you!

Answer №1

Consider an alternative approach that eliminates the need to convert the number into a string or array of numbers/characters. Here's how it works:

  1. Start by setting a variable curr to -1.
  2. Implement a loop with the condition while num > 0 and execute the following steps:
  • next_curr = num % 10
  • if next_curr == curr: return true
  • curr = next_curr
  • num = num / 10 (using integer division)
  1. If the loop finishes, return false.

This algorithm operates in a single pass with time complexity of O(log n), where n represents the input number. The space complexity is O(1).

It's worth noting that while your initial algorithm also had a time complexity of O(log n), it required 2 passes and had a space complexity of O(log n).

While I haven't coded in JavaScript recently, below is a possible JS implementation of this algorithm:

function sameAdjacentDigits(num) {
    // Handle negative numbers and prevent potential issues when using Math.floor later on
    num = Math.abs(num)
    let curr = -1
    while (num > 0) {
        const nextCurr = num % 10
        if (nextCurr == curr) return true
        curr = nextCurr
        num = Math.floor(num / 10)
    }
    return false
}

Answer №3

The simplest method to achieve this is through the use of regular expressions. Although the efficiency of the algorithm is not certain, a potential solution could be

/(\d)\1/

Answer №4

Based on the idea presented by @Tschallacka's response:

const values = [12,34,56];

const output = values.map(val=>{
  const check = val.toString().match(/(00|11|22|33|44|55|66|77|88|99)/);
  return check !== null;
})

console.log(output);

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

Update class name in React component based on state change

My current setup involves the setting of active and class flags as shown below: constructor(props) { super(props); this.state = {'active': false, 'class': 'album'}; } handleClick(id) { if(this.state.active){ this.s ...

Tool to insert content into the initial subdirectory

My goal is to develop a bookmarklet that can add text after the main domain but before any subpath. For example: http://example.com/home/start -> http://example.com/text/home/start I am considering storing the full path, removing the domain, replacing ...

Trouble with npm installation on Windows following node update

After updating my Node.JS last night, my npm install function stopped working. I tried uninstalling and reinstalling Node, but it didn't solve the issue. My system is running on Windows 8.1 with Node version 8.9.4 and NPM version 3.3.12. The error mes ...

Transforming business entities into JSON format

Currently, I am facing a challenge with serializing my business objects into JSON for use in a JavaScript application. My main concern is maintaining the purity of my business objects by keeping them unaware of data access or persistence. Introducing a toJ ...

Ways to transmit data from PHP to JavaScript

I have a file called "hotlaps.php" where I've created a JavaScript script: echo "<body onload=\"myFunction(".$array_1.",".$array_2.",".$array_3.");\">"; In my "hotlaps.js" file, I have the following function: function myFunction(arr ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Adding fields to all objects in an array within MongoDB

I'm trying to update all objects in an array by adding a new field only if it doesn't already exist. I attempted to use the updateMany method but it doesn't seem to be working. Can someone please assist me? const updateResult = await Form.up ...

Dealing with forms in Next.js with TypeScript and server-side actions - Oops! Error: e._formData.get is not a recognized function

I am currently working on managing form submissions in a Next.js 14 server action, using TypeScript within my project. I have implemented FormData to collect form data but encountered an issue: Error: e._formData.get is not a function. Below is the code s ...

Remove the Prisma self-referencing relationship (one-to-many)

I'm working with this particular prisma schema: model Directory { id String @id @default(cuid()) name String? parentDirectoryId String? userId String parentDirectory Directory? @relation("p ...

The jqgrid hidden grid is causing data duplication and the vertical scroll is covering up the information

Using jqgrid 4.4.4 has presented a challenge that I've encountered. Issue Resolved Scenario My goal is to hide jqgrid on startup without causing data duplication. Solution Found Eliminating scroll:true prevented the data from duplicating as it di ...

Error: The property 'inputItem' is not recognized on type 'EventTarget' - Utilizing Semantic-Ui, React, and Typescript

Currently, I'm utilizing React, Typescript, and Semantic UI react components. My aim is to clear the input field after successfully adding an item. While debugging, I've noticed the event.currentTarget.inputName.value which I wish to set to an em ...

Extracting data from a JSON file and displaying it using Angular

I'm facing a challenge with parsing two JSON format data and displaying them in Angular. I'm unsure of how to proceed and need guidance. The second data includes a plan_id that refers to the "plan" data. How can I create a small lookup object to ...

Retrieving information from a local JSON file in Vue.js using the jQuery $.getJSON() method

Currently, I am in the process of developing a demo application using Vuejs which involves extracting map data from a local .json file. The extracted data is then used to obtain specific information like latitude and longitude values that are necessary for ...

Is there a way to determine if the value of an array has not been defined?

When attempting to access the value of an array that does not exist, an error is thrown stating "variable is not defined." Consider the following example: var arr = new Array(); arr['house']['rooms'] = 2; Using the following check: ...

Function in Typescript that accepts either a single object or an array of objects

We frequently use a simple function declaration where the function can accept either a single object or an array of objects of a certain type. The basic declaration looks like this: interface ISomeInterface { name: string; } class SomeClass { pu ...

Encountering an error message while starting up a Node Express server

Hello everyone, I am currently new to webpack and attempting to run my own server using 'node server.js'. However, I encountered an issue with the following error message: $ node server.js /path/to/server.js:3 import path from 'path' ^ ...

The initial return value of $(document).height may be inaccurate, but is accurate upon recalculation

I am working on implementing a pop-up screen and I would like to darken the background when it opens. Below is the Javascript code: $(document).on('click', '.item', function(){ $("#popUp").css("display" , "block"); ...

Is there a way to completely remove an element from the dom once the ajax call has returned

I've been struggling to completely remove LI elements and their content, including the checkbox input, from the DOM without success. After an ajax callback, I am calling the following function, but it only removes the contents and not the element its ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Is it safe for me to assume that mobile browsers that have JavaScript enabled will also be able to

While acknowledging that providing a definitive answer to this question may be challenging, I am wondering: Is it feasible to assume that mobile browsers with JavaScript capabilities can successfully manage jQuery? Specifically, basic functions like click ...