LeetCode - Algorithms - 149. Max Points on a Line

Problem

149. Max Points on a Line

Java

1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

class Solution {
public int maxPoints(int[][] points) {
int n = 0;
for (int i = 0; i < points.length; i++) {
int m = maxCollinearPoints(points, i);
if (m > n)
n = m;
}
return n;
}

private int maxCollinearPoints(int[][] points, int idx) {
Map<BigDecimal, Integer> map = new HashMap<BigDecimal, Integer>();
int x0 = points[idx][0];
int y0 = points[idx][1];
int x = 0, y = 0;
int duplicate = 1;
int vertical = 0;
for (int i = 0; i < points.length; i++) {
if (i != idx) {
x = points[i][0];
y = points[i][1];
if (x == x0) {
if (y == y0) {
duplicate++;
}
else {
vertical++;
}
} else {
BigDecimal deltaY = BigDecimal.valueOf(y - y0);
BigDecimal deltaX = BigDecimal.valueOf(x - x0);
BigDecimal slope = deltaY.divide(deltaX, 16, RoundingMode.FLOOR);
if (map.containsKey(slope)) {
map.put(slope, map.get(slope) + 1);
} else {
map.put(slope, 1);
}
}

}
}
int max = 0;
for (Integer num : map.values()) {
if (num + duplicate > max)
max = num + duplicate;
}
if ( (vertical + duplicate) > max )
max = vertical + duplicate;
return max;
}
}

Submission Detail

  • 41 / 41 test cases passed.
  • Runtime: 14 ms, faster than 72.08% of Java online submissions for Max Points on a Line.
  • Memory Usage: 39.6 MB, less than 41.21% of Java online submissions for Max Points on a Line.

programcreek

© https://www.programcreek.com/2014/04/leetcode-max-points-on-a-line-java/

This problem can be solve by counting points that have the same slope for each point. When counting, we need to be careful about the duplicate points and points on the vertical lines.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

class Solution {
public int maxPoints(int[][] points) {
HashMap<BigDecimal, Integer> result = new HashMap<BigDecimal, Integer>();
int max = 0;

for (int i = 0; i < points.length; i++) {
int duplicate = 1;
int vertical = 0;
for (int j = i + 1; j < points.length; j++) {
//handle duplicates and vertical
if (points[i][0] == points[j][0]) {
if (points[i][1] == points[j][1]) {
duplicate++;
} else {
vertical++;
}
} else {
BigDecimal slope =
points[j][1] == points[i][1] ? BigDecimal.valueOf(0.0) : BigDecimal.valueOf(1.0 * (points[j][1] - points[i][1])).divide(BigDecimal.valueOf(points[j][0] - points[i][0]), 16,
RoundingMode.FLOOR);
if (result.get(slope) != null) {
result.put(slope, result.get(slope) + 1);
} else {
result.put(slope, 1);
}
}
}

for (Integer count : result.values()) {
if (count + duplicate > max) {
max = count + duplicate;
}
}

max = Math.max(vertical + duplicate, max);
result.clear();
}

return max;
}
}

Submission Detail

  • 41 / 41 test cases passed.
  • Runtime: 25 ms, faster than 42.00% of Java online submissions for Max Points on a Line.
  • Memory Usage: 40.4 MB, less than 20.64% of Java online submissions for Max Points on a Line.

How to get back to work after a career break - Carol Fishman Cohen - TEDxBeaconStreet - Transcript

People returning to work after a career break: I call them relaunchers. These are people who have taken career breaks for elder care, for childcare reasons, pursuing a personal interest or a personal health issue. Closely related are career transitioners of all kinds: veterans, military spouses, retirees coming out of retirement or repatriating expats. Returning to work after a career break is hard because of a disconnect between the employers and the relaunchers. Employers can view hiring people with a gap on their resume as a high-risk proposition, and individuals on career break can have doubts about their abilities to relaunch their careers, especially if they’ve been out for a long time. This disconnect is a problem that I’m trying to help solve.

Now, successful relaunchers are everywhere and in every field. This is Sami Kafala. He’s a nuclear physicist in the UK who took a five-year career break to be home with his five children. The Singapore press recently wrote about nurses returning to work after long career breaks. And speaking of long career breaks, this is Mimi Kahn. She’s a social worker in Orange County, California, who returned to work in a social services organization after a 25-year career break. That’s the longest career break that I’m aware of. Supreme Court Justice Sandra Day O’Connor took a five-year career break early in her career.

