Baraka Coding Question

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.0 kB
3
Indexable
Never
import java.sql.Array;
import java.util.ArrayList;

public class Main {

//    You have an alphanumeric string (only latin letters and digits).
//    Return the same string but where letters remain on the same positions and digits are in reverse order
//    Example:
//    ab4c13 -> ab3c14

    public static void test(String input) {
        //    ab4c13 -> ab3c14
        //   [a, b, -1, c, -1, -1]
        // Approach
            // arr[] = 4, 1, 3
            // arr.rever()

        // Iterate the array
            // string[] = new string[input.length]
            // In case of any alphabet
                // store it in the current location
            // In case of a number
                // add it into a separate datastruture // num[]
            // complete the iteration

        // iterate the new_array -> again
        // wherever I see an empty string // null
        // arr[i] = new String(num[j])


        // Time Complexity: O(N)

        // ab4c13 O(N) -, 0(N)
        var x = new ArrayList<>(); // number
        var m = new ArrayList<String>(); // alphaets
        
        // Somehow in the input array itself, mark the numbers
        // Then, complete the iteration and store the numbers alone
        // Then, iterate the input array i.e -1
        // R
        
        
        for (char c: input.toCharArray()) {
            if (Character.isDigit(c)) {
                // save this somewhere
                x.add(c); // digit
                m.add("-1");
            } else {
                m.add(String.valueOf(c));
            }
        }
        String ans = "";
        var index = x.size() - 1;
        for (var y: m) {
            // we are expecting a digit
            if (y.equalsIgnoreCase("-1")) {
                ans += x.get(index);
                index -= 1;
            } else {
                ans += y;
            }
        }

        System.out.println(ans);
    }


    public static void main(String[] args) {
        test("ab4c13");
        test("ab3c41");
    }
}