Palindrome tree

Palindrome tree
TypeTree
Invented2015
Invented byMikhail Rubinchik, Arseny M. Shur
Time complexity in big O notation
Operation Average Worst case
Search O(n*log σ) O(n*log σ)
Insert O(log σ) O(n)
Space complexity
Space O(n) O(n)

In computer science a palindrome tree, also called an EerTree,[1] is a type of search tree, that allows for fast access to all palindromes contained in a string. They can be used to solve the longest palindromic substring, the k-factorization problem[2] (can a given string be divided into exactly k palindromes), palindromic length of a string[3] (what is the minimum number of palindromes needed to construct the string), and finding and counting all distinct sub-palindromes. Palindrome trees do this in an online manner, that is it does not require the entire string at the start and can be added to character by character.

Description

Palindrome Tree example for TACOCAT, where solid lines are character edges and dashed lines are suffix edges

Like most trees, a palindrome tree consists of vertices and directed edges. Each vertex in the tree represents a palindrome (e.g. 'tacocat') but only stores the length of the palindrome, and each edge represents either a character or a suffix. The character edges represent that when the character is appended to both ends of the palindrome represented by the source vertex, the palindrome in the destination vertex is created (e.g. an edge labeled 't' would connect the source vertex 'acoca' to the destination vertex 'tacocat'). The suffix edge connects each palindrome to the largest palindrome suffix it possesses (in the previous example 'tacocat' would have a suffix edge to 't', and 'atacocata' would have a suffix link to 'ata'). Where palindrome trees differ from regular trees, is that they have two roots (as they are in fact two separate trees). The two roots represent palindromes of length −1, and 0. That is, if the character 'a' is appended to both roots the tree will produce 'a' and 'aa' respectively. Since each edge adds (or removes) an even number of characters, the two trees are only ever connected by suffix edges.

Operations

Add

Since a palindrome tree follows an online construction, it maintains a pointer to the last palindrome added to the tree. To add the next character to the palindrome tree, add(x) first checks if the first character before the palindrome matches the character being added, if it does not, the suffix links are followed until a palindrome can be added to the tree. Once a palindrome has been found, if it already existed in the tree, there is no work to do. Otherwise, a new vertex is added with a link from the suffix to the new vertex, and a suffix link for the new vertex is added. If the length of the new palindrome is 1, the suffix link points to the root of the palindrome tree that represents a length of −1.

# S -> Input String
# x -> position in the string of the character being added
def add(x: int) -> bool:
    """Add character to the palindrome tree."""
    while True:
        if x - 1 - current.length >= 0 and S[x - 1 - current.length] == S[x]:
            break
        current = current.suffix

    if current.add[S[x]] is not None:
        return False

    suffix = current
    current = Palindrome_Vertex()
    current.length = suffix.length + 2
    suffix.add[S[x]] = current

    if current.length == 1:
        current.suffix = root
        return True

    while True:
        suffix = suffix.suffix
        if x - 1 - suffix.length >= 0 and S[x - 1 - suffix.length] == S[x]:
            current.suffix = suffix.add[S[x]]
            return True

Joint trees

Finding palindromes that are common to multiple strings or unique to a single string can be done with additional space where is the number of strings being compared. This is accomplished by adding an array of length to each vertex, and setting the flag to 1 at index if that vertex was reached when adding string . The only other modification needed is to reset the current pointer to the root at the end of each string. By joining trees in such a manner the following problems can be solved:

  • Number of palindromes common to all strings
  • Number of unique palindromes in a string
  • Longest palindrome common to all strings
  • The number of palindromes that occur more often in one string than others

Complexity

Time

Constructing a palindrome tree takes time, where is the length of the string and is the size of the alphabet. With calls to add(x), each call takes amortized time. This is a result of each call to add(x) increases the depth of the current vertex (the last palindrome in the tree) by at most one, and searching all possible character edges of a vertex takes time. By assigning the cost of moving up and down the tree to each call to add(x), the cost of moving up the tree more than once is 'paid for' by an equal number of calls to add(x) when moving up the tree did not occur.