And this is Tracy Shapiro, who took a 13-year career break. Tracy answered a call for essays by the Today Show from people who were trying to return to work but having a difficult time of it. Tracy wrote in that she was a mom of five who loved her time at home, but she had gone through a divorce and needed to return to work, plus she really wanted to bring work back into her life because she loved working. Tracy was doing what so many of us do when we feel like we’ve put in a good day in the job search. She was looking for a finance or accounting role, and she had just spent the last nine months very diligently researching companies online and applying for jobs with no results.

I met Tracy in June of 2011, when the Today Show asked me if I could work with her to see if I could help her turn things around. The first thing I told Tracy was she had to get out of the house. I told her she had to go public with her job search and tell everyone she knew about her interest in returning to work. I also told her, “You are going to have a lot of conversations that don’t go anywhere. Expect that, and don’t be discouraged by it. There will be a handful that ultimately lead to a job opportunity.”

I’ll tell you what happened with Tracy in a little bit, but I want to share with you a discovery that I made when I was returning to work after my own career break of 11 years out of the full-time workforce. And that is, that people’s view of you is frozen in time. What I mean by this is, when you start to get in touch with people and you get back in touch with those people from the past, the people with whom you worked or went to school, they are going to remember you as you were before your career break. And that’s even if your sense of self has diminished over time, as happens with so many of us the farther removed we are from our professional identities. So for example, you might think of yourself as someone who looks like this. This is me, crazy after a day of driving around in my minivan. Or here I am in the kitchen. But those people from the past, they don’t know about any of this. They only remember you as you were, and it’s a great confidence boost to be back in touch with these people and hear their enthusiasm about your interest in returning to work.

There’s one more thing I remember vividly from my own career break. And that was that I hardly kept up with the business news. My background is in finance, and I hardly kept up with any news when I was home caring for my four young children. So I was afraid I’d go into an interview and start talking about a company that didn’t exist anymore. So I had to resubscribe to the Wall Street Journal and read it for a good six months cover to cover before I felt like I had a handle on what was going on in the business world again.

I believe relaunchers are a gem of the workforce, and here’s why. Think about our life stage: for those of us who took career breaks for childcare reasons, we have fewer or no maternity leaves. We did that already. We have fewer spousal or partner job relocations. We’re in a more settled time of life. We have great work experience. We have a more mature perspective. We’re not trying to find ourselves at an employer’s expense. Plus we have an energy, an enthusiasm about returning to work precisely because we’ve been away from it for a while.

On the flip side, I speak with employers, and here are two concerns that employers have about hiring relaunchers.

The first one is, employers are worried that relaunchers are technologically obsolete. Now, I can tell you, having been technologically obsolete myself at one point, that it’s a temporary condition. I had done my financial analysis so long ago that I used Lotus 1-2-3. I don’t know if anyone can even remember back that far, but I had to relearn it on Excel. It actually wasn’t that hard. A lot of the commands are the same. I found PowerPoint much more challenging, but now I use PowerPoint all the time. I tell relaunchers that employers expect them to come to the table with a working knowledge of basic office management software. And if they’re not up to speed, then it’s their responsibility to get there. And they do.

The second area of concern that employers have about relaunchers is they’re worried that relaunchers don’t know what they want to do. I tell relaunchers that they need to do the hard work to figure out whether their interests and skills have changed or have not changed while they have been on career break. That’s not the employer’s job. It’s the relauncher’s responsibility to demonstrate to the employer where they can add the most value.

Back in 2010 I started noticing something. I had been tracking return to work programs since 2008, and in 2010, I started noticing the use of a short-term paid work opportunity, whether it was called an internship or not, but an internship-like experience, as a way for professionals to return to work. I saw Goldman Sachs and Sara Lee start corporate reentry internship programs. I saw a returning engineer, a nontraditional reentry candidate, apply for an entry-level internship program in the military, and then get a permanent job afterward. I saw two universities integrate internships into mid-career executive education programs.

So I wrote a report about what I was seeing, and it became this article for Harvard Business Review called “The 40-Year-Old Intern.” I have to thank the editors there for that title, and also for this artwork where you can see the 40-year-old intern in the midst of all the college interns. And then, courtesy of Fox Business News, they called the concept “The 50-Year-Old Intern.”

(Laughter)

