Change language

Python | Get the smallest window in a string containing all the characters of a given pattern

| |

Examples :

  Input:  str = ’pythonengineering’ pattern =’ gks’  Output:  geeks  Input:  str = ’new string’ pattern =’ rg’  Output:  ring 

Approach # 1 Using Python enumerate ()
This method uses Python enumerate () . need [k] to store how many times we need the character k, and the absence indicates how many characters have not yet been found. In a loop, first add a new symbol to the window. Then, if nothing is missing, remove as much as possible from the beginning of the window, and then update the result.

# Python3 code to find the smallest
# window in a line containing all
# characters of another line

from collections import Counter

 
# Function to find the smallest window containing
# all characters & # 39; pat & # 39;

def min_window ( str , pattern):

  

# No storage. missing characters

missing = len (pattern)

 

# No read. required characters

need = Counter (pattern)

I = J = i = 0

 

# Enumeration bypass

for j, k in enumerate ( str , 1 ):

missing - = need [k]" 0

need [k] - = 1

 

# If nothing is missing, delete as many as

# possible from the launcher

if not missing:

while need [ str [i]] " 0 :

need [ str [i]] + = 1 ; i + = 1

 

if not J or j - i " = J - I:

I, J = i, j

 

need [ str [i]] + = 1 ; i + = 1

missing + = 1

 

# Returning the results window

return str [I: J]

 
Driver code

string = "pythonengineering"

pattern = "fks"

print (min_window (string, pattern))

Exit :

 ksf 

Approach # 2: Using collections.defaultdict ()
This method uses two defaultdicts & # 39; src & # 39; and & # 39; dest & # 39 ;. Defaultdict works exactly like a normal dict, but it is initialized with a function ("default factory") that takes no arguments. source is empty and target consists of template elements as keys and number of occurrences as value. At each iteration & # 39; i & # 39; we check if i- th element str is present in the target dictionary or not and update accordingly source dictionary.

# Python3 code to find the smallest
# window in a line containing all
# characters of another line

from collections import defaultdict

import sys

def min_window ( str , pattern):

 

# Function for checking rules source and

# destination

def isValid (i, j):

for item in j:

if item not in i or i [item] "j [item]:

return False

return True

 

source = defaultdict ( int )

  target = defaultdict ( int )

 

# The target consists of template elements and 1

# as key: value pair

for e in pattern:

target [e] + = 1

 

  # Minimum window length

minLen = sys.maxsize

n = len ( str )

ans, j = ’’, 0  

for i in range (n):

 

# Update source for valid source - target pair

while j "n and (isValid (source, target) = = False ):

source [ str [j]] + = 1

j + = 1

 

# Check source-target pair for correctness

if isValid (source, target):

if minLen" j - i + 1 :

  minLen = j - i + 1

  ans = str [i : j]

source [ str [i]] - = 1

return ans

 
Driver code

string = " geekforgeeks "

pattern = "gks"

print (min_window (string, pattern))

Exit:

 geeks 

Approach # 3: Dynamic Approach
In this method, we use a for loop, and at each iteration of, say i, we find the shortest interval that ends with i and includes all the letters in the pattern. This can be done by taking into account two data structures, ie "Rpos" and "rdict". rpos — is a sorted list of positions that store the rightmost positions of the pattern characters in str, and rdict — it is a dictionary mapping character to position. rdict values ​​are the same as rpos.

# Python3 code to find the smallest
# window on a line containing all
# characters of another line

from collections import Counter, defaultdict

 

def min_window ( str , pattern):

 

rdict, count = defaultdict ( list ), Counter (pattern)

rpos, res = [], "" 

 

# Loop only on c exists in the template

for i, c in filter ( lambda x: x [ 1 ] in pattern, enumerate ( str )): 

if len (rdict) = = count: 

  # If limit is reached, remove

rpos.remove (rdict.pop ( 0 ))

 

# Add to dictation

rdict [i] .append (i)

# Add to list

  rpos.append (i) 

 

  if ( len (rpos ) = = len (pattern) and

(res = = "" or rpos [ - 1 ] - rpos [ 0 ] " len (res))):

  res = str [rpos [ 0 ]: rpos [ - 1 ] + 1

  

return res

 
Driver code

string = "pythonengineering"

pattern = "gks "

print (min_window (string, pattern))

Exit:

 geeks 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically