⬅ Previous Topic
Implement Atoi - Convert String to Integer in JavaNext Topic ⮕
Edit Distance Problem⬅ Previous Topic
Implement Atoi - Convert String to Integer in JavaNext Topic ⮕
Edit Distance ProblemTopic Contents
Given a string of length n
, your task is to count the total number of substrings present in it.
A substring is a contiguous part of the string. For example, in the string "abc", the substrings are: "a", "b", "c", "ab", "bc", and "abc".
Note: Do not confuse substrings with subsequences. A substring maintains the original order and continuity of characters, whereas a subsequence can skip characters.
If the input string is empty, the number of substrings is 0
.
n
.n * (n + 1) / 2
.def count_substrings(s):
n = len(s)
# Total substrings = n * (n + 1) // 2
return n * (n + 1) // 2
# Example
s = "abc"
print("Total substrings:", count_substrings(s))
Case | Time Complexity | Explanation |
---|---|---|
Best Case | O(1) | Only a single formula is evaluated regardless of string length. |
Average Case | O(1) | Computation does not depend on content, just length. |
Average Case | O(1) | Even for the largest strings, only the length is used in a constant time operation. |
O(1)
Explanation: The algorithm uses a constant amount of memory for computation.
⬅ Previous Topic
Implement Atoi - Convert String to Integer in JavaNext Topic ⮕
Edit Distance ProblemYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.