Java Solution with Only 4 Lines

  • 0
    public class Solution {
        public boolean canConstruct(String ransomNote, String magazine) {
            List<Character> list = new ArrayList<>();
            for(char ch : magazine.toCharArray()) list.add(ch);
            for(char ch : ransomNote.toCharArray()) if(!list.remove((Character)ch)) return false;
            return true;

  • 0

    Actually this is O(n2).
    The time complexity of removing an element from list is O(n).

    For O(n) solution - one option is to use hashmap whose addition and removal of time complexity is O(1)

  • 0
    This post is deleted!

  • 0

    @neo Yes you are right, thanks for your correction.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.