878716. The New Line

Easy

The New Line

Summary

Given a string, the task is to add a new line character at each occurrence of a specific word in the string. The problem involves manipulating strings and finding specific patterns.

Detailed Explanation

The approach for this problem is straightforward. We will iterate through the input string and check if the current substring matches the target word. If it does, we add a new line character after the matched word.

Here's a step-by-step breakdown of the solution:

  1. Initialize an empty result string.
  2. Iterate through the input string using a loop.
  3. For each character in the string:
    • Check if the substring from the start of the string to the current position matches the target word.
    • If it does, add the target word followed by a new line character to the result string.
  4. Return the modified result string.

Time complexity: O(n), where n is the length of the input string. Space complexity: O(1), as we only use a constant amount of space to store the result and temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public String addNewLine(String str, String word) {
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < str.length(); i++) {
        if (str.substring(i).startsWith(word)) {
            result.append(str.substring(0, i)).append("\n").append(word);
            i += word.length() - 1;
        } else {
            result.append(str.charAt(i));
        }
    }
    return result.toString();
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.