Strings in Data Structures: Complete Guide with Operations and Examples

Introduction

Strings are one of the most commonly used data types in programming. They are used to represent names, messages, passwords, sentences, email addresses, and many other forms of text.

In Data Structures and Algorithms (DSA), string problems help programmers understand character processing, searching, pattern matching, and efficient data manipulation.

For example, checking whether a word is a palindrome, reversing a sentence, counting character frequencies, and finding a substring are all common string problems.

This guide explains strings from the basics, including their operations, implementation, time complexity, and important coding interview problems.

What Is a String?

A string is a sequence of characters arranged in a particular order.

For example:

cpp
string name = "PrimeProblem";

Here, PrimeProblem is a string containing a sequence of characters.

Each character can be accessed using an index. In C++ and many other programming languages, indexing starts from zero.

| Index | Character |
|---|---|
| 0 | P |
| 1 | r |
| 2 | i |
| 3 | m |
| 4 | e |
| 5 | P |
| 6 | r |
| 7 | o |
| 8 | b |
| 9 | l |
| 10 | e |
| 11 | m |

The length of this string is 12.

How Are Strings Stored?

The internal representation of strings depends on the programming language.

In C++, the standard string class stores a sequence of characters and manages its memory automatically. A traditional C-style string is represented using a character array terminated by a null character.

Example:

cpp
char word[] = "Hello";

The character array contains:

text
H  e  l  l  o  

The null character indicates the end of a C-style string.

Modern programming languages may use different character encodings, such as UTF-8 or UTF-16. Therefore, the number of bytes in a string may differ from the number of visible characters.

Types of Strings

Strings can be discussed in different forms depending on their content and representation.

1. Empty String

An empty string contains zero characters.

cpp
string text = "";

Its length is zero.

2. Single-Character String

A string can contain only one character.

cpp
string letter = "A";

Its length is one.

3. Alphanumeric String

An alphanumeric string contains letters and numbers.

cpp
string code = "DSA2026";

4. String with Special Characters

A string may contain spaces, punctuation marks, and special symbols.

cpp
string message = "Learn DSA: Step by Step!";

5. Substring

A substring is a continuous sequence of characters taken from another string.

For example, the string "gram" is a substring of "programming".

Basic String Operations

String operations are frequently used in programming problems.

1. Finding String Length

The length operation returns the number of characters in a string.

```cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
string text = "Programming";

cout << text.length();

return 0;
}
```

Output:

text
11

For a typical string implementation, retrieving the stored length is O(1).

2. Accessing a Character

You can access an individual character using its index.

```cpp
string text = "Computer";

cout << text[0];
cout << text[3];
```

Output:

text
Cm

Indexed character access is generally O(1).

3. Updating a Character

In a mutable C++ string, an existing character can be replaced using its index.

```cpp
string text = "Hello";

text[0] = 'Y';

cout << text;
```

Output:

text
Yello

4. Concatenation

Concatenation means joining two or more strings.

```cpp
string first = "Prime";
string second = "Problem";

string result = first + second;

cout << result;
```

Output:

text
PrimeProblem

The time required depends on the lengths of the strings and whether memory allocation or copying is needed.

5. Extracting a Substring

A substring operation extracts a portion of an existing string.

```cpp
string text = "Programming";

string result = text.substr(0, 7);

cout << result;
```

Output:

text
Program

The first argument is the starting index and the second argument is the number of characters to extract.

6. Comparing Strings

Strings can be compared to check whether their contents are equal or to determine their lexicographical order.

```cpp
string first = "apple";
string second = "apple";

if (first == second) {
cout << "Strings are equal";
}
```

Output:

text
Strings are equal

Comparing two strings can take time proportional to their length in the worst case.

7. Reversing a String

Reversing means changing the order of characters.

```cpp
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
string text = "hello";

reverse(text.begin(), text.end());

cout << text;

return 0;
}
```

Output:

text
olleh

The time complexity is O(n).

Important String Manipulation Problems

String manipulation is an important part of DSA practice.

1. Reverse a String

