Contents

Left Right (with.Java)

   Sep 28, 2023     3 min read

This is a post about left-right (with.Java).

We’ll be solving coding test questions, reflecting on the problems we’ve solved, and learning about other ways to solve them.

Let’s start with the problem.

Problem

A list of strings, str_list, contains a number of the four strings β€œu”, β€œd”, β€œl”, and β€œr”.

Complete the solution function to return an ordered list of strings to the left of β€œl” and β€œr” in str_list if β€œl” comes first, and an ordered list of strings to the right of β€œr” if β€œr” comes first.

If there is no β€œl” or β€œr”, return an empty list.

Example input and output
str_listresult
[β€œu”, β€œu”, β€œl”, β€œr”][β€œu”, β€œu”]
[β€œl”][]

My solution to the problem

class Solution {
    public String[] solution(String[] str_list) {
        int lIndex = -1;
        int rIndex = -1;

        for (int i = 0; i < str_list.length; i++) {
            if (str_list[i].equals("l")) {
                lIndex = i;
                break;
            } else if (str_list[i].equals("r")) {
                rIndex = i;
                break;
            }
        }
        if (lIndex == -1 && rIndex == -1) {
            return new String[0];
        }

        if (lIndex != -1) {
            String[] answer = new String[lIndex];
            for (int j = 0; j < lIndex; j++) {
                answer[j] = str_list[j];
            }
            } return answer;
        }
        else {
            String[] answer = new String[str_list.length - rIndex - 1];
            for (int k = rIndex + 1; k < str_list.length; k++) {
                answer[k - rIndex - 1] = str_list[k];
            }
            } return answer;
        }
    }
}
solution description

int lIndex = -1;, int rIndex = -1;: Initialize the index of the β€œl” character and the index of the β€œr” character. The initial values are set to -1.

First iteration (for (int i = 0; i < str_list.length; i++) {): Loops through the array str_list, looking for the character β€œl” or β€œr”. If an β€œl” is found, store its index in lIndex and exit the loop; if an β€œr” is found, store its index in rIndex and exit the loop.

if (lIndex == -1 && rIndex == -1) { return new String[0]; }: If neither β€œl” nor β€œr” is found, return an empty string array.

if (lIndex != -1) { … } else { … }: Performs different logic depending on if either β€œl” or β€œr” was found.

If β€œl” is found:

String[] answer = new String[lIndex];: Create an array answer to store the strings before the β€œl” character.

Use a loop to copy the strings before the β€œl” character into the answer array.

Return the answer array.

If an β€œr” is found:

String[] answer = new String[str_list.length - rIndex - 1];: Create an array answer to store the strings after the β€œr” character.

Use a loop to copy the strings after the β€œr” character into the answer array.

Return the answer array.