Cracked Code at Position 880 (LeetCode)

Given an encoded string S, the decoded string is determined by reading each character and following the steps below:

  • If the character is a letter, it is written directly onto the tape.
  • If the character is a digit (denoted as d), the current tape is repeated d-1 more times in total.

The task is to find and return the K-th letter (1 indexed) in the decoded string for a given encoded string S and index K.

I have attached my solution which shows different output compared to the expected result. Can anyone please suggest what changes need to be made in my solution? Thank you in advance.

INPUT
decodeAtIndex ("vzpp636m8y", 2920)
Expected Output: "z"
Output I received: "p"


var decodeAtIndex = function(S, K) {
    let res = '';
    let hasNumber = false;
    let number = '';
    let i = 0;
    
    while((i < S.length)) {
          if(S[i] < 10) {
              number = number + S[i];
              hasNumber = true;
              while(S[i + 1] < 10) {
                    number = number + S[++i];
              }
          }
        
        if (hasNumber) {
           let repeat = res.repeat(parseInt(number - 1));
            res = `${res}${repeat}`; 
            hasNumber = false;
            number = '';
        } else {
            res = `${res}${S[i]}`;            
        }
        i++;
    }    
    return res[K - 1];
    
};

Answer №1

Your code is correct except for the typo parseInt(number - 1), where you are performing subtraction before parsing.

The problem was misunderstood by you. It clearly states that if a digit d is found, the tape should be repeated up to that point another d - 1 times. Not the number itself. For instance, a222 should not be translated as

repeat('a', 222)

instead, it should be

repeat(repeat(repeat('a', 2), 2), 2) = repeat('a', 8)

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

I am having an issue with jQuery's remove() function where it does not remove an element on the first attempt, even though the element

I am encountering an issue with an ajax call where the content is loaded into a specific div with async set to false. Within this content, there is a button with the id 'cancelbtn'. The problem arises when I try to remove this button using $(&apo ...

Having trouble with your AngularJS ng-repeat functionality?

As a newcomer to AngularJs, I am still grappling with the basics. Currently, I am using the Soundcloud API to retrieve a list of followers for a specific user. In my $scope.init function, I have managed to establish a connection with Soundcloud, authentica ...

Why is the time input field in AngularJS programmed to expect a date instead?

When booking, I stored the time using $filter('date')($scope.booktime, 'mediumTime'). After booking, I have an editbooking function where I pass the time and encounter an error in the console: Error: [ngModel:datefmt] Expected 11:59:00 ...

Having trouble with the JsonLoader copied from Threejs.org?

I've been trying to make use of a JSONLoader from threejs.org, but I'm facing some issues. Three.js seems to be functioning properly because I can easily create a cube. However, when I attempt to load a js file through the JSONLoader, nothing hap ...

Tips for aligning the arrow of a dropdown menu option

When examining the code provided, I have noticed the clr-select-container with specific attributes as depicted. In the screenshot attached, it displays the clr-select-container. The issue that I am encountering is that the inverted arrow is positioned a f ...

Analyzing different kinds of inputs received by a function

Let's say we have the following abstractions for fetching data from an API: Data storage class class DataItem<T> { data?: T | null } Query function function queryData ( fn: () => Promise<any> item: DataItem<any> ...

What could be causing the issue with my dependency injection in my Angular application?

Let's get started angular.module('app', [ 'ngCookies', 'ngResource', 'ngSanitize', 'ngRoute' ]) This is my simple factory. Nothing fancy here angular.module('app') .factory(&apos ...

Vue Application experiences issues resizing Three.js Animation in Canvas

Currently, I am deep diving into learning Three.js within a Vue.js component. Take a look at my code snippet: <script> import * as THREE from "three"; export default { name: "Scene", mounted() { this.initializeThree(); ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

Create a dynamic HTML page using JavaScript

When I click on the following links: How can I create a new page using JavaScript? Create and dynamically append elements I'm looking to dynamically add HTML elements with JavaScript within a div, but I don't want my code to become overly comp ...

External IPs cannot access Node.js

I am facing an issue with my Amazon EC2 Server where I have set up a node js server. It is not accessible from the outside using the public DNS, but it can be accessed from the same instance (localhost). Any assistance in resolving this problem would be gr ...

Tips for modifying the size and color of a Material UI icon

Utilizing the CircularProgress-Icon component from Material UI, I'm interested in modifying the size and color attributes. Below is the code snippet in question: size color The snippet of code in question appears as follows: const useStyles = makeSt ...

Starting a typescript class with an already existing object - a step-by-step guide

Although my question may seem similar to previous ones, I have not found the answer I am looking for, so I am posting it here. Here is my example: Class A{ id:number; name:string; } Class B{ id:number; name:string; age:number; grade:number; } ...

Tips for linking weight scale device to a website

I recently developed a web application that calculates the weight of products. The application was created using PHP, JavaScript, and AJAX, running on a XAMPP server. Now my client is requesting for me to integrate a weight scale machine into the applica ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...

Is there a way to prevent certain folders that have .vue files from being included in the VueJS build process?

https://i.sstatic.net/YU1rB.png module.exports = { presets: [ '@vue/app' ], module:{ rules: [ { test: /\.vue$/, exclude: [ './src/components/Homepages/number1', './src ...

Utilizing the power of JavaScript in an HTML file to develop a straightforward price calculator

I am new to the world of HTML coding and currently working on an assignment for my online computer course. I reached out to my professor for help, but unfortunately, he hasn't been very responsive. The task at hand is to create a basic cost calculator ...

Prevent unnecessary re-renders of components by optimizing state changes with hooks

In my Layout component, there is a Table component with an Entry component for each row. Each row can be selected, and when a row is selected, it is added to the state so that all selected entries can be sent to a REST service later using a button. The i ...

At compile time, Typescript runs smoothly, but errors may arise during runtime

Currently, I am delving into learning Typescript and have encountered a snag in my code. Despite searching extensively for a solution, I have been unable to find any relevant material pertaining to my issue. Below is the code snippet in question: <code ...

How to obtain the height of the parent screen using an iframe

Imagine a scenario where a div contains an image that is set to perfectly fit the height of the screen. This setup works flawlessly, with one exception - when placed within an iframe, the height of the div adjusts to match the content's height rather ...