Problem: Reverse the given string without using a separate reversed string.

Example:

text
Input: hello
Output: olleh

Solution:

```cpp
string text = "hello";

int left = 0;
int right = text.length() - 1;

while (left < right) {
swap(text[left], text[right]);

left++;
right--;
}
```

Time complexity: O(n).

Auxiliary space complexity: O(1), assuming the string can be modified in place.

2. Check Whether a String Is a Palindrome

A palindrome reads the same from left to right and right to left.

Examples:

  • madam
  • level
  • racecar

Solution:

```cpp
bool isPalindrome(string text) {
int left = 0;
int right = text.length() - 1;

while (left < right) {
if (text[left] != text[right]) {
return false;
}

left++;
right--;
}

return true;
}
```

Time complexity: O(n).

Auxiliary space complexity: O(1) for the comparison process when the input is already available as a string.

3. Count Vowels and Consonants

Problem: Count the vowels and consonants in a string containing English letters.

Solution:

```cpp
int vowels = 0;
int consonants = 0;

string text = "programming";

for (char ch : text) {
if (ch == 'a' || ch == 'e' || ch == 'i' ||
ch == 'o' || ch == 'u') {
vowels++;
} else if (ch >= 'a' && ch <= 'z') {
consonants++;
}
}

cout << "Vowels: " << vowels << endl;
cout << "Consonants: " << consonants;
```

Time complexity: O(n).

This example assumes lowercase English letters.

4. Find the Frequency of Characters

Character frequency means counting how many times each character appears.

Example:

```text
Input: banana

a = 3
b = 1
n = 2
```

Solution:

```cpp
#include <iostream>
#include <string>
using namespace std;

int main() {
string text = "banana";
int frequency[256] = {0};

for (unsigned char ch : text) {
frequency[ch]++;
}

for (int i = 0; i < 256; i++) {
if (frequency[i] > 0) {
cout << char(i) << " : "
<< frequency[i] << endl;
}
}

return 0;
}
```

Time complexity: O(n + 256), which is O(n) when the character set size is treated as constant.

5. Check Whether Two Strings Are Anagrams

Two strings are anagrams when they contain the same characters with the same frequencies, regardless of their order.

Example:

```text
Input: listen
Input: silent

Output: Anagram
```

Solution:

```cpp
#include <algorithm>
#include <string>
using namespace std;

bool areAnagrams(string first, string second) {
if (first.length() != second.length()) {
return false;
}

sort(first.begin(), first.end());
sort(second.begin(), second.end());

return first == second;
}
```

Time complexity: O(n log n), because sorting dominates the operation.

This implementation compares characters exactly and is case-sensitive.

String Searching Algorithms

Searching is one of the most important topics in string algorithms. It involves finding a character or a pattern inside a larger string.

1. Naive Pattern Searching

The naive algorithm checks the pattern at every possible starting position in the text.

Example:

text
Text:    A B C A B C D
Pattern:       A B C

It compares characters until a match is found or the current position fails.

Worst-case time complexity: O(n × m), where n is the text length and m is the pattern length.

2. Knuth-Morris-Pratt (KMP)

KMP is an efficient pattern searching algorithm. It uses information from previously matched characters to avoid unnecessary comparisons.

It creates an LPS array, which stands for Longest Proper Prefix that is also a Suffix.

The LPS array helps determine how far the pattern can shift after a mismatch.

Time complexity: O(n + m).

3. Rabin-Karp Algorithm

Rabin-Karp uses hashing to search for patterns in a text. It calculates a hash value for the pattern and compares it with hashes of text windows.

When hash values match, the algorithm can verify the actual characters to avoid incorrect matches caused by hash collisions.

Its expected performance is often efficient, although the worst-case complexity can be O(n × m).

String Algorithms and Their Time Complexity

| Operation or algorithm | Typical time complexity |
|---|---|
| Access character by index | O(1) |
| Traverse a string | O(n) |
| Reverse a string | O(n) |
| Compare strings | O(n) worst case |
| Naive pattern searching | O(n × m) worst case |
| KMP pattern searching | O(n + m) |
| Rabin-Karp | O(n + m) expected in suitable conditions |
| Sorting characters | O(n log n) |