So five of the biggest financial services companies have reentry internship programs for returning finance professionals. And at this point, hundreds of people have participated. These internships are paid, and the people who move on to permanent roles are commanding competitive salaries. And now, seven of the biggest engineering companies are piloting reentry internship programs for returning engineers as part of an initiative with the Society of Women Engineers. Now, why are companies embracing the reentry internship? Because the internship allows the employer to base their hiring decision on an actual work sample instead of a series of interviews, and the employer does not have to make that permanent hiring decision until the internship period is over. This testing out period removes the perceived risk that some managers attach to hiring relaunchers, and they are attracting excellent candidates who are turning into great hires.

Think about how far we have come. Before this, most employers were not interested in engaging with relaunchers at all. But now, not only are programs being developed specifically with relaunchers in mind, but you can’t even apply for these programs unless you have a gap on your résumé.

This is the mark of real change, of true institutional shift, because if we can solve this problem for relaunchers, we can solve it for other career transitioners too. In fact, an employer just told me that their veterans return to work program is based on their reentry internship program. And there’s no reason why there can’t be a retiree internship program. Different pool, same concept.

So let me tell you what happened with Tracy Shapiro. Remember that she had to tell everyone she knew about her interest in returning to work. Well, one critical conversation with another parent in her community led to a job offer for Tracy, and it was an accounting job in a finance department. But it was a temp job. The company told her there was a possibility it could turn into something more, but no guarantees. This was in the fall of 2011. Tracy loved this company, and she loved the people and the office was less than 10 minutes from her house. So even though she had a second job offer at another company for a permanent full-time role, she decided to take her chances with this internship and hope for the best. Well, she ended up blowing away all of their expectations, and the company not only made her a permanent offer at the beginning of 2012, but they made it even more interesting and challenging, because they knew what Tracy could handle.

Fast forward to 2015, Tracy’s been promoted. They’ve paid for her to get her MBA at night. She’s even hired another relauncher to work for her. Tracy’s temp job was a tryout, just like an internship, and it ended up being a win for both Tracy and her employer.

Now, my goal is to bring the reentry internship concept to more and more employers. But in the meantime, if you are returning to work after a career break, don’t hesitate to suggest an internship or an internship-like arrangement to an employer that does not have a formal reentry internship program. Be their first success story, and you can be the example for more relaunchers to come.

Thank you.

All the world's a stage

by William Shakespeare

All the world’s a stage,
And all the men and women merely players;
They have their exits and their entrances,
And one man in his time plays many parts,
His acts being seven ages. At first, the infant,
Mewling and puking in the nurse’s arms.
Then the whining schoolboy, with his satchel
And shining morning face, creeping like snail
Unwillingly to school. And then the lover,
Sighing like furnace, with a woeful ballad
Made to his mistress’ eyebrow. Then a soldier,
Full of strange oaths and bearded like the pard,
Jealous in honour, sudden and quick in quarrel,
Seeking the bubble reputation
Even in the cannon’s mouth. And then the justice,
In fair round belly with good capon lined,
With eyes severe and beard of formal cut,
Full of wise saws and modern instances;
And so he plays his part. The sixth age shifts
Into the lean and slippered pantaloon,
With spectacles on nose and pouch on side;
His youthful hose, well saved, a world too wide
For his shrunk shank, and his big manly voice,
Turning again toward childish treble, pipes
And whistles in his sound. Last scene of all,
That ends this strange eventful history,
Is second childishness and mere oblivion,
Sans teeth, sans eyes, sans taste, sans everything.


“All the world’s a stage” is the phrase that begins a monologue from William Shakespeare’s pastoral comedy As You Like It, spoken by the melancholy Jaques in Act II Scene VII Line 139. The speech compares the world to a stage and life to a play and catalogues the seven stages of a man’s life, sometimes referred to as the seven ages of man.


王阳明诗十二首

王守仁,知行合一,全能大儒,明朝一哥。如《菜根谭》所言:非上上智,无了了心。👍

你未看此花时,此花与汝同归于寂。
你来看此花时,则此花颜色一时明白起来,便知此花不在你的外。
Before you see the flower, both you and the flower are in a state of isolation. When you see the flower its color and shape become clearer to you — which means that knowledge of the flower cannot exist apart from mind.

答人问道

饥来吃饭倦来眠,只此修行玄更玄。
说与世人浑不信,却从身外觅神仙。

中秋

去年中秋阴复晴,今年中秋阴复阴。
百年好景不多遇,况乃白发相侵寻。
吾心自有光明月,千古团圆永无缺。
山河大地拥情辉,赏心何必中秋节。

