|
| 1 | +# Minimum Window Substring in R |
| 2 | +# Author: sgindeed |
| 3 | +# Description: Finds the smallest substring of s that contains all characters of t |
| 4 | + |
| 5 | +# Ask for inputs |
| 6 | +s <- readline(prompt = "Enter main string: ") |
| 7 | +t <- readline(prompt = "Enter target characters: ") |
| 8 | + |
| 9 | +# Convert to lowercase for case-insensitivity |
| 10 | +s <- tolower(s) |
| 11 | +t <- tolower(t) |
| 12 | + |
| 13 | +# Edge case |
| 14 | +if (nchar(s) == 0 || nchar(t) == 0) { |
| 15 | + cat("Empty input. Exiting.\n") |
| 16 | + quit(save = "no") |
| 17 | +} |
| 18 | + |
| 19 | +# Convert to char arrays |
| 20 | +s_chars <- strsplit(s, "")[[1]] |
| 21 | +t_chars <- strsplit(t, "")[[1]] |
| 22 | + |
| 23 | +# Frequency of characters in t |
| 24 | +t_count <- table(t_chars) |
| 25 | +window_count <- list() |
| 26 | + |
| 27 | +required <- length(t_count) |
| 28 | +formed <- 0 |
| 29 | + |
| 30 | +left <- 1 |
| 31 | +right <- 0 |
| 32 | +min_len <- Inf |
| 33 | +min_window <- "" |
| 34 | + |
| 35 | +# Sliding window |
| 36 | +while (right < length(s_chars)) { |
| 37 | + right <- right + 1 |
| 38 | + char <- s_chars[right] |
| 39 | + window_count[[char]] <- (window_count[[char]] %||% 0) + 1 |
| 40 | + |
| 41 | + if (!is.na(t_count[char]) && window_count[[char]] == t_count[char]) { |
| 42 | + formed <- formed + 1 |
| 43 | + } |
| 44 | + |
| 45 | + # Try to contract the window |
| 46 | + while (left <= right && formed == required) { |
| 47 | + if ((right - left + 1) < min_len) { |
| 48 | + min_len <- right - left + 1 |
| 49 | + min_window <- paste0(s_chars[left:right], collapse = "") |
| 50 | + } |
| 51 | + |
| 52 | + left_char <- s_chars[left] |
| 53 | + window_count[[left_char]] <- window_count[[left_char]] - 1 |
| 54 | + if (!is.na(t_count[left_char]) && window_count[[left_char]] < t_count[left_char]) { |
| 55 | + formed <- formed - 1 |
| 56 | + } |
| 57 | + left <- left + 1 |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +if (is.infinite(min_len)) { |
| 62 | + cat("No valid window found.\n") |
| 63 | +} else { |
| 64 | + cat("Minimum window substring:", min_window, "\n") |
| 65 | + cat("Length:", min_len, "\n") |
| 66 | +} |
0 commit comments