top of page

Keep Reading !

You can also checkout more topics like...

peep-101_edited.png
EXPLORE COURSES (6).png
EXPLORE COURSES (9).png
EXPLORE COURSES (7)_edited.jpg

Reverse a Array or String

For Array

You are given an Array arr. You need to reverse the array

SAMPLE 1:

Input:
arr[] = 1 2 3 4
Output: 4 3 2 1

Your Task:

You only need to create a function reverseArray() that takes s as a parameter and returns the reversed Array.


Answer:

public void swapAtIndex(int i , int j, int arr[])
    {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;

    }
    public static int[] reverseArray(int arr[])
    {
        
        
            int first = 0;
            int last = arr.length - 1;
            while(fist<last)
            {
                swapAtIndex(fist,last,arr);
                first++;
                last++;
            }

        return arr;

    }



Click on the Execute button below for code up and running



For String

You are given a string s. You need to reverse the string.

Example 1:

Input:
str = Code
Output: edoC

Example 2:

Input:
str = Hello
Output: olleH

Your Task:

You only need to complete the function reverseWord() that takes s as parameter and returns the reversed string.

Expected Time Complexity: O(|STR|). Expected Auxiliary Space: O(1).

Constraints: 1 <= |str| <= 10000



public static String reverseWord(String str)
    {
        //using normal string, mind it! in java string are 
           manipulated so it is time taking
        
        // tnormalnoraml string "reverse" and initialize itanwith a 
             empty string
        
           String reverse = "";
        
        for(int i = str.length()-1; i>=0;i--)
        {
            reverse += str.charAt(i);
        }
        return reverse;
    }


Click on the Execute button below for code up and running



82 views0 comments

Recent Posts

See All

Comments


bottom of page