王门四句教

无善无恶之体,有善有恶意之动。
知善知恶是良知,为善去恶是格物。

赠阳伯

阳伯即伯阳,伯阳竟安在?
大道即人,万古未尝改。
长生在求仁,金丹非外待。
谬矣三十年,于今吾始悔。

书汪进之太极岩

始信非明镜台,须知明镜亦尘埃。
人人有个圆圈在,莫向蒲团坐死灰。

溪水

年华若流水,一去无回停。
悠悠百年内,吾道终何成!

咏良知四首示诸生

个个人有仲尼,自将闻见苦遮迷。
而今指与真头面,只是良知更莫疑。

问君何事日憧憧?烦恼场中错用功。
莫道圣门无口诀,良知两字是参同。

人人自有定盘针,万化根源总在
却笑从前颠倒见,枝枝叶叶外头寻。

无声无臭独知时,此是乾坤万有基。
抛却自家无尽藏,沿门持钵效贫儿。

示诸生

尔身各各自天真,不问求人更问人。
致良知成德业,谩从故纸费精神。
乾坤是易原非尽,心性何形得有尘?
莫道先生学禅语,此言端的为君陈。

啾啾吟

智者不惑仁不忧,君胡戚戚眉双愁?
信步行来皆坦道,凭天判下非人谋。

贈衛八處士 - Meeting With an Old Friend

杜甫,诗圣,语不惊人死不休,诗人中的贝多芬。辜鸿铭,晚清怪杰,英文最好的中国人。

贈衛八處士

杜甫

人生不相見,動如參與商。今夕複何夕,共此燈燭光!
少壯能幾時,鬓發各已蒼!訪舊半爲鬼,驚呼熱中腸。
焉知二十載,重上君子堂。昔別君未婚,兒女忽成行。
怡然敬父執,問我來何方?問答乃未已,驅兒羅酒漿。
夜雨剪春韭,新炊間黃粱。主稱會面難,壹舉累十觞。
十觞亦不醉,感子故意長。明日隔山嶽,世事兩茫茫。


Meeting With an Old Friend

Thomson

In life, friends seldom are brought near;
Like stars, each one shines in its sphere.
To-night, oh! what a happy night!
We sit beneath the same lamplight.
Our youth and strength last but a day.
You and I ah! our hairs are grey.
Friends! Half are in a better land,
With tears we grasp each other’s hand.
Twenty more years, short, after all,
I once again ascend your hall.
When we met, you had not a wife;
Now you have children, such is life!
Beaming, they greet their father’s chum;
They ask me from where I have come.
Before our say, we each have said,
The table is already laid.
Fresh salads from the garden near,
Rice mixed with millet, frugal cheer.
When shall we meet? ‘tis hard to know.
And so let the wine freely flow.
This wine, I know, will do no harm.
My old friend’s welcome is so warm.
To-morrow I go, to be whirled.
Again into the wide, wide world.


Stray Birds

by Rabindranath Tagore

6
IF you shed tears when you miss the sun, you also miss the stars.

18
WHAT you are you do not see, what you see is your shadow.

20
I CANNOT choose the best.
The best chooses me.

22
THAT I exist is a perpetual surprise which is life.

24
REST belongs to the work as the eyelids to the eyes.

25
MAN is a born child, his power is the power of growth.

40
DO not blame your food because you have no appetite.

48
The stars are not afraid to appear like fireflies.

51
YOUR idol is shattered in the dust to prove that God’s dust is greater than your idol.

52
MAN does not reveal himself in his history, he struggles up through it.

56
LIFE is given to us, we earn it by giving it.

65
TINY grass, your steps are small, but you possess the earth under your tread.

75
WE read the world wrong and say that it deceives us.

79
MAN barricades against himself.

82
LET life be beautiful like summer flowers and death like autumn leaves.

84
IN death the many becomes one; in life the one becomes many.
Religion will be one when God is dead.

90
IN darkness the One appears as uniform; in the light the One appears as manifold.

99
DEATH’S stamp gives value to the coin of life; making it possible to buy with life what is truly precious.

117
THE grass-blade is worth of the great world where it grows.

130
IF you shut your door to all errors truth will be shut out.

134
THE roots below the earth claim no rewards for making the branches fruitful.

139
TIME is the wealth of change, but the clock in its parody makes it mere change and no wealth.

