Goal: write a method to determine if a string is a pangram.

observations

A pangram is a phrase using all the letters of the alphabet.

  • The quick brown fox jumps over the lazy dog.
  • The five boxing wizards jump quickly.
  • Bright vixens jump; dozy fowl quack.

assumptions

For this problem let the alphabet consist of only letters ignoring case, and let’s assume our input may include punctuation, digits, or spaces.

program

Give it a try in your programming language of choice, and try to be brief. Test negative case by removing words from the pangram. Below I share my solutions in Swift and C#.


my solution examples

A pangram uses all letter characters at least once. Counting would be one option, but notice we’re looking for a phrase that is the superset of the alphabet.

Swift 3

Turn the phrase into a Set and find if the phrase-set is a superset of the letters-set.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//: Playground - noun: a place where people can play

import Cocoa

let letters = "abcdefghijklmnopqrstuvwxyz"
let phrase = "The quick brown fox jumps over Lazy Dog."
let phraseFail = "The brown fox jumps over the lazy dog."
let letterSet = Set(letters)
let phraseSet = Set(phrase.lowercased()
let phraseFailSet = Set(phraseFail.lowercased()

if phraseSet.isSuperset(of: letterSet) {
    print("is pangram")
}
else {
    print("Not pangram")
}
if phraseFailSet.isSuperset(of: letterSet) {
    print("is pangram")
}
else {
    print("Not pangram")
}

C#

For this solution I used LINQ to query distinct letters which should equal the length of our English alphabet, 26. Learn more about LINQ on MSDN.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
using System;
using System.Linq;

namespace MyTutorialConsoleApp
{
    public static class StringPlay
    {
        public static bool IsPangram(string phrase)
        {
            if (String.IsNullOrWhiteSpace(phrase) || phrase.Length < 26)
            {
                return false;
            }

            if (phrase.Where(char.IsLetter).Select(char.ToLower).Distinct().Count() == 26)
            {
                return true;
            }

            return false;
        }
    }
}