• Log InLog In
  • Register
Liquid`
Team Liquid Liquipedia
EDT 19:53
CEST 01:53
KST 08:53
  • Home
  • Forum
  • Calendar
  • Streams
  • Liquipedia
  • Features
  • Store
  • EPT
  • TL+
  • StarCraft 2
  • Brood War
  • Smash
  • Heroes
  • Counter-Strike
  • Overwatch
  • Liquibet
  • Fantasy StarCraft
  • TLPD
  • StarCraft 2
  • Brood War
  • Blogs
Forum Sidebar
Events/Features
News
Featured News
[ASL21] Ro24 Preview Pt2: News Flash10[ASL21] Ro24 Preview Pt1: New Chaos0Team Liquid Map Contest #22 - Presented by Monster Energy18ByuL: The Forgotten Master of ZvT30Behind the Blue - Team Liquid History Book20
Community News
$5,000 WardiTV TLMC tournament - Presented by Monster Energy1GSL CK: More events planned pending crowdfunding0Weekly Cups (May 30-Apr 5): herO, Clem, SHIN win0[BSL22] RO32 Group Stage4Weekly Cups (March 23-29): herO takes triple6
StarCraft 2
General
BGE Stara Zagora 2026 cancelled Blizzard Classic Cup @ BlizzCon 2026 - $100k prize pool Weekly Cups (May 30-Apr 5): herO, Clem, SHIN win Rongyi Cup S3 - Preview & Info Team Liquid Map Contest #22 - Presented by Monster Energy
Tourneys
RSL Season 4 announced for March-April $5,000 WardiTV TLMC tournament - Presented by Monster Energy Sea Duckling Open (Global, Bronze-Diamond) GSL CK: More events planned pending crowdfunding Sparkling Tuna Cup - Weekly Open Tournament
Strategy
Custom Maps
[D]RTS in all its shapes and glory <3 [A] Nemrods 1/4 players [M] (2) Frigid Storage
External Content
The PondCast: SC2 News & Results Mutation # 520 Moving Fees Mutation # 519 Inner Power Mutation # 518 Radiation Zone
Brood War
General
so ive been playing broodwar for a week straight. Gypsy to Korea ASL21 General Discussion Pros React To: JaeDong vs Queen [BSL22] RO32 Group Stage
Tourneys
[BSL22] RO32 Group B - Sunday 21:00 CEST [BSL22] RO32 Group A - Saturday 21:00 CEST 🌍 Weekly Foreign Showmatches [Megathread] Daily Proleagues
Strategy
Muta micro map competition Fighting Spirit mining rates What's the deal with APM & what's its true value Simple Questions, Simple Answers
Other Games
General Games
Stormgate/Frost Giant Megathread Starcraft Tabletop Miniature Game General RTS Discussion Thread Nintendo Switch Thread Darkest Dungeon
Dota 2
The Story of Wings Gaming Official 'what is Dota anymore' discussion
League of Legends
G2 just beat GenG in First stand
Heroes of the Storm
Simple Questions, Simple Answers Heroes of the Storm 2.0
Hearthstone
Deck construction bug Heroes of StarCraft mini-set
TL Mafia
Mafia Game Mode Feedback/Ideas TL Mafia Community Thread Five o'clock TL Mafia
Community
General
US Politics Mega-thread Things Aren’t Peaceful in Palestine European Politico-economics QA Mega-thread Canadian Politics Mega-thread Russo-Ukrainian War Thread
Fan Clubs
The IdrA Fan Club
Media & Entertainment
[Manga] One Piece [Req][Books] Good Fantasy/SciFi books Movie Discussion!
Sports
2024 - 2026 Football Thread Formula 1 Discussion Cricket [SPORT] Tokyo Olympics 2021 Thread General nutrition recommendations
World Cup 2022
Tech Support
[G] How to Block Livestream Ads
TL Community
The Automated Ban List
Blogs
Loot Boxes—Emotions, And Why…
TrAiDoS
Broowar part 2
qwaykee
Funny Nicknames
LUCKY_NOOB
Iranian anarchists: organize…
XenOsky
FS++
Kraekkling
ASL S21 English Commentary…
namkraft
Electronics
mantequilla
Customize Sidebar...

Website Feedback

Closed Threads



Active: 2865 users

The Big Programming Thread - Page 859

Forum Index > General Forum
Post a Reply
Prev 1 857 858 859 860 861 1032 Next
Thread Rules
1. This is not a "do my homework for me" thread. If you have specific questions, ask, but don't post an assignment or homework problem and expect an exact solution.
2. No recruiting for your cockamamie projects (you won't replace facebook with 3 dudes you found on the internet and $20)
3. If you can't articulate why a language is bad, don't start slinging shit about it. Just remember that nothing is worse than making CSS IE6 compatible.
4. Use [code] tags to format code blocks.
Nesserev
Profile Blog Joined January 2011
Belgium2760 Posts
Last Edited: 2017-03-09 22:14:58
March 09 2017 22:03 GMT
#17161
--- Nuked ---
netherh
Profile Blog Joined November 2011
United Kingdom333 Posts
Last Edited: 2017-03-09 22:31:33
March 09 2017 22:30 GMT
#17162
On March 10 2017 07:03 Nesserev wrote:
Show nested quote +
On March 10 2017 05:09 Blisse wrote:
5-minute hard limit. Time yourself.

Find the longest palindromic substring in a list of strings.

For example, given strings: "carracecar", "aabbaa", "aabbbabab", return either "racecar" or 7.

I don't see how you could write any decent code under 5 minutes to solve this problem.


Yeah. Took me about 15 minutes to create a basic solution and realise it didn't work, 30 minutes of trying to remember how reverse_iterators work (yay C++), and another 15 minutes of fiddling around and fixing edge cases.

Googling shows there are better ways of doing this (and would be the first step anywhere other than interviews I guess...).

+ Show Spoiler +



#include <string>
#include <array>
#include <iostream>
#include <algorithm>
#include <cassert>

int main(int, char*[])
{
auto input = std::array<std::string, 9u>{ "", "a", "ab", "abc", "aa", "cac", "aabbbabab", "aabbaa", "carracecar" };

auto best = std::string();

for (auto const& s : input)
{
if (s.size() < 2u)
continue;

// won't find a longer palindrome in a shorter or equal string
if (s.size() <= best.size())
continue;

std::cout << "checking: " << s << std::endl;

for (auto i = s.begin(); std::next(i) != s.end(); ++i)
{
using RIt = std::reverse_iterator<std::string::const_iterator>;

// i is the start of a palindrome (e.g. the first 'a' in "aa")
auto even = std::mismatch(std::next(i), s.end(), RIt(std::next(i)), s.rend());

auto even_first = even.second.base();
auto even_last = even.first;
auto even_length = std::distance(even_first, even_last);

assert(even_length >= 0);
auto even_length_u = static_cast<unsigned int>(even_length);

if (even_length_u > 1 && even_length_u > best.size())
best = std::string(even_first, even_last);

// i is the middle of a palindrome (e.g. the 'a' in "cac")
auto odd = std::mismatch(std::next(i), s.end(), RIt(i), s.rend());

auto odd_first = odd.second.base();
auto odd_last = odd.first;
auto odd_length = std::distance(odd_first, odd_last);

assert(odd_length >= 0);
auto odd_length_u = static_cast<unsigned int>(odd_length);

if (odd_length_u > 1 && odd_length_u > best.size())
best = std::string(odd_first, odd_last);
}

std::cout << "best so far: " << best << " " << best.size() << std::endl;
}

std::cout << "best: " << best << " " << best.size() << std::endl;
}


slmw
Profile Blog Joined October 2010
Finland233 Posts
March 09 2017 22:36 GMT
#17163
O(N^2) per word should be simple enough to do in five minutes for anyone with a bit of competitive programming practice. O(N) is quite a bit tougher with all the index fiddling and potential one off errors.
Khalum
Profile Joined September 2010
Austria831 Posts
Last Edited: 2017-03-10 01:19:30
March 10 2017 01:18 GMT
#17164
5 minutes are more than enough for a trivial approach. It won't be pretty but it should work.

I'm curious why the string as well as the length are valid outputs. The approach is the same?
meatpudding
Profile Joined March 2011
Australia520 Posts
March 10 2017 01:25 GMT
#17165
This took me 7 minutes and it still doesn't quite work. Basic idea is to "fan out" both ways from each character and stop when the palindrome ends. Store the longest palindrome word and print it.

def palin(s):
longest_n = 0
longest_start = 0
start = 0
end = 0
for i in range(len(s)):
start = i
end = i
while (s >= 0 and end < len(s)):
if (s[start] == s[end]):
n = end - start + 1
if (n > longest_n):
longest_n = n
longest_start = start
else:
break
start -= 1
end += 1

print longest_n, s[longest_start:longest_start + longest_n]


palin("carracecar")
palin("aabbaa")
palin("aabbbabab")


Output:

7 racecar
3
5 abbba


I only just realised that this will only work for odd palindromes.
Be excellent to each other.
tofucake
Profile Blog Joined October 2009
Hyrule19201 Posts
March 10 2017 01:43 GMT
#17166
I just had an interview today with a palindrome question. In JS it takes about 30 seconds to read the instructions, think, then type out

function isPalindrome(possiblePalindrome) {
return possiblePalindrome == possiblePalindrome.split('').reverse().join('').toString();
}


making it support an array and finding the longest palindrome of the bunch is another 2 minutes :\
Liquipediaasante sana squash banana
Hanh
Profile Joined June 2016
146 Posts
March 10 2017 01:55 GMT
#17167
Still too long! Heh

 
let is_palindrome s = rev s = s
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-10 02:33:28
March 10 2017 02:24 GMT
#17168
This is what I did. took 15-20 min cuz i kept making stupid mistakes



public static int find(ArrayList<String> words) {
int size = 1;
int total = 0;
for(String w : words) {

for(int i = 0; i < w.length() - 1; i++) {
int front = 1, back = 1;
while(((i - back >= 0) && (i + front <= w.length() - 1) && (w.charAt(i + front) == w.charAt(i - back)))) {
size += 2;
back++;
front++;
}
if (size > total) {
total = size;
}
size = 1;
}
}
return total;
}



pretty sure this is O(n) unless we are dealing with the longest strings of all time

I didn't record the actual string because blisse said I didn't have to. but I could if I needed to it would just be a very mildly painful addition

edit: I guess slmw was talking about beating O(n^2) per word, which makes more sense because why would you have to iterate through words more than once

So looking at the complexity of this per word... mmmm..
I really am not sure? I guess it's technically O(n^2) but it's like a really good O(n^2), and that's worst case.

maybe someone who is good at complexity could look at this and tell me what the complexity per word is?
slmw
Profile Blog Joined October 2010
Finland233 Posts
March 10 2017 02:37 GMT
#17169
Simplest O(N^2) per word implementation I could think of, very similar to your python solution. O(N) per word was quite a bit tougher to do and definitely over 5 minutes. :D

On March 10 2017 10:18 Khalum wrote:
I'm curious why the string as well as the length are valid outputs. The approach is the same?


It's just basically a matter of formatting the output.

On March 10 2017 10:43 tofucake wrote:
I just had an interview today with a palindrome question. In JS it takes about 30 seconds to read the instructions, think, then type out

function isPalindrome(possiblePalindrome) {
return possiblePalindrome == possiblePalindrome.split('').reverse().join('').toString();
}


making it support an array and finding the longest palindrome of the bunch is another 2 minutes :\


You gotta still create all the substrings though so a bit more programming left to do!. Also this is O(N^3) per word!

On March 10 2017 11:24 travis wrote:
This is what I did. took 15-20 min cuz i kept making stupid mistakes



public static int find(ArrayList<String> words) {
int size = 1;
int total = 0;
for(String w : words) {

for(int i = 0; i < w.length() - 1; i++) {
int front = 1, back = 1;
while(((i - back >= 0) && (i + front <= w.length() - 1) && (w.charAt(i + front) == w.charAt(i - back)))) {
size += 2;
back++;
front++;
}
if (size > total) {
total = size;
}
size = 1;
}
}
return total;
}



pretty sure this is O(n) unless we are dealing with the longest strings of all time

I didn't record the actual string because blisse said I didn't have to. but I could if I needed to it would just be a very mildly painful addition

edit: I guess slmw was talking about beating O(n^2) per word, which makes more sense because why would you have to iterate through words more than once

So looking at the complexity of this per word... mmmm..
I really am not sure? I guess it's technically O(n^2) but it's like a really good O(n^2), and that's worst case.


This is O(N^2) per word, but doesn't it work just for odd palindromes? https://ideone.com/ke4q0k
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-10 02:39:50
March 10 2017 02:38 GMT
#17170
oh duh of course it only works for odd palindromes

looking up i probably did whatever meatpudding was doing

tbh I never even realized it was a palindrome if it wasn't odd, lol. the problem would be a million times harder for me including even palindromes

basically I'd be writing all separate code to handle even palindromes
it'd still be O(n^2) though
WarSame
Profile Blog Joined February 2010
Canada1950 Posts
March 10 2017 05:11 GMT
#17171
Do any of you know a good place to go for code review? I want to have my git repo checked to see if there are better coding decisions I could have made. Is there some sort of dedicated area or site for that?
Can it be I stayed away too long? Did you miss these rhymes while I was gone?
ShoCkeyy
Profile Blog Joined July 2008
7815 Posts
March 10 2017 05:57 GMT
#17172
WarSame depending on the language, you can ask some one in the freenode irc chat. I'm sure some one there or here would be willing to review.
Life?
Hanh
Profile Joined June 2016
146 Posts
March 10 2017 06:05 GMT
#17173
On March 10 2017 11:38 travis wrote:
oh duh of course it only works for odd palindromes

looking up i probably did whatever meatpudding was doing

tbh I never even realized it was a palindrome if it wasn't odd, lol. the problem would be a million times harder for me including even palindromes

basically I'd be writing all separate code to handle even palindromes
it'd still be O(n^2) though


Don't worry too much about performance. Focus on correctness first. There is no point in returning a wrong result quickly.
Looking back at this thread, the people who talk about how easy the question is have yet to give a good answer.
Manit0u
Profile Blog Joined August 2004
Poland17717 Posts
March 10 2017 08:04 GMT
#17174
On March 10 2017 14:11 WarSame wrote:
Do any of you know a good place to go for code review? I want to have my git repo checked to see if there are better coding decisions I could have made. Is there some sort of dedicated area or site for that?


What language? I love code reviews
Time is precious. Waste it wisely.
Cynry
Profile Blog Joined August 2010
810 Posts
Last Edited: 2017-03-10 12:04:29
March 10 2017 08:56 GMT
#17175
Anyone here knows golang, and have used the mongodb official drivers (mgo) ?
I've been working for almost 2 years with mongo in js without an issue, but ever since I started go every single query that I have to do is a pain in the ass.

It's my first project in go, soooo todolist it is !
And here's the query that is driving me nuts lately:
func (u *User) getNextTask(date time.Time) (Task, error) {
task := Task{}
query := bson.M{
"id": bson.M{"$in": u.Tasks},
"timestamp": bson.M{"$gte": date},
}
err := Tasks.Find(query).Sort("timestamp").Limit(1).One(&task)
if err != nil {
return task, err
}
return task, nil
}

Simply receives a date, get the tasks that have been created after, sort them by ascending order to get the next one, limit to one result, etc. It doesn't even get here anyway.
The query doesn't return anything, although everything I've checked is correct. I receive a proper date, u.Tasks does contain an array of bson.ObjectIds (the query works when I remove the timestamp part, so this is fine). There is at the moment of the tests, at least a task that has should match the query (same user, created after, can be checked if I do the same query without the timestamp part).
So it apparently comes from that very line

"timestamp": bson.M{"$gte": date},

but I can't see what's wrong with it. At this point I suspect a typo or something silly like that, but I seem to need an exterior look... So, anyone ?

Palindrome challenge: All I could come up in 5 minutes was some pseudo code that didn't work for odd palindromes... forgot about those ^^
Khalum
Profile Joined September 2010
Austria831 Posts
Last Edited: 2017-03-10 10:39:13
March 10 2017 10:34 GMT
#17176
On March 10 2017 15:05 Hanh wrote:
[..]
Looking back at this thread, the people who talk about how easy the question is have yet to give a good answer.



Fair point! I had just come home from a night of drinking and would definately not have given a good answer then
Am still a bit drunk but I gave it a shot to put my money where my mouth was. My solution is probably not correct. I hacked it in 7 minutes (yes, more than 5...) so I guess I failed anyways. Now back to sleep.


int palindromeLength(string s)
{
for (int i=0; i<s.length()/2; ++i)
{
if (s[i] != s[s.length()-1-i])
{
return 0;
}
}
return s.length();
}

int getLongestPalindrome(string s)
{
int maxLen = 0;
for (string::iterator ita=s.begin(); ita<s.end()-maxLen-1; ++ita)
{
for (string::iterator itb=ita+maxLen+1; itb<s.end(); ++itb)
{
maxLen = max(maxLen, palindromeLength(string(ita,itb)));
}
}
return maxLen;
}



[edit]
This is missing a function that calls getLongestPalindrome() with some strings to be tested and collects the max of these.

[edit2]
Fixed 2 errors. Yes, I cheat.
netherh
Profile Blog Joined November 2011
United Kingdom333 Posts
Last Edited: 2017-03-10 13:46:06
March 10 2017 13:42 GMT
#17177
On March 10 2017 14:11 WarSame wrote:
Do any of you know a good place to go for code review? I want to have my git repo checked to see if there are better coding decisions I could have made. Is there some sort of dedicated area or site for that?


Well there's this:

http://codereview.stackexchange.com/

I think you're supposed to include code in the question though, so depends on how large your repo is, or if you can extract specific bits of code.
Deleted User 3420
Profile Blog Joined May 2003
24492 Posts
Last Edited: 2017-03-10 14:09:55
March 10 2017 14:04 GMT
#17178
Situation in C:

I want to pass a char pointer to a function.
Then go through the memory, and find integers.
Store those integers into a character array.
And then return the pointer to the new character array (that only holds the integers).

But because my character array is local to the function it becomes garbage when my function ends, so this doesn't work
But I am not supposed to use dynamic memory allocation, and im not supposed to use global variables

so how do I do what I am describing?


edit: is what I need to do, to declare my character array before i call my function, and then pass a pointer to it to my function? god I hate C
slmw
Profile Blog Joined October 2010
Finland233 Posts
March 10 2017 14:17 GMT
#17179
If you allocate an array on the stack it gets cleaned up when you exit the function scope. If you allocate it on the heap, you're responsible for cleaning it up. If you need to do it on the stack, do everything before you exit the stack scope. It isn't that different from other languages.
waffelz
Profile Blog Joined June 2012
Germany711 Posts
March 10 2017 16:05 GMT
#17180
On March 09 2017 05:57 Nesserev wrote:
Show nested quote +
On March 09 2017 05:01 waffelz wrote:
Can someone recommend a good ARM-emulator, preferably with some tools to inspect memory etc, support of C would be nice too but not a must. OS would be preferably windows, but linux would work too.

Have you checked out qemu yet? (http://www.qemu-project.org/)


I haven't, but I will check it out, Thanks for the suggestion.
RIP "The big travis CS degree thread", taken from us too soon | Honourable forum princess, defended by Rebs-approved white knights
Prev 1 857 858 859 860 861 1032 Next
Please log in or register to reply.
Live Events Refresh
Next event in 7m
[ Submit Event ]
Live Streams
Refresh
StarCraft 2
SpeCial 189
ViBE62
StarCraft: Brood War
GuemChi 3904
Artosis 563
Noble 13
Dota 2
monkeys_forever400
capcasts156
League of Legends
JimRising 441
Counter-Strike
Coldzera 1797
Super Smash Bros
hungrybox299
C9.Mang0241
Mew2King84
AZ_Axe78
Other Games
summit1g19005
Day[9].tv521
ROOTCatZ72
Organizations
Other Games
gamesdonequick756
BasetradeTV138
StarCraft 2
Blizzard YouTube
StarCraft: Brood War
BSLTrovo
sctven
[ Show 21 non-featured ]
StarCraft 2
• RyuSc2 49
• davetesta10
• mYiSmile18
• CranKy Ducklings SOOP6
• IndyKCrew
• sooper7s
• AfreecaTV YouTube
• Migwel
• intothetv
• LaughNgamezSOOP
• Kozan
StarCraft: Brood War
• blackmanpl 29
• HerbMon 10
• BSLYoutube
• STPLYoutube
• ZZZeroYoutube
Dota 2
• masondota21507
League of Legends
• Doublelift4144
Other Games
• imaqtpie1204
• Scarra697
• Day9tv521
Upcoming Events
Replay Cast
7m
CranKy Ducklings9
The PondCast
10h 7m
CranKy Ducklings
1d
WardiTV Team League
1d 11h
Replay Cast
2 days
CranKy Ducklings
2 days
WardiTV Team League
2 days
uThermal 2v2 Circuit
2 days
BSL
2 days
n0maD vs perroflaco
TerrOr vs ZZZero
MadiNho vs WolFix
DragOn vs LancerX
Sparkling Tuna Cup
3 days
[ Show More ]
WardiTV Team League
3 days
OSC
3 days
BSL
3 days
Sterling vs Azhi_Dahaki
Napoleon vs Mazur
Jimin vs Nesh
spx vs Strudel
Replay Cast
4 days
Replay Cast
4 days
Wardi Open
4 days
GSL
5 days
Replay Cast
6 days
Kung Fu Cup
6 days
Liquipedia Results

Completed

CSL Elite League 2026
RSL Revival: Season 4
NationLESS Cup

Ongoing

BSL Season 22
ASL Season 21
CSL 2026 SPRING (S20)
StarCraft2 Community Team League 2026 Spring
Nations Cup 2026
PGL Bucharest 2026
Stake Ranked Episode 1
BLAST Open Spring 2026
ESL Pro League S23 Finals
ESL Pro League S23 Stage 1&2
PGL Cluj-Napoca 2026
IEM Kraków 2026
BLAST Bounty Winter 2026

Upcoming

Escore Tournament S2: W2
IPSL Spring 2026
Escore Tournament S2: W3
Acropolis #4
BSL 22 Non-Korean Championship
CSLAN 4
Kung Fu Cup 2026 Grand Finals
HSC XXIX
uThermal 2v2 2026 Main Event
RSL Revival: Season 5
WardiTV TLMC #16
IEM Cologne Major 2026
Stake Ranked Episode 2
CS Asia Championships 2026
Asian Champions League 2026
IEM Atlanta 2026
PGL Astana 2026
BLAST Rivals Spring 2026
CCT Season 3 Global Finals
IEM Rio 2026
TLPD

1. ByuN
2. TY
3. Dark
4. Solar
5. Stats
6. Nerchio
7. sOs
8. soO
9. INnoVation
10. Elazer
1. Rain
2. Flash
3. EffOrt
4. Last
5. Bisu
6. Soulkey
7. Mini
8. Sharp
Sidebar Settings...

Advertising | Privacy Policy | Terms Of Use | Contact Us

Original banner artwork: Jim Warren
The contents of this webpage are copyright © 2026 TLnet. All Rights Reserved.