Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Longest String Chain

Posted on August 5, 2019July 26, 2020 by braindenny

Longest String Chain



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #hashmap, #dynamicprogramming, #lis

Given an integer array of size n, find all elements that appear more than n/3 times. The algorithm should run in linear time and in O(1) space.

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


  • Solution:
// https://code.dennyzhang.com/longest-string-chain
// Basic Ideas: LIS dp + hashmap
//
//  Notice: instead of adding a character, try to delete one
//  The sequence doesn't matter: There might be a chain of s[i] -> s[j] with j<i
//
// Complexity: Time O(n*log(n)), Space O(n)
import "sort"
func longestStrChain(words []string) int {
    sort.Slice(words , func(i, j int) bool {
        return len(words[i])<len(words[j])
    })
    m := map[string]int{}
    dp := make([]int, len(words))
    res := 0
    dp[0] = 1
    m[words[0]] = 0
    for i:=1; i<len(words); i++ {
        word := words[i]
        max := 1
        for j, _ := range word {
            word2 := word[0:j]+word[j+1:]
            if v, ok := m[word2]; ok {
                if dp[v]+1>max {
                    max = dp[v]+1
                }
            }
        }
        dp[i] = max
        m[word] = i
        if max > res {
            res = max
        }
    }
    return res
}
linkedin
github
slack

Post Views: 0
Posted in MediumTagged #dynamicprogramming, #inspiring, hashmap, lis

Post navigation

LeetCode: Word Squares
LeetCode: Corporate Flight Bookings

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.