How would you like to learn today?
Visualize algorithms in real time, explore them step by step, or challenge yourself with a test.Choose a path to focus—or scroll down to preview all options.
Visualize the algorithm step-by-step with interactive animations in real time.
Read the full explanation, examples, and starter code at your own pace.
Drag and arrange the algorithm steps in the correct execution order.
🧠 Select Active to activate
Follow every state change, comparison, and transformation as the execution unfolds in real time.
📖 Select Passive to activate
You are given an array of strings called words. Your task is to count the number of pairs (i, j) (where i < j) such that a string words[i] is both a prefix and a suffix of another string words[j].
str1 is a prefix of str2 if str2 starts with str1.
Example: "ab" is a prefix of "abc", but not of "cab".str1 is a suffix of str2 if str2 ends with str1."bc" is a suffix of "abc", but not of "bca".str1 is both a prefix and suffix of str2
if:
- str2 starts with str1, and
- str2 ends with str1.Input: words = ["a", "aba", "ababa", "aa"]
Output: 4
Explanation:
The valid pairs (i, j) are:
(0, 1) because "a" is both a prefix and suffix of "aba".(0, 2) because "a" is both a prefix and suffix of "ababa".(0, 3) because "a" is both a prefix and suffix of "aa".(1, 2) because "aba" is both a prefix and suffix of "ababa".Input: words = ["pa", "papa", "ma", "mama"]
Output: 2
Explanation:
The valid pairs (i, j) are:
(0, 1) because "pa" is both a prefix and suffix of "papa".(2, 3) because "ma" is both a prefix and suffix of "mama".Input: words = ["abab", "ab"]
Output: 0
Explanation:
No valid pairs exist because none of the strings in words satisfy the condition of being both a prefix and suffix.
1 <= words.length <= 501 <= words[i].length <= 10words[i] contains only lowercase English letters.Return the total number of valid (i, j) pairs where i < j and words[i] is both a prefix and a suffix of words[j].
🎯 Select Challenge to activate
Drag and arrange the algorithm steps in the correct execution order instead of spending time typing code letter by letter.
The algorithm is divided into three logical parts. Carefully rearrange each section in the correct order to form a complete and valid solution.
Understand Below AlgorithmGreen text means the instruction is placed in the correct position.
Red text means the instruction is in the wrong position.
Instructions with the same background color indicate particular blocks start and end.
A tick mark means the instruction is correct and locked.
🔒 Locked steps cannot be moved. Only unlocked steps are draggable.
🔊 Enable sound for swap feedback and completion effects.