Permutation in String — DSA Interview 150 · Sliding Window
Classic interview problem #567.
Input (stdin)
Line 1: s1\nLine 2: s2
Output (stdout)
true if permutation of s1 in s2
Your program must read from stdin and write the answer to stdout (no extra debug text).
ab eidbaooo
true
| Test | Status | Details |
|---|
Ready — edit the code above and click Run or Submit.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
static int[] Ria(string line = null)
{
line ??= Console.ReadLine();
if (string.IsNullOrWhiteSpace(line)) return Array.Empty<int>();
return line.Trim().Split(new[] { ' ', ',', '\t' }, StringSplitOptions.RemoveEmptyEntries)
.Select(int.Parse).ToArray();
}
static string[] Rsa()
{
int n = int.Parse(Console.ReadLine());
var arr = new string[n];
for (int i = 0; i < n; i++) arr[i] = Console.ReadLine();
return arr;
}
static void W(params object[] parts) => Console.WriteLine(string.Join(" ", parts));
static void Wb(bool v) => Console.WriteLine(v ? "true" : "false");
static void Wi(int v) => Console.WriteLine(v);
static void Ws(string v) => Console.WriteLine(v);
static void Main()
{
string s1 = Console.ReadLine();
string s2 = Console.ReadLine();
var need = new int[26], have = new int[26];
foreach (var c in s1) need[c - 'a']++;
int matches = 0;
for (int i = 0; i < 26; i++) if (need[i] == 0) matches++;
bool found = false;
for (int i = 0; i < s2.Length; i++) {
int idx = s2[i] - 'a';
have[idx]++;
if (have[idx] == need[idx]) matches++;
else if (have[idx] == need[idx] + 1) matches--;
if (i >= s1.Length) {
int outIdx = s2[i - s1.Length] - 'a';
have[outIdx]--;
if (have[outIdx] == need[outIdx]) matches++;
else if (have[outIdx] == need[outIdx] - 1) matches--;
}
if (matches == 26) { found = true; break; }
}
Wb(found);
}
}
Try solving on your own first, then reveal the official answer.
Pattern: Sliding Window
Read from stdin, write to stdout. Classic interview problem #567.