Check Order Of Character In String Using OrderedDict() - Python
Given an input string and a pattern, check if characters in the input string appear in the same order as in the pattern. Assume the pattern has no duplicate characters. For Examples:
Input: s = "engineers rock", pattern = "er"
Output: true
Explanation: All 'e' in the input string are before all 'r'.
Let's explore different methods to check order of character in string using OrderedDict().
Using OrderedDict with Index Mapping
This method stores the first occurrence index of each unique character using OrderedDict and then checks whether the pattern’s characters appear in increasing index order within the string.
from collections import OrderedDict
s = 'engineers rock'
p = 'er'
od = OrderedDict()
for i, ch in enumerate(s):
if ch not in od:
od[ch] = i
pos = -1
for ch in p:
if ch not in od or od[ch] < pos:
print(False)
break
pos = od[ch]
else:
print(True)
Output
True
Explanation:
- od[ch] = i: Stores the first occurrence index of each unique character in OrderedDict.
- for ch in p: Iterates through pattern characters sequentially.
- if ch not in od or od[ch] < pos: Checks if the character is missing or out of order.
- pos = od[ch]: Updates the last matched index.
Using OrderedDict.fromkeys()
OrderedDict preserves the order of characters while removing duplicates. You can use it to check if the letters of a pattern appear in the correct order in a string.
from collections import OrderedDict
s = 'engineers rock'
p = 'er'
od = OrderedDict.fromkeys(s)
ptr = 0
for k in od:
if k == p[ptr]:
ptr += 1
if ptr == len(p):
print(True)
break
else:
print(False)
Output
True
Explanation:
- OrderedDict.fromkeys(s): creates an ordered set of unique characters.
- ptr: tracks the position in the pattern.
- Loops through keys; if a key matches p[ptr], increment ptr.
- If all pattern characters are matched, prints True; otherwise prints False.
Using Manual Insertion into OrderedDict
In this method, characters are manually inserted into an OrderedDict while keeping their order intact. The pattern is then checked sequentially against the ordered keys to verify if its characters appear in the same order as in the string.
from collections import OrderedDict
s = 'engineers rock'
p = 'er'
od = OrderedDict()
for ch in s:
if ch not in od:
od[ch] = None
ptr = 0
for k in od:
if k == p[ptr]:
ptr += 1
if ptr == len(p):
print(True)
break
else:
print(False)
Output
True
Explanation:
- if ch not in od: od[ch] = None: Inserts each unique character while preserving order.
- for k in od: Iterates through ordered unique characters.
- if k == p[ptr]: ptr += 1: Advances the pattern pointer when characters match.
- if ptr == len(p): print(True): Confirms all pattern characters appear in correct order.