A method for reversing specific characters within lengthy strings

I'm currently tackling a coding problem:

For a given string s and an integer k, the task is to reverse the first k characters for every 2k characters starting from the beginning of the string.

If there are less than k characters remaining, reverse all of them. If there are between k and 2k characters left, only reverse the initial k characters and keep the rest unchanged.

I managed to create a program that successfully handles 45 out of the 60 test cases, but it seems to struggle with very lengthy strings. In fact, when provided with strings of 999 characters, the last few outputs were gibberish.

I have thoroughly reviewed my code but cannot pinpoint any errors that might have led to this issue. Any suggestions? Perhaps simpler approaches or more efficient ways to structure my code?

function reverseArrayOfChars(sArray) {
  const length = sArray.length;
  let temp;
  for (let s = 0; s < length / 2; s++) {
    temp = sArray[s];
    sArray[s] = sArray[length - 1 - s];
    sArray[length - 1 - s] = temp;
  }
  return sArray;
}

function reverseStr(s, k) {
  let sArray = s.split("");
  let newArray = []; //Final array to be returned
  let tempArray = []; //tempArray is used to store returns from reverseArrayOfChars function. These returns are then concatenated onto newArray.
  let switchBoard = 1; //Used to 'switch' between two conditions. Changes automatically every iteration of the loop.
  for (let counter = 0; counter < sArray.length; counter += k) {
    switchBoard = switchBoard === 0 ? 1 : 0;
    if (sArray.length - counter < k) {
      tempArray = reverseArrayOfChars(sArray.slice(counter));
      newArray = newArray.concat(tempArray);
      break;
    } else if (sArray.length - counter > k && sArray.length < k * 2) {
      tempArray = reverseArrayOfChars(sArray.slice(counter, counter + k));
      newArray = newArray.concat(tempArray);
      tempArray = sArray.slice(counter + k);
      newArray = newArray.concat(tempArray);
      break;
    } else if (switchBoard === 0) {
      tempArray = reverseArrayOfChars(sArray.slice(counter, counter + k));
      newArray = newArray.concat(tempArray);
    } else if (switchBoard === 1) {
      tempArray = sArray.slice(counter, counter + k);
      newArray = newArray.concat(tempArray);
    }
  }
  return newArray.join("");

Answer №1

Here is an alternative solution that you can experiment with:

function reverseStringWithSeg(s, k) {
    if (k > s.length)
        return s.split('').reverse().join('');
    
    const splitStr = s.split('');
    
    for (let i = 0; i < s.length; i += 2*k) {
        const reversedSegment = splitStr.splice(i, k).reverse();
        splitStr.splice(i, 0, ...reversedSegment);
    }
    
    return splitStr.join('');
}

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

Validation with Javascript can trigger the display of a hidden element

Hello there, I could really use some assistance with the JavaScript part of this code. I have two JavaScript functions: one for validating if a radio checkbox is selected, and another for revealing the "answer". Currently, an alert pops up if no selections ...

Is there a way to ensure uniform display of HTML form error messages across various browsers?

Recently, I completed a login form that consists of username and password fields. For the username, I used a text field with the type email, while for the password, I utilized a text field with the type password which requires validation through a regex pa ...

How to retrieve a MySQL column in Node.js using template literals

I have been trying to retrieve a field from MySQL in my Node.js file using template literals, but I am struggling to get the value. In my post.controller.js file, you can see where it says message: Post ${body.post_id} was successfully created, with post_i ...

Looking for assistance with transforming JSON data into a three-tiered multidimensional array using JavaScript

Seeking guidance on converting JSON data into a 3-tier multidimensional array using JavaScript. The JSON data I am working with is structured as follows: [ {'City':'Philadelphia','State':'Pennsylvania','Countr ...

Press the jQuery button and inform me once it has been activated

My jQuery code is set up to automatically press buttons for me every second. Occasionally, some pages take a long time to load until the button appears. Here is the current code I am using: (function($){ setInterval(function(){ $('.play-b ...

css effect of background image transitioning on mouse hover

Is there a way to have an element on my webpage with a background image that follows the movement of the mouse when hovered over? I want it to be similar to this website: This is the HTML code I currently have: <section id="home" data-speed="3" data-t ...

What is the process for uploading files using AngularFire on Firebase Storage?

Despite watching multiple videos and tutorials, I am encountering a 403 error while working with Angular 1. To solve the issue of ng-model not supporting files, I created an Angular directive named file-model: app.directive('fileModel',['$ ...

Issue with React.js button functionality not functioning as expected

import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props); this.state = { items: [] } } addItem(e) { var itemArray = this.state.items; ...

Querying MongoDB with a JavaScript file for formatting datetime values

I am utilizing mongodb3.0.5 and my database collection appears as follows: { "_id" : "xxxxxxxxxxxxxxx", "SchoolId" : 1, "ActivationTimestamp" : ISODate("2015-09-22T13:01:58.000Z"), "PersonDetails" : [ { "Name" : "John" ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

Exploring the World of 3D Rotation with Three.js

I currently have 2 mesh objects - the Anchor and the Rod. The Anchor rotates around the z-axis, as shown in the image. The Rod is designed to only move backward and forwards. You can view the image here: . However, I am struggling to determine the matrix ...

Attempting to bring in HTML through a helper, but Rails doesn't seem too thrilled about it

I have a form that triggers a remote GET request, leading to the display of a modal. The issue I'm facing is that multiple actions can utilize the same model, so I am attempting to employ a helper and jQuery to showcase different data based on what is ...

Securing Node function parameters in an asynchronous environment

I've been grappling with a pressing question lately, and I just can't seem to find a definitive answer. Let me share with you a Node function that I frequently use. It manages web requests and conducts some input/output operations: function han ...

The ExpressJS app generator seems to be struggling to identify and interpret the flags

I seem to be having trouble running the express app generator with flags. For example, when I run express --version, it interprets the --version part as a target directory and creates the app there. This is happening on Windows XP SP3. Could I be doi ...

Create a password variable while typing

Looking to avoid interference from browsers with autocomplete and password suggestions while maintaining the show/hide letters feature. The goal is to keep the password stored as a variable, regardless of whether the characters are shown or hidden. The is ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

The challenge of handling Set type in TypeScript errors

I'm currently facing two errors while trying to convert a function to TypeScript. The issue lies with the parameters, which are of type Set import type {Set} from 'typescript' function union<T>(setA: Set<T>, setB: Set<T>) ...

Is there a way for multiple <select> elements to have identical options in React?

Currently, I have a React component structured like this: export default function ExampleComponent() { return ( <div> <select required name="select1"> <option label=" "></opti ...

Is there a way to turn off TypeScript Inference for imported JavaScript Modules? (Or set it to always infer type as any)

As I attempt to utilize a JS module within a TypeScript File, I encounter errors due to the absence of type declarations in the JS module. The root cause lies in a default argument within the imported JS function that TypeScript erroneously interprets as ...

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...