Using the two-pointer technique in JavaScript to tackle the reverse vowel dilemma

I encountered the Reverse Vowel problem on Leetcode and decided to tackle it using the Two Pointers pattern. Here is the implementation:

var reverseVowels = function(s) {
    let arrS = s.split('')
    let vowels = ['a','e','i','o','u'];
    let start = 0;
    let end = arrS.length - 1;
    while(start < end) {
      if(!vowels.includes(arrS[start]) && !vowels.includes(arrS[end])) {
        start++;
        end--;
      } else if(vowels.includes(arrS[start]) && !vowels.includes(arrS[end])) {
        end--;
      } else if(!vowels.includes(arrS[start]) && vowels.includes(arrS[end])) {
        start++;
      } else if(vowels.includes(arrS[start]) && vowels.includes(arrS[end])) {
        let elementAtLo = arrS[start]
        arrS[start] = arrS[end];
        arrS[end] = elementAtLo;
        start++;
        end--;
      } 
    }
    return arrS.join('')
};

In the above code, I attempt to swap vowels found at both pointers. However, when I use the following code

arrS[start] = arrS[end];
arrS[end] = arrS[start];

the function fails to produce the correct output. But when I make use of this exchange:

let elementAtLo = arrS[start]
        arrS[start] = arrS[end];
        arrS[end] = elementAtLo;

everything works as intended. Can someone explain why one method works while the other does not?

I am struggling to comprehend the logic behind the success of my implementation.

Answer №1

As you navigate through the code, the initial scenario demonstrates how the array's value gets overwritten, making it impossible to retrieve.

a=[0,1];
console.log(a[0]+', '+a[1]);
a[0]=a[1];
console.log(a[0]+', '+a[1]);
a[1]=a[0];
console.log(a[0]+', '+a[1]);
   

The subsequent example illustrates the utilization of a temporary variable tmp to safeguard the initial value before it undergoes overwriting, ensuring that it remains accessible.

a=[0,1];
console.log(a[0]+', '+a[1]);
tmp=a[1];
console.log(a[0]+', '+a[1]+', '+tmp);
a[1]=a[0];
console.log(a[0]+', '+a[1]+', '+tmp);
a[0]=tmp;
console.log(a[0]+', '+a[1]+', '+tmp);

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

Tips on configuring a hidden input field to validate a form

I am currently attempting to create a blind input field using PHP that will validate if the input field is empty. If it's not empty, the message set up to be sent will not send. However, I have encountered several issues with the placement and wording ...

rendering json data as html using javascript

I am encountering some difficulties with displaying JSON data in HTML using JavaScript. Here is the sample JSON data: { "80": { "Id": "80", "FirstName": "Ranjan", "MiddleName": "Kumar", "LastName": "Gupta", "Gender": "Male", "Locat ...

merging JavaScript objects with complex conditions

I am attempting to combine data from two http requests into a single object based on specific conditions. Take a look at the following objects: vehicles: [ { vId: 1, color: 'green', passengers: [ { name: 'Joe', ag ...

When is the appropriate time to provide arguments to the constructor of a TypeScript service?

I am grappling with the concept of when to pass arguments to a service's constructor versus passing them in the execution of the service. For instance, I have a service that filters rows from an Excel sheet: @Injectable() export class FilterRowsServi ...

Storing dropdown selection in database using Laravel form and AJAX

In my controller (FocalController.php), I have generated a dropdown list using the following code: $focalData = DB::table('role_users')->orderBy('users.id','DESC') ->leftJoin('users', function($j ...

Updating an element within an array in a Mongoose database: A step-by-step guide

Currently, I'm looking to make updates to the "like" attribute within an array stored in my mongoose database. { "_id" : ObjectId("59c7eb0c4a992f8702d847a4"), "title" : "Favorite Rapper", "token" : "9b3fd295a1", "votes" : [ { ...

Method not found in Angular

I am currently working on an Angular application with a C# backend that exposes services. I am trying to use AngularJS resources to access these services. However, when I call the resource in the controller, I am encountering the following error: TypeErro ...

add the closing </div> tag using jquery only

Having a slight issue here, it seems that jQuery is being overly clever. Within my HTML code, I am attempting to insert this string into a div container: </div><div class="something"> You'll notice that the closing tag comes first, foll ...

Tips for creating a fixed element with ScrollTrigger and GSAP

How can I prevent the right div from jumping on top of the left div when using a scroll trigger to make the left div's position fixed? gsap.registerPlugin(ScrollTrigger); const tlfour = gsap.timeline({ scrollTrigger: { trigger: ".ma ...

Optimal asset management strategies for Angular applications

What is the process for loading assets in an Angular app? Will the app wait for all assets to load before bootstrapping, or will they be lazy loaded if not needed on the initial page? I have a large number of PDFs stored in the assets folder that I load a ...

Custom JavaScript clock designed for the Lockscreen of jailbroken iPhones

I am struggling with getting my JavaScript code to display the time correctly on my HTML Lockscreen. After looking at a few examples, I noticed that others are using document.getElementById() instead of document.write() and pushing it to a div. I attempt ...

Angular.js is experiencing difficulties when using the input value attribute in conjunction with ng-model

I've been hard at work on an app that allows users to edit items, with those changes updating in a database. To prevent empty form submissions, I automatically fill the input fields with the current item's information. form.form-update(method="p ...

Use Django, Ajax, and Jquery to incrementally add items to a "cart" by selecting checkboxes one by one

Despite adding new code, it's still not working as expected... I've been attempting to implement a feature where users can select items using checkboxes and add them to the "cart" displayed at the top of the page. Each item on the page has a che ...

Create a new JSON file to preserve the value of a JSON object

I am working with a JSON file that looks like this: { "soils": [{ "mukey": "658854", "mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)", "sl_source": "Fl soil map", "cokey": "3035468", "soilName": "Eunola", " ...

PHP, jQuery, and MySQL combine to create a powerful autocomplete feature for your

I've implemented the source code from into my project, but I'm facing an issue where I can't retrieve any results when typing in the autocomplete textbox. Could someone point out where I might be making a mistake? This is the code I am us ...

Arranging JSON data based on related properties in JavaScript

I have a JSON order with multiple products associated by vendorId, and I'm seeking to group them into separate arrays rather than having all of them listed together. How can I accomplish this? Here is my code: let order = { "product ...

The expiry date of the cookie remains unchanged

When attempting to create a cookie and specify an expiration date, I am encountering an issue where it remains as "Session". This problem is occurring in Google Chrome. I'm looking for insights on what might be causing this behavior. The code snippe ...

What is the code for a non-breaking space in a JavaScript string?

It seems that this code is not functioning as expected: text = $td.text(); if (text == '&nbsp;') { text = ''; } Could it be related to a non-breaking space or the ampersand causing issues in JavaScript? ...

how can one cycle through this demonstration

Within my code, there is a variable called "data" which holds an array of objects: [{"id_questao":1,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 1","id_formulario":1},{"id_questao":2,"id_tipoquestao":1,"conteudo":"Pergunta exemplo 2","id_formulario":1} ...

Add a fresh item to a list using jQuery

Attempting to add a new list item using jQuery. In this scenario, the process works well, but when attempting to retrieve the value of an input field using .val(), no list item is created. http://www.example.com Code snippet: $(document).ready(functi ...