https://leetcode.com/ashagraev/ Открыл для себя leetcode. Вообще-то он позиционируется...

https://leetcode.com/ashagraev/

Открыл для себя leetcode.

Вообще-то он позиционируется как ресурс для подготовки к собеседованиям. Задачки там тегированы компаниями, которые такие задачи на собеседованиях задают, для каждой задачки есть информация о том, как часто её задают на собеседованиях, и вообще они даже специальную книжку для подготовки к собеседованиям написали.

Собеседоваться мне никуда не нужно, но понял несколько плюсов от такой направленности ресурса:
1. Задачи намного ближе к проблематике, встречающеся в реальном продакшене. Действительно, именно такие задачи и приходится решать по сто раз на дню, когда пишешь очередной data mining. И они, конечно, несравненно ближе к продакшену, чем задачки с codeforces/projecteuler/etc. Например, есть задача про реализацию LRU- и LFU-кешей, есть про сериализацию/десериализацию, куча задачек на деревья и т.п. Стандартные brainteaser'ы тоже представлены во множестве.
2. Есть группировка по "темам" (строки, хеш-таблицы, деревья и т.п.). Это оказалось очень крутой темой и я для себя внезапно открыл несколько существенных пробелов в скиллах - например, оказалось, что я никогда в жизни не писал кода про связанные списки, и поэтому в соответствующей области у меня провал, код получается очень плохой. Короче говоря, даже на easy-задачах я нашел, чему поучиться - это здорово.
3. После решения каждой задачи можно посмотреть время ее исполнения и сравнить с решениями других участников. Взять самое быстрое и посмотреть, что умеет автор и чего не умеешь ты. Например, я узнал, что задачу про majority element (https://leetcode.com/problems/majority-element/#/description) можно решать вот так: https://pastebin.com/3hyChCWc. Вот честное слово, не знал этого никогда и всегда решал через битики, хотя задача абсолютно классическая. Вообще, одно из самых полезных упражнений в программировании - разгонять, разгонять свой код до посинения, пока узких мест не останется. В этом процессе постоянно чему-то новому учишься - алгоритмам, оптимизации и т.п. К счастью, на leetcode такая возможность есть и ярко бросается в глаза.
4. Иногда есть авторские решения, и там тоже бывает чего почитать. Приятно и то, что в некоторых ситуациях я знаю больше, чем там написано - например, если знать, что такое disjoint set union, можно решить сразу пачку однотипных задач на связность, некоторые из которых при этом считаются достаточно сложными.
5. Еще там есть не только алгоритмические задачки, а еще и задачи на базы данных, bash и еще всякое. Ненавижу SQL, а вот решение всех четыре задач на bash мне доставило огромное удовольствие. В работе bash'ем лучше не пользоваться, но всё равно, когда берёшь его в руки, есть ощущение какой-то магии. Например, написать на awk транспонирование матрицы ( https://leetcode.com/problems/transpose-file/#/description) - что может быть романтичнее? :)
6. Направленность на интервью действительно работает. В промышленном коде часто подразумеваются некоторые инварианты, которые в "дикой природе" уже неверны. Так, увидев int, надо сразу подумать, что он же может быть и отрицательным (в тех задачах, которые в продакшене, как правило, принимают unsigned, и мозг уже настроен на это), а все указатели во всех местах надо проверить на nullptr. Еще надо всегда тестировать особенный corner case - задачу минимального размера (скажем, пустой список на входе) - такое тоже в продакшене нечасто встретишь. Мне видится, что это всё действительно полезно даже для опытных программистов, которые готовятся к собеседованию или просто не хотят слишком сильно отрываться от реальной жизни.

В общем, всячески рекомендую - кажется, профессиональный программист должен решать, хотя бы поначалу, задачки оттуда пачками и за короткое время, а начинающий - стремиться научиться делать примерно всё, что там написано, это значительно повысит шансы хорошего оффера :) Если говорить о студентах, то их главная проблема - отсутствие большого количества написанного за жизнь кода, из-за чего им тяжело живётся. Вот есть отличный ресурс для того, чтобы с этой проблемой справиться.

По состоянию на сейчас у меня 88 решённых задач. Надеюсь, со временем я все-таки добью easy/medium секции, и тогда вот и начнётся жара.
https://leetcode.com/ashagraev/
 
I discovered leetcode.
 
In fact, it is positioned as a resource for preparing for interviews. Tasks there are tagged by companies that ask such tasks at interviews, for each task there is information about how often it is asked at interviews, and in general they even wrote a special book to prepare for interviews.
 
I don’t need to interview anywhere, but I realized a few pluses from this orientation of the resource:
1. Tasks are much closer to the problems encountered in real production. Indeed, it is precisely such tasks that have to be solved a hundred times a day when you write the next data mining. And they, of course, are incomparably closer to production than tasks with codeforces / projecteuler / etc. For example, there is a task about implementing LRU and LFU caches, there is about serialization / deserialization, a bunch of tasks on trees, etc. Standard brainteasers are also represented in a multitude.
2. There is a grouping by "topics" (strings, hash tables, trees, etc.). This turned out to be a very cool topic and for myself I suddenly discovered several significant gaps in skills - for example, it turned out that I had never written code about linked lists in my life, and therefore I have a failure in the corresponding area, the code is very bad. In short, even on easy tasks, I found something to learn - it's great.
3. After solving each problem, you can see the time of its execution and compare with the solutions of other participants. Take the fastest and see what the author can and what you can not. For example, I found out that the problem about majority element (https://leetcode.com/problems/majority-element/#/description) can be solved like this: https://pastebin.com/3hyChCWc. Here is my word of honor, I never knew this and always solved it through beatiks, although the task is absolutely classical. In general, one of the most useful exercises in programming is to overclock, overclock your code until it turns blue, until there are no bottlenecks. In this process, you are constantly learning something new - algorithms, optimization, etc. Fortunately, there is such an opportunity on leetcode and is strikingly striking.
4. Sometimes there are copyright solutions, and there are also things to read there. It is also pleasant that in some situations I know more than what is written there - for example, if you know what a disjoint set union is, you can immediately solve a bunch of similar problems of connectivity, some of which are considered quite complicated.
5. Still there are not only algorithmic problems, but also tasks on databases, bash and all sorts of other things. I hate SQL, but the solution to all four bash tasks was a real pleasure for me. It’s better not to use bash in work, but anyway, when you pick it up, you have a feeling of some kind of magic. For example, to write matrix transposition on awk (https://leetcode.com/problems/transpose-file/#/description) - what could be more romantic? :)
6. Focusing on the interview really works. In industrial code, some invariants are often implied which in the wild are already incorrect. So, when you see an int, you should immediately think that it can be negative (in those tasks that, in production, they usually accept unsigned, and the brain is already configured for this), and all pointers in all places should be checked for nullptr. You also need to always test the special corner case - the minimum size task (say, an empty input list) - this is also rarely seen in production. It seems to me that all this is really useful even for experienced programmers who are preparing for an interview or simply do not want to break away too much from real life.
 
In general, I recommend it in every way - it seems that a professional programmer should solve the problems from there in batches and in a short time, and the beginner should strive to learn how to do just about everything that is written there, this will significantly increase the chances of a good offer :) If we talk about students , then their main problem is the lack of a large amount of code written for life, which is why it is hard for them to live. Here is an excellent resource to deal with this problem.
 
As of right now I have 88 solved problems. I hope that over time I will finish the easy / medium section, and then the heat will begin.
У записи 11 лайков,
0 репостов,
673 просмотров.
Эту запись оставил(а) на своей стене Алексей Шаграев

Понравилось следующим людям