Here, n represents the length of the main string and m represents the pattern length where applicable.

What Is the Two-Pointer Technique in Strings?

The two-pointer technique uses two indices to process a string efficiently.

One pointer may start at the beginning, while the other starts at the end.

For example, the palindrome checking problem uses two pointers:

cpp
int left = 0;
int right = text.length() - 1;

The pointers move toward each other while comparing characters.

This technique is useful for:

  • Reversing strings.
  • Checking palindromes.
  • Comparing characters from opposite ends.
  • Removing selected characters.
  • Solving some substring and array problems.

What Is a Sliding Window in String Problems?

Sliding window is a technique that maintains a moving section of a string.

Instead of repeatedly examining every possible substring from the beginning, an algorithm updates information as the window moves.

For example, consider finding the longest substring without repeating characters.

A sliding window can expand when a new character is valid and shrink when a duplicate appears.

This approach can solve the problem in O(n) time with an appropriate implementation.

Common String Problems in DSA

Practice the following problems in increasing order of difficulty.

Beginner Problems

  • Reverse a string.
  • Check whether a string is a palindrome.
  • Count vowels and consonants.
  • Find the length of a string.
  • Convert lowercase letters to uppercase.
  • Count words in a sentence.
  • Find the frequency of each character.

Intermediate Problems

  • Check whether two strings are anagrams.
  • Find the first non-repeating character.
  • Remove duplicate characters.
  • Find the longest common prefix.
  • Reverse words in a sentence.
  • Find the longest substring without repeating characters.
  • Group anagrams.

Advanced Problems

  • Implement the KMP algorithm.
  • Implement the Rabin-Karp algorithm.
  • Find the longest palindromic substring.
  • Find the minimum window substring.
  • Implement the Z algorithm.
  • Find all occurrences of a pattern in a text.

Advantages of Strings

Strings offer several benefits in programming:

  1. They provide a convenient way to represent text.
  2. Characters can be accessed and processed individually.
  3. String libraries provide useful built-in operations.
  4. They are essential for text processing and searching.
  5. String algorithms are useful in compilers, search systems, and natural language processing.

Common Mistakes While Solving String Problems

Beginners often make these mistakes:

  • Accessing an index outside the valid string range.
  • Forgetting that indexing usually starts at zero.
  • Confusing a substring with a subsequence.
  • Ignoring uppercase and lowercase differences.
  • Using inefficient nested loops when a better algorithm exists.
  • Forgetting about spaces and punctuation in input.
  • Assuming every visible character occupies exactly one byte.

Understanding these details can prevent bugs and improve algorithm efficiency.

Frequently Asked Questions

What is a string in DSA?

A string is an ordered sequence of characters used to represent text. String problems involve operations such as searching, comparison, manipulation, and pattern matching.

What is the difference between a string and a character array?

A character array is an array that stores characters. A string is a text representation or data type that may provide additional operations and memory management depending on the programming language.

What is a substring?

A substring is a continuous sequence of characters taken from a larger string.

What is the difference between a substring and a subsequence?

A substring contains consecutive characters. A subsequence preserves the original character order but may skip characters.

Which string algorithm should beginners learn first?

Start with string traversal, reversal, palindrome checking, frequency counting, and basic pattern searching. Then move to KMP and other advanced algorithms.

Are strings important for coding interviews?

Yes. String problems are common in technical interviews because they test indexing, searching, hashing, two pointers, sliding windows, and problem-solving skills.

Conclusion

Strings are an essential part of Data Structures and Algorithms. They help programmers process text and solve problems involving character sequences, searching, comparison, and pattern matching.

Begin with basic string operations and gradually practice two-pointer techniques, sliding windows, character frequency, and pattern searching. Once these concepts become familiar, advanced string algorithms such as KMP and Rabin-Karp will become easier to understand.

✓

You’ve reached the end of this guide. Explore more tutorials on PrimeProblem.