easystringhashmapsorting

Valid Anagram

Given two strings, print "true" if one is a permutation of the other.

Problem

Statement

An anagram is a rearrangement of a string's characters. listen ↔ silent. evil ↔ vile. Not: hello ↔ world.

Two canonical approaches: (a) sort both strings and compare — O(n log n) time, O(1) extra space; (b) count characters in a hashmap or frequency array and compare — O(n) time, O(k) space where k is the alphabet size. For ASCII, k = 128, so (b) is strictly better.

Read two lines. Print "true" or "false".

Worked cases

Examples

Input
listen
silent
Output
true
Input
hello
world
Output
false
Input
anagram
nagaram
Output
true
Bounds

Constraints

  • 1 ≤ length of both strings ≤ 10^5
  • ASCII lowercase only.
Reference

Sample solutions

Runnable starter code. Click "Try in playground" to open pre-loaded with the test fixtures.

Python
from collections import Counter
a = input(); b = input()
print('true' if Counter(a) == Counter(b) else 'false')
Java
import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String a = sc.nextLine(), b = sc.nextLine();
        if (a.length() != b.length()) { System.out.println("false"); return; }
        int[] freq = new int[128];
        for (char c : a.toCharArray()) freq[c]++;
        for (char c : b.toCharArray()) if (--freq[c] < 0) { System.out.println("false"); return; }
        System.out.println("true");
    }
}
C++
#include <bits/stdc++.h>
using namespace std;

int main() {
    string a, b; getline(cin, a); getline(cin, b);
    if (a.size() != b.size()) { cout << "false\n"; return 0; }
    int freq[128] = {0};
    for (char c : a) freq[(unsigned char)c]++;
    for (char c : b) if (--freq[(unsigned char)c] < 0) { cout << "false\n"; return 0; }
    cout << "true\n";
}
Also try