149
THE world has opened its heart of light in the morning.
Come out, my heart, with thy love to meet it.

167
THE world has kissed my soul with its pain, asking for its return in songs.

176
THE water in a vessel is sparkling; the water in the sea is dark.
The small truth has words that are clear; the great truth has great silence.

193
A MIND all logic is like a knife all blade.
It makes the hand bleed that uses it.

203
THE day, with the noise of this little earth, drowns the silence of all worlds.

204
THE song feels the infinite in the air, the picture in the earth, the poem in the air and the earth;
For its words have meaning that walks and music that soars.

206
LET me not put myself wrongly to my world and set it against me.

211
GOD’s right hand is gentle, but terrible is his left hand.

217
THE service of the fruit is precious, the service of the flower is sweet, but let my service be the service of the leaves in its shade of humble devotion.

222
THE world does not leak because death is not a crack.

225
THE fountain of death makes the still water of life play.

231
SET bird’s wings with gold and it will never again soar in the sky.

242
THIS life is the crossing of a sea, where we meet in the same narrow ship.
In death we reach the shore and go to our different worlds.

248
MAN is worse than an animal when he is an animal.

252
AROUND the sunny island of Life swells day and night death’s limitless song of the sea.

268
DEATH belongs to life as birth does. The walk is in the raising of the foot as in the laying of it down.

279
WE live in this world when we love it.

282
I SHALL die again and again to know that life is inexhaustible.

284
LOVE is life in its fulness like the cup with its wine.

300
GOD waits for man to regain his childhood in wisdom.

307
LET me not shame thee, Father, who displayest thy glory in thy children.

313
WE shall know some day that death can never rob us of that which our soul has gained, for her gains are one with herself.

316
LET me live truly, my Lord, so that death to me become true.

323
I HAVE suffered and despaired and known death and I am glad that I am in this great world.


HackerRank - Regex - Assertions

© HackerRank

Positive Lookahead

regex_1(?=regex_2)

The positive lookahead (?=) asserts regex_1 to be immediately followed by regex_2. The lookahead is excluded from the match. It does not return matches of regex_2. The lookahead only asserts whether a match is possible or not.

For Example

1
c(?=o)

is matched with chocolate

Task

gooooo!

1
o(?=oo)

Negative Lookahead

regex_1(?!regex_2)

The negative lookahead (?!) asserts regex_1 not to be immediately followed by regex_2. Lookahead is excluded from the match (do not consume matches of regex_2), but only assert whether a match is possible or not.

For Example

1
c(?!o)

is matched with chocolate

Task

If S =goooo, then regex should match goooo. Because the first g is not follwed by g and the last o is not followed by o.

gooooo

1
(\S)(?!\1)

Positive Lookbehind

(?<=regex_2)regex_1

The positive lookbehind (?<=) asserts regex_1 to be immediately preceded by regex_2. Lookbehind is excluded from the match (do not consume matches of regex_2), but only assert whether a match is possible or not.

For Example

1
(?<=[a-z])[aeiou]

is matched with helo

Task

123Go!

1
(?<=[13579])\d

Negative Lookbehind

(?<!regex_2)regex_1

The negative lookbehind (?<!) asserts regex_1 not to be immediately preceded by regex_2. Lookbehind is excluded from the match (do not consume matches of regex_2), but only assert whether a match is possible or not.

For Example

1
(?<![a-z])[aeiou]

is matched with helo

Task

1o1s

1
(?<![aeiuoAEIOU]).

Resources

Regex - Subdomains - Assertions

LeetCode - Algorithms - 793. Preimage Size of Factorial Zeroes Function

Problem

793. Preimage Size of Factorial Zeroes Function

Relevant problem

An easy problem as 172. Factorial Trailing Zeroes and its solutions: https://hezhigang.github.io/2020/06/06/LeetCode-Algorithms-factorial-trailing-zeroes/

Java

Binary Search strategy

Binary search, also known as half-interval search, logarithmic search, or binary chop, is a general algorithm for linearly ordered data structure, and There are numerous variations of binary search.