Space

A palindrome tree takes space: At most vertices to store the sub-palindromes and two roots, edges, linking the vertices and suffix edges.

Space–time tradeoff

If instead of storing only the add edges that exist for each palindrome an array of length edges is stored, finding the correct edge can be done in constant time reducing construction time to while increasing space to , where is the number of palindromes.

References

  1. ^ Rubinchik, Mikhail; Shur, Arseny M. (2015). "Eertree: An Efficient Data Structure for Processing Palindromes in Strings". European Journal of Combinatorics. arXiv:1506.04862v1.
  2. ^ Galil, Zvi; Seiferas, Joel (1978). "A Linear-Time On-Line Recognition Algorithm for Palstar". Journal of the ACM. 25 (1): 102–111. doi:10.1145/322047.322056. S2CID 41095273.
  3. ^ Fici, Gabriele; Gagie, Travis; Kärkkäinen, Juha; Kempa, Dominik (2014). "A subquadratic algorithm for minimum palindromic factorization". Journal of Discrete Algorithms. 28: 41–48. arXiv:1403.2431. doi:10.1016/j.jda.2014.08.001. S2CID 14871164.

Read other articles:

Dalam nama yang mengikuti kebiasaan penamaan Slavia Timur ini, patronimiknya adalah Volodymyrovych dan nama keluarganya adalah Zinchenko. Oleksandr Zinchenko Zinchenko bermain untuk Manchester City pada 2021Informasi pribadiNama lengkap Oleksandr Volodymyrovych Zinchenko[1]Tanggal lahir 15 Desember 1996 (umur 27)[2]Tempat lahir Radomyshl, UkrainaTinggi 175 cm (5 ft 9 in)[3]Posisi bermain Gelandang serangBek kiriBek sayap kiriInformasi klubKlub s...

 

