Concatenate One String to Another

Asked atM2P Fintech
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

You are given two strings str1 and str2. Write a program to concatenate str2 to the end of str1, and return the resulting combined string.

Concatenation means joining both strings in their original order.

Input: str1 = "Hello", str2 = "World" Output: "HelloWorld" Explanation: str2 is appended at the end of str1

**Input: **str1 = "abc", str2 = "123" **Output: **"abc123"

**Input: **str1 = "Good", str2 = "Morning"

  • 1 <= str1.length, str2.length <= 105
  • Strings may contain alphabets, digits, spaces, or special characters

cpp

class Solution {
public:
    string concatenate(string str1, string str2) {
        // Your code goes here
    }
};

java

class Solution {
    public String concatenate(String str1, String str2) {
        // Your code goes here
    }
}

python

class Solution:
    def concatenate(self, str1: str, str2: str) -> str:
        # Your code goes here

javascript

class Solution {
    concatenate(str1, str2) {
        // Your code goes here
    }
}

csharp

class Solution {
    public string Concatenate(string str1, string str2) {
        // Your code goes here
    }
}

go

func concatenate(str1 string, str2 string) string {
	// Your code goes here
}
Stuck? Show a way to structure it+
  1. 01Preserve str1 order.
  2. 02Append str2 after it.
  3. 03Return the combined value.
  4. 04Use a builder where repeated concatenation is involved.

Reference answer

Then expect these follow-ups

  • How would you concatenate a large list of strings efficiently?

    Tests: string builder

  • What is the difference between concatenation and interleaving?

    Tests: problem reading

Free to read · better with Enzo

Practice this out loud with Enzo

Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.

Next question