All challenges
Easy 0 solved 0% acceptance

Every Other Character

Keep the characters at even positions.

What you'll learn

  • Pick characters at even positions
  • Loop with a step of 2 or use slicing
  • Build a new string

Problem

Build a new string from the characters of text at positions 0, 2, 4, … (every other character, starting with the first).

Implement every_other_character(text).

Input

text: The original text.

Output

Return the characters at even positions, in order.

Constraints

0 ≤ length of text ≤ 10,000

Examples

Example 1
Input:
text = "programming"

Expected output:
expected = "pormig"
Input:
std::string text = "programming";

Expected output:
std::string expected = "pormig";
Input:
string text = "programming";

Expected output:
string expected = "pormig";

Explanation

Positions 0, 2, 4, 6, 8, 10 give p, o, r, m, i, g: "pormig".

Example 2
Input:
text = "a"

Expected output:
expected = "a"
Input:
std::string text = "a";

Expected output:
std::string expected = "a";
Input:
string text = "a";

Expected output:
string expected = "a";

Explanation

Only position 0 exists: "a".

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

You want characters at positions 0, 2, 4, and so on.

Hint 2

A step-by-two traversal is the simplest way to select them.

Hint 3

If the text is empty or has odd length, the pattern still works naturally.

Expected complexity

O(n) time, O(n) extra space

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.