Contents

Removing "ad" (with.Java)

   Oct 15, 2023     2 min read

This is the article about removing “ad”.

We’ll do this by solving a coding test problem, doing a retrospective on the problem we solved, and learning about other ways to solve it.

Let’s start with the problem

Problem

You are given an array of strings, strArr.

Complete a solution function that removes all strings in the array that contain the substring “ad” and returns the remaining strings to the array in order.

Example input and output
strArrresult
[“and”,”notad”,”abcd”][“and”,”abcd”]
[“there”,”are”,”no”,”a”,”ds”][“there”,”are”,”no”,”a”,”ds”]

My solution to the problem

class Solution {
    public String[] solution(String[] strArr) {
        int count = 0;
        String ad = "ad";
        for (int i = 0; i < strArr.length; i++) {
            if (!strArr[i].contains(ad)) {
                count++;
            }
        }
        String[] answer = new String[count];
        int index = 0;
        for (int i = 0; i < strArr.length; i++) {
            if (!strArr[i].contains(ad)) {
                answer[index++] = strArr[i];
            }
        }

    } return answer;
}
solution description

public String[] solution(String[] strArr): A function that takes an array of strings, strArr, as input and solves the problem. It returns an array of strings as the return value.

int count = 0;: Initialize the variable count to store the number of valid strings.

String ad = “ad”;: A variable to store the substring “ad”. It will be used later to check if the string contains this.

for (int i = 0; i < strArr.length; i++) { … }: Runs a loop for each string in the given array of strings, strArr.

if (!strArr[i].contains(ad)) { … }: Checks if the current string does not contain “ad”. If it does not, increment the value of count.

String[] answer = new String[count];: Create an answer array sized to fit the number of valid strings.

int index = 0;: Initialize the index variable to be used when storing strings in the answer array.

In the second iteration, perform the task of storing the valid strings into the answer array. It checks and saves it to the answer array only if it does not contain “ad”, incrementing the index value as it does so.

return answer;: Returns the answer array as finally constructed.