This article contains content that is written like an advertisement. Please help improve it by removing promotional content and inappropriate external links, and by adding encyclopedic content written from a neutral point of view. (May 2023) (Learn how and when to remove this template message) American privacy and security researcher, computer hacker, whistleblower and entrepreneur For the surname Kamkar, see Kamkar. Samy KamkarKamkar speaking at the Black Hat conference in 2010Born (1985-12-...

 

Koridor 12 TransjakartaPluit - Tanjung PriokHalte Mangga Dua adalah salah satu halte yang melayani koridor 12InfoPemilikPT. Transportasi JakartaWilayahJakarta BaratJakarta PusatJakarta UtaraJenisStreet-level Bus Rapid TransitJumlah stasiun24 halteOperasiDimulai14 Februari 2013OperatorPT. Transportasi Jakarta (prasarana, armada, pramudi dan petugas)Mayasari Bakti (armada dan pramudi)TeknisPanjang sistem18.85 kmKecepatan rata-rata50 km/jam Peta rute(klik gambar untuk memperbesar) Peta Transjaka...

2003 single by Martina McBrideIn My Daughter's EyesSingle by Martina McBridefrom the album Martina ReleasedNovember 17, 2003 (2003-11-17)Recorded2003; Blackbird Studio(Nashville)GenreCountryLength3:15LabelRCA NashvilleSongwriter(s)James T. SlaterProducer(s) Martina McBride Paul Worley Martina McBride singles chronology This One's for the Girls (2003) In My Daughter's Eyes (2003) How Far (2004) In My Daughter's Eyes is a song written by James T. Slater and recorded by American c...

 

Series of two uncrewed Soviet spacecraft Mars 1M spacecraft Mars 1M was a series of two uncrewed spacecraft which were used in the first Soviet missions to explore Mars.[1] They were the earliest missions of the Mars program. The Western media dubbed the spacecraft Marsnik, a portmanteau of Mars and Sputnik. Spacecraft Mars 1M No.1, known in the West as Marsnik 1, Mars 1960A and Korabl 4, was destroyed in a launch failure on October 10, 1960. In 1962, NASA Administrator James E. Webb ...

 

Maracaibo Maracaibo merupakan kota terbesar kedua Venezuela. Penduduknya berjumlah 2.225.000 jiwa (2007). Kota ini memiliki luas wilayah 550 km² dengan memiliki angka kepadatan penduduk 4.045 jiwa/km². Kota ini merupakan ibu kota negara bagian Zulia. Pranala luar Wikimedia Commons memiliki media mengenai Maracaibo. (Spanyol) Maracaibo en Internet (Spanyol) Panorama Digital -Largest Maracaibo based newspaper (Spanyol) [1] Cada lugar en Maracaibo, Directorio de empresas. (Spanyol) La Ver...

Guaraní Antonio Franco Datos generalesNombre Club Deportivo Guaraní Antonio FrancoApodo(s) La FranjaFundación 12 de junio de 1932 (91 años)Presidente Patricio VedoyaEntrenador Manuel DuttoInstalacionesEstadio Clemente Fernández de OliveiraCapacidad 12.000Inauguración 15 de agosto de 1963Uniforme Titular Alternativo Última temporadaLiga Torneo Regional Federal AmateurTítulos 36 (por última vez en Clausura 2023)Copa Copa ArgentinaRegional Liga Posadeña [editar datos en ...

 

You can help expand this article with text translated from the corresponding article in Arabic. (January 2022) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accurate, rather than simply copy-pasting machine-translated text into the English Wikipedia. Do not translate text that appears unreliable or lo...

 

Star Wars: The Force AwakensSutradaraJ. J. AbramsProduser Kathleen Kennedy J. J. Abrams Bryan Burk Ditulis oleh Lawrence Kasdan J. J. Abrams Michael Arndt Pemeran Harrison Ford Mark Hamill Carrie Fisher Adam Driver Daisy Ridley John Boyega Oscar Isaac Lupita Nyong'o Andy Serkis Domhnall Gleeson Anthony Daniels Peter Mayhew Max von Sydow Yayan Ruhian Iko Uwais Penata musikJohn WilliamsSinematograferDaniel MindelPenyunting Maryann Brandon Mary Jo Markey Perusahaanproduksi Lucasfilm Ltd. B...

Questa voce sull'argomento attori statunitensi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Harry Groener Harry Groener (Augusta, 10 settembre 1951) è un attore statunitense. Indice 1 Biografia 2 Filmografia 2.1 Cinema 2.2 Televisione 3 Doppiatori italiani 4 Altri progetti 5 Collegamenti esterni Biografia Dopo la nascita in Germania, è emigrato con la sua famiglia negli Stati Uniti all'età di due...

 

Державний комітет телебачення і радіомовлення України (Держкомтелерадіо) Приміщення комітетуЗагальна інформаціяКраїна  УкраїнаДата створення 2003Керівне відомство Кабінет Міністрів УкраїниРічний бюджет 1 964 898 500 ₴[1]Голова Олег НаливайкоПідвідомчі ор...

 

Dewangga Jus sanguinelloCommon connotationsDewangga     Koordinat warnaTriplet hex#FF616BsRGBB    (r, g, b)(255, 97, 107)HSV       (h, s, v)(356°, 62%, 100%)SumberDaftar Istilah WarnaBeauty Color Code[1]B: Dinormalkan ke [0–255] (bita) Dewangga (bahasa Inggris: Grenadine pink) adalah corak warna merah kekuningan yang condong ke arah jingga. Warna ini sudah digunakan dalam tata busana sejak abad ke-19.[2] Sari jeruk darah juga ...

Jan Adriaensens Nazionalità  Belgio Ciclismo Specialità Strada Termine carriera 1961 CarrieraSquadre di club 1952 Libertas1953 Libertas Rochet1954 LibertasL'ExpressAlpa1955 Terrot Libertas1956 Mercier1957-1958 Carpano1959 Peugeot1960 Philco1961 Groene LeeuwNazionale 1953-1961 Belgio   Modifica dati su Wikidata · Manuale Jan Adriaensens (Willebroek, 6 giugno 1932 – 2 ottobre 2018) è stato un ciclista su strada belga. ...

 

Adult contemporary radio station in Wichita, Kansas KRBBWichita, KansasBroadcast areaWichita metropolitan areaFrequency97.9 MHz (HD Radio)BrandingB98ProgrammingFormatAdult contemporarySubchannelsHD2: Contemporary hit radio Kiss RadioAffiliationsPremiere NetworksOwnershipOwneriHeartMedia, Inc.(iHM Licenses, LLC)Sister stationsKTHR, KZCH, KZSNHistoryFirst air dateSeptember 19, 1948; 75 years ago (1948-09-19) (as KFH-FM)Former call signsKFH-FM (1948–1971)KBRA (1971–1982)KLZ...

 

此條目可参照英語維基百科相應條目来扩充。 (2019年4月16日)若您熟悉来源语言和主题,请协助参考外语维基百科扩充条目。请勿直接提交机械翻译,也不要翻译不可靠、低品质内容。依版权协议,译文需在编辑摘要注明来源,或于讨论页顶部标记{{Translated page}}标签。 此條目需要补充更多来源。 (2019年4月16日)请协助補充多方面可靠来源以改善这篇条目,无法查证的内容可能�...

Pour les articles homonymes, voir Burnaby (homonymie). Davy BurnabyBiographieNaissance 7 avril 1881BucklandDécès 18 avril 1949 (à 68 ans)Nationalité britanniqueFormation Haileybury and Imperial Service College (en)Activité ActeurPère Henry Fowke Burnaby (d)Conjoint Maude Lambert (d)modifier - modifier le code - modifier Wikidata Davy Burnaby ou George Davy-Burnaby (né le 7 avril 1881 à Buckland, Hertfordshire, en Angleterre - mort le 18 avril 1949 à Angmering, Sussex en Anglete...

 

لينكس جورنالLinux Journal (بالإنجليزية)[1] الشعارمعلومات عامةتصدر كل شهربلد المنشأ  الولايات المتحدة[1] التأسيس 3 يناير 1994 الاختفاء 7 أغسطس 2019[2] أول نشر 1994موقع الويب http://www.linuxjournal.com/التحريراللغة اإانجليزيةالتصنيفات حاسوبالمواضيع حاسوب — جنو/لينكس الإدارةISSN 1075-3583ت�...

 

Mexican footballer (born 1976) In this Portuguese name, the first or maternal family name is Naelson and the second or paternal family name is Matias. Sinha Sinha playing for TolucaPersonal informationFull name Antônio Naelson Matias[1]Date of birth (1976-05-23) 23 May 1976 (age 48)Place of birth Itajá, Rio Grande do Norte, BrazilHeight 1.63 m (5 ft 4 in)Position(s) Attacking midfielderYouth career1985–1993 América-RNSenior career*Years Team Apps (Gls)1998...

This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Culture of Egypt – news · newspapers · books · scholar · JSTOR (October 2023) (Learn how and when to remove this message)This article is part of a series onLife in Egypt Culture Architecture Ancient Egyptian art Contemporary Cinema Cuisine Dance Belly dance Ra...

 

It has been suggested that this article be merged into Church of the East in India. (Discuss) Proposed since September 2024. A Persian cross of 9th century AD at Kadamattom Church Several historical evidences shed light on a significant Malankara–Persian ecclesiastical relationship that spanned centuries. While an ecclesiastical relationship existed between the Saint Thomas Christians of India and the Church in Sassanid Empire (Church of the East) in the earlier centuries, closer ecclesiast...