Let \( f(x) \) be the number of zeroes at the end of \(x!\). We can observe that \( f(x) \) rise when \( x \equiv 0 \hspace{2mm} (mod \hspace{1mm} 5) \),
and \( f(5k)=f(5k+1)=f(5k+2)=f(5k+3)=f(5k+4) \).
\( f(x)=\lfloor \frac{x}{5} \rfloor + \lfloor \frac{x}{25} \rfloor + \cdots + \lfloor \frac{x}{5^n} \rfloor \) where \( \lfloor \frac{x}{5^n} \rfloor \geq 1 \)
This geometric sequence with common ratio \( r = \frac{1}{5} \) has a limit that can be computed from the finite sum formula \( \sum_{k=1}^{\infty} \frac{x}{5^k} = \lim_{n \to \infty}\sum_{k=1}^{n} \frac{x}{5^k} = \frac{\frac{x}{5}}{1-\frac{1}{5}} = \frac{x}{4} \), so, there is a inequality that \( \frac{x}{5} < f(x) < \frac{x}{4} \), which gives a small upper and lower bound for binary search algorithm.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public int preimageSizeFZF(int K) {
int count = 0;
long r = search_rank(K);
count = r==-1?0:5;
return count;
}

private long search_rank(long K) {
long lo = 4*K;
long hi = 5*K;
while (lo <= hi) {
long mid = lo + (hi - lo) / 2;
long y = f(mid);
if (K < y)
hi = mid - 1;
else if (K > y)
lo = mid + 1;
else
return mid;
}
return -1;
}

private long f(long x) {
long count = 0;
for (long i = 5; i <= x; i *= 5)
count += x / i;
return count;
}
}

Submission Detail

  • 44 / 44 test cases passed.
  • Runtime: 0 ms, faster than 100.00% of Java online submissions for Preimage Size of Factorial Zeroes Function.
  • Memory Usage: 35.6 MB, less than 100.00% of Java online submissions for Preimage Size of Factorial Zeroes Function.

Complexity Analysis

Time Complexity

\( O(NlogN) \) where N is the input integer such that \( f(x)=N \)

Space Complexity

\( O(1) \) as there is no extra space other than local varibles.

HackerRank - Regex - Backreferences

© HackerRank

Matching Same Text Again & Again

\group_number

This tool (\1 references the first capturing group) matches the same text as previously matched by the capturing group.

For Example

1
(\d)\1

It can match 00, 11, 22, 33, 44, 55, 66, 77, 88 or 99.

Task

ab #1?AZa$ab #1?AZa$

1
^([a-z])(\w)(\s)(\W)(\d)(\D)([A-Z])([a-zA-Z])([aeiouAEIOU])(\S)\1\2\3\4\5\6\7\8\9\10$

Backreferences To Failed Groups

Backreference to a capturing group that match nothing is different from backreference to a capturing group that did not participate in the match at all.

Capturing group that match nothing

1
(b?)o\1

is matched with o

Here, b? is optional and matches nothing.
Thus, (b?) is successfully matched and capture nothing.
o is matched with o and \1 successfully matches the nothing captured by the group.

Capturing group that didn’t participate in the match at all

1
(b)?o\1

is not matching o

In most regex flavors (excluding JavaScript), (b)?o\1 fails to match o.

Here, (b) fails to match at all. Since, the whole group is optional the regex engine does proceed to match o.
The regex engine now arrives at \1 which references a group that did not participate in the match attempt at all.
Thus, the backreference fails to match at all.

Task

12-34-56-78

12345678

1

1
^\d{2}(-?)\d{2}\1\d{2}\1\d{2}$

2

1
^\d{2}(-?)(\d{2}\1){2}\d{2}$

Branch Reset Groups

NOTE - Branch reset group is supported by Perl, PHP, Delphi and R.

(?|regex)

A branch reset group consists of alternations and capturing groups. (?|(regex1)|(regex2))
Alternatives in branch reset group share same capturing group.

1
(?|(Haa)|(Hee)|(bye)|(k))\1

is mathched with HaaHaa and kk

Task

12-34-56-78

12:34:56:78

12---34---56---78

12.34.56.78

1
/^\d{2}(?|(-)|(:)|(---)|(\.)|){1}(\d{2}\1){2}\d{2}$/

Forward References

NOTE - Forward reference is supported by JGsoft, .NET, Java, Perl, PCRE, PHP, Delphi and Ruby regex flavors.

Forward reference creates a back reference to a regex that would appear later.
Forward references are only useful if they’re inside a repeated group.
Then there may arise a case in which the regex engine evaluates the backreference after the group has been matched already.

1
(\2amigo|(go!))+

is matched with go!go!amigo

Task

tactactic

tactactictactic

1
^(\2tic|(tac))+$

Resources

Regex - Subdomains